HRC20 With Hydrachainjs
HRC20 With Hydrachainjs
In this chapter we will use HydrachainJS to build a NodeJS CLI tool to interact with the HRC20 token we deployed previously.
You can download the project code: https://github.com/hydra-chain/hydrajs-token-cli
Note On NodeJS Compatibility
You'll need a version of node that supports async/await. You should be ok if your version number is greater than 8.
My version is 8.6 (nothing special about this version...):
node --version
v8.6.0I recommend that you download the Long Term Support version (8.9.3):
You can test whether async/await is supported or not by entering into the node REPL:
$ nodeThen create an async function:
> async () => { }
[AsyncFunction]If for some reason you need to run hydrajs on a platform that does not support async/await, please create an issue.
Note on Code Editor
For modern JavaScript development, you really owe it to yourself to try VSCode. hydrachainjs comes with static type definitions for its API, and with VSCode you get some of the most useful IDE features (e.g. type-accurate autocomplete) without the UX bloat:
It is recommended to try TypeScript too. JavaScript is in fact an extremely powerful language. TypeScript is the sobered-up version, yet retaining the same dynamism and expressivity that JavaScript developers love.
Setup The HRC20 CLI Project
Let's clone the NodeJS project to the directory mytoken-js:
The project dependencies are listed in package.json:
Install these dependencies:
Or
yarn installif you prefer that. See: https://yarnpkg.com/en/docs/install
Getting The Total Supply
Let's try to get the token's total supply. Run the script index.js:
Oops, the script needs to load information about the contracts you have deployed.
The
requirefunction loadssolar.jsonas a JavaScript object.
You should link (or copy) solar.development.json generated in the previous chapter to the project directory as solar.json:
See an example solar.development.json file
Now try again:
Yay it works (hopefully).
Calling A Read-Only Method
The Solidity method we called is:
The ABI definition (loaded from solar.json) is:
And to call this method using JavaScript:
myToken.call("totalSupply")returns a Promise, andawaitis a syntatic sugar to that waits for the asynchronous computation, then returns the result.Solidity numbers (int, uint, etc.) are represented in JavaScript using BigNumber.
The result object contains other useful information aside from the returned values.
Do console.log(result) to print it out:
If you hover your mouse cursor over the result variable, you should see that its type is IContractCallDecodedResult:
The type definition for IContractCallDecodedResult:
Call Method With Arguments
The balance subcommand checks how many tokens an account has:
The JavaScript code that implements this:
The arguments to balanceOf are passed in as an array.
Send VS Call
Confusingly, there are two ways to invoke a method: send and call. These two names are inherited from Ethereum. A more descriptive way to name them is perhaps to call send "commit" and call "query".
call(or "query"): executes contract code on your own local hyrad node as a "simulation", returning results, but not changing the blockchain. This is free.send(or "commit"): creates an actual transaction that would execute code globally on the network, changing the blockchain. This costs gas.
Next, we are going to mint some new tokens using hydrajs. And because minting token changes the blockchain, we'll use send.
Mint Tokens With Send
The mint command creates new tokens by using send to create a new transaction. Then it waits for that transaction to confirm:
We should see that the balance had increased:
The mint function source code:
txis the transaction submitted.tx.confirm(1)is a Promise that returns when there is one confirmation for the transaction.
Token Transfer
Let's transfer tokens from dcd32...9e94 to another account. The contract's transfer method takes two arguments:
_toaddress is the receiver of the tokens._valueis the amount of tokens to transfer.
Note that the API does not require the _from address. It is assumed that msg.sender is the source of the token balance to transfer from.
Ah, msg.sender, our old nemesis.
As we've learned in The Owner UTXO Address, HYDRA doesn't really have the idea of an "account". The msg.sender is the address of whatever UTXO that was used to pay for the transaction.
To act as dcb3...9e94, we need to explicitly specify an UTXO that has the same address. We can do this by using the senderAddress option.
In the above code, the third argument of send allows you to specify the msg.sender. Remember to prefund this address with UTXOs.
There are other options you can specify for send. The full type definition is IContractSendRequestOptions:
To test transfer, let's generate a new receiver address, and convert it to hex:
To transfer 100 tokens from dcb3...9e94:
Note that we MUST specify the senderAddress using base58 address format. We'll fix this in the future.
We can then verify that 9d74...9cc6 had indeed received the tokens:
And that the origin account's balance decremented by 100:
Observing Contract Events
The CappedToken contract defines a few events. The Transfer event is emitted whenever fund is moved from one account to another (also when minting new tokens). The Transfer event:
Let's use qtumjs to subscribe to the stream of contract events, so we can react in a timely manner when a transfer occurs. The code:
Let's see it in action. Launch the events subscriber:
The program hangs there waiting for new events. In another terminal, mint more tokens:
Wait for a bit for confirmations. In the events terminal, you should see both Mint and Transfer events printed out:
If you are running your own hydrad node instead of the provided docker image, you'll need to enable
-logeventsfor events logging to work.
Conclusion
In this chapter we've developed a simple NodeJS CLI tool to interact with an HRC20 contract.
hydrajs is a Promise-based API. Use async/await to write clean asynchronous code.
callis like "query",sendis like "commit".Use
senderAddressto incallorsendto specify themsg.owner.
Now that you know how to use hydrajs, you are ready to build a DApp, and be on your way to fame and riches!
Last updated
Was this helpful?