This is long demonstration of checking account balance, with the backend usage of JavaScript SDK.
Note: we used extra steps to avoid silent failure that can happen in CasperClient.balanceOfByPublicKey()
.
- Create project directory
$ mkdir /tmp/casper-balance-test
$ cd /tmp/casper-balance-test
- Install JS SDK - in this case
2.15.4
version:
$ yarn add --silent [email protected]
- Run Node REPL:
$ node
Welcome to Node.js v20.8.0.
Type ".help" for more information.
- Import base items from SDK:
> const { CasperClient, CLPublicKey, encodeBase16 } = (await import("casper-js-sdk")).default;
- Configure mainnet RPC and example public key of user account:
> const NODE_RPC = "https://casper-node.xyz:47777/rpc";
> const ACCOUNT_PUBLIC_KEY = "01e44b08110044928ec39baab349fee9f05c832530f73b0a2d1d8fdb63c3d12461";
- Convert public key into account hash:
> const publicKey = CLPublicKey.fromHex(ACCOUNT_PUBLIC_KEY);
> const accountHashStr = encodeBase16(publicKey.toAccountHash());
> console.log(accountHashStr);
'fa5c933f908608377f451a52791b5d53955d99f7bad2707bd82eef32a893db5a'
- Create RPC client and fetch state root hash:
> const client = new CasperClient(NODE_RPC);
> const stateRootHash = await client.nodeClient.getLatestBlockInfo().then(it => it.block?.header.state_root_hash);
> console.log(stateRootHash);
fbc7a065566a4522fc7708170952b90a777f1c022d4563fb25306b99d1a1adb5
- Get address of account's main purse:
> const balanceUref = await client.nodeClient.getAccountBalanceUrefByPublicKeyHash(stateRootHash, accountHashStr);
> console.log(balanceUref);
uref-21dc39f0cd720ab29ead40fee6bb88ff0adf7ef3ab7d0463738e2b0248dbf350-007
- Fetch purse balance:
> let balance = await client.nodeClient.getAccountBalance(stateRootHash, balanceUref);
> console.log(balance.toNumber());
130400000000
As you can see account has 130400000000 motes (130.4 CSPR) in the main purse. It is exactly the same value as presented at CSPR.live: