Steem-lib Guide [Part2]

in #steem-lib8 years ago (edited)

Previous: Steem-lib Guide [Part1]

This section is about transaction construction, signing and broadcast.


Set Keys

Set a privatekey(WIF) as signingkey for an account.

var MY_ACCOUNT = "my-account-name";
var MY_KEY = "wif*****";

remote.set_key(MY_ACCOUNT, MY_KEY)

this will cache the key into the client for later use of signing. The first argument (MY_ACCOUNT) is a label for the privatekey, could be arbitrary string but is convenient/intuitive by using just account name.

Alternate set-up, using Steemit's username + password
remote.set_auth('my-account-name', 'my-dummy-password');

this method will generate all keys from username + password, and cache them into the client.


Construct a transaction

// create a tx with MY_ACCOUNT as signer
var tx = remote.transaction(MY_ACCOUNT);

tx.add_operation('transfer', {
    from: MY_ACCOUNT,
    to: "the-recipient-account",
    amount: "1.000 STEEM",
    memo: "payment for xxx" 
});

// to manually set expiration, e.g. 30s.
tx.expiration = Math.ceil(Date.now()/1000 + 30);

For the full list of supported operations, have a look into operation.js

optional steps:

  • tx.complete() - to auto-complete the transaction with expiration = 60s later, fill the ref_block_num and ref_block_prefix fields with infos of last-irreversible-block.
  • tx.sign() - do the signing with private-key (of MY_ACCOUNT).
    in the case where set_auth() method was used instead of set_key(), the client would choose the appropriate key according to result of 'get_required_signature' API.

Broadcast transaction

There are two methods to accomplish this, both doing the similar jobs:

  • if the transaction is incompleted, perform tx.complete(); then tx.sign();
  • send the transaction out to all connected servers.

tx.broadcast() will callback immediately when the txn got into a head-block, or if there's an error.

// show immediate result whether the tx is included in a head block
tx.broadcast(function(err, res){
  // immedate result from broadcast_api.
  console.log(err, res)
})

tx.submit() will not callback until the txn was seen in an irreversible-block.

tx.submit(function(err, res){
  if (err) return console.log('Error:', err);
  if (res) console.log('Success & Final');
});

// broadcast result is still availabe by listening to 'submitted' event.
tx.once('submitted', function(err, res){
  // head-block result
  console.log(err || res)
})

More Example:

Check the examples folder of the repository.


Next: Steem-lib Guide [Part3]

Coin Marketplace

STEEM 0.20
TRX 0.25
JST 0.038
BTC 98646.90
ETH 3511.62
USDT 1.00
SBD 2.98