【问题标题】:Cannot change storage from Polkadot API无法从 Polkadot API 更改存储
【发布时间】:2021-08-19 09:06:38
【问题描述】:

我制作了一个基于基板的项目,并使用 polkadot.js 在节点 js 中创建了一个应用程序,但代码不会更改我的基板链中的存储。

index.js

// Import
const express = require('express');
const { ApiPromise, WsProvider } = require('@polkadot/api');
var crypto = require('crypto');
const app = express();
app.get('/index', (req, res) =>{
    async function digestMessage(message) {
        try{
            
            const hash = await crypto.createHash('sha256',message).digest('hex');
            return hash;
        }
        catch(error){
            console.log(error);
        }
        
      }
      
    async function main(){
    
    
        // Construct
        const wsProvider = new WsProvider('ws://127.0.0.1:9944');
    
        const api = await ApiPromise.create({ provider: wsProvider,
            rpc: {
                carpooling: {
                  getDriver: {
                    description: 'Just a test method',
                    params: [],
                    type: "u32",
                  }}},
            types: {
                DriverOf: {
                    id: 'u32',
                    car_no: 'Hash',
                    location: ('u32', 'u32'),
                    price: 'u32',
                },
                CustomerOf: {
                    id: 'u32',
                    name: 'Hash',
                    location: ('u32', 'u32'),
                },
              }
        });
        
        try{
            const cabNo = 'UP76 E 8550';
            const output = digestMessage(cabNo);
            output.then((hash)=>{
                api.tx.carpooling.addNewCab(12,{id:12, car_no: hash,location: (10,20), price: 50});
            })
            
            let booked = api.tx.carpooling.bookRide(12, 45);
            console.log(`The output from bookRide is ${booked}`);
            let directSum = await api.rpc.carpooling.getDriver();
            console.log(`The customerID from the RPC is ${directSum}`);
            
        }
        catch(error){
            console.log(error);
        }
    
    }   
    main().then(() => console.log('completed'));
    res.send("Done");
});
app.listen(6069);

以下代码在Pallets/carpooling/lib.rs

bookRide 调度电话

#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
        pub fn book_ride(origin: OriginFor<T>, driver_id: u32, customer_id: u32) -> DispatchResult {
            // Check that the extrinsic was signed and get the signer.
            // This function will return an error if the extrinsic is not signed.
            // https://substrate.dev/docs/en/knowledgebase/runtime/origin
            let who = ensure_signed(origin)?;
            ensure!(
                <Driver<T>>::contains_key(&driver_id),
                Error::<T>::DriverDoesNotExist
            );
            ensure!(
                !(<Booking<T>>::contains_key(&driver_id)),
                Error::<T>::CabIsAlreadyBooked
            );
            <Booking<T>>::insert(&driver_id, &customer_id);
            Self::deposit_event(Event::CabBooked(who, driver_id));
            Ok(().into())
        }

DriverOf 结构

type DriverOf<T> = SDriver<<T as frame_system::Config>::Hash>;
    #[derive(Encode, Decode, Copy, Clone, Default, PartialEq, RuntimeDebug)]
    pub struct SDriver<Hash> {
        pub id: u32,
        pub car_no: Hash,
        pub location: (u32, u32),
        pub price: u32,
        pub destination: (u32, u32),
    }

nodejs 中的应用不会改变存储。我使用返回 None 的 RPC 查询存储。任何人都可以帮助我吗?

更新代码

...

try{
            const cabNo = 'UP76 E 8550';
            const output = digestMessage(cabNo);
            output.then(async (hash)=>{
                const addDriver = api.tx.carpooling.addNewCab(12,{id:12, car_no: hash,location: (10,20), price: 50,destination: (30,40)});
                const out = await addDriver.signAndSend(alice);
            }).catch((e)=>{
                console.log(e);
            })
            
            let booked = api.tx.carpooling.bookRide(12, 99);
            
            
            const hash = await booked.signAndSend(alice);
            let bookedCust = await api.rpc.carpooling.getDriver();
            console.log(`The customerID from the RPC is ${bookedCust}`);
            
}
catch(error){
            console.log(error);
}
    
   
... 

【问题讨论】:

    标签: rust substrate


    【解决方案1】:

    在我看来,这里的问题是您实际上并没有提交执行book_ride 的事务。

    你写的代码是:

    let booked = api.tx.carpooling.bookRide(12, 45);
    

    但这实际上并没有做任何事情。要实际提交外部,您需要signAndSubmit 交易:

    // Sign and send the transaction using our account
    const hash = await booked.signAndSend(alice);
    

    有关更多上下文,请查看此处的示例和文档:

    https://polkadot.js.org/docs/api/examples/promise/make-transfer

    【讨论】:

    • 我已经发布了有问题的更新代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    相关资源
    最近更新 更多