paritytech / oo7

The Bonds framework along with associated modules.
53 stars 15 forks source link

add nodejs example for oo7-substrate #102

Open brenzi opened 5 years ago

brenzi commented 5 years ago

As I was missing an example on how to use oo7-substrate with nodejs to call some runtime function, I hacked one up. Would be great if you could include this (and possibly more interesting examples)

const util = require('util');
var substrate = require('oo7-substrate');
//window=global;

//substrate.setNodeUri(['wss://substrate-rpc.parity.io/']); // charred cherry
//substrate.setNodeUri(['wss://poc3-rpc.polkadot.io/']); // alexander
substrate.setNodeUri(['ws://127.0.0.1:9944/']); // local

// track chain height
var chain = substrate.chain;
chain.height.tie((height) =>{
    console.log('[chain height] '+height);
} )

// register accounts
var system = substrate.system;
var secretstore = substrate.secretStore();
// if running a plain substrate node, alice will have genesis hard-coded funds 
var alice_seed = '0x416c696365202020202020202020202020202020202020202020202020202020';
var alice_accountid = secretstore.submit(alice_seed, 'Alice');
// new acount without funds
var newbie_seed = '0x4e65776269652020202020202020202020202020202020202020202020202020';
var newbie_accountid = secretstore.submit(newbie_seed, 'Newbie');

// sign some string
var msg = new util.TextEncoder().encode('this is true');
var msg_sig = secretstore.sign(alice_accountid, msg);

// populate runtime (query RPC)
substrate.runtimeUp.then(() => {
    var runtime = substrate.runtime
    var calls = substrate.calls
    var post = substrate.post
    // track Alice's balance
    runtime.balances.freeBalance(alice_accountid).tie((bal)=>{
        console.log('[Alice balance] '+bal);
    } ) 
    // track Newbie's balance
    runtime.balances.freeBalance(newbie_accountid).tie((bal)=>{
        console.log('[Newbie balance] '+bal);
    } )
    // send funds and track tx progress
    post({sender: alice_accountid, call: calls.balances.transfer(newbie_accountid, 1000000)}).tie((data) =>{
        if (data.finalised) {
            console.log('>>> tx finalized')
        } 

    } )
} )
brenzi commented 5 years ago

might help with https://github.com/paritytech/substrate/issues/578