Skip to content

Instantly share code, notes, and snippets.

@koxu1996
Last active April 25, 2024 12:00
Show Gist options
  • Save koxu1996/1ecffc774a2f0f9d6d104a23d33890f1 to your computer and use it in GitHub Desktop.
Save koxu1996/1ecffc774a2f0f9d6d104a23d33890f1 to your computer and use it in GitHub Desktop.

Balance check with Casper JS SDK

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().

Steps

  1. Create project directory
$ mkdir /tmp/casper-balance-test
$ cd /tmp/casper-balance-test
  1. Install JS SDK - in this case 2.15.4 version:
$ yarn add --silent casper-js-sdk@2.15.4
  1. Run Node REPL:
$ node
Welcome to Node.js v20.8.0.
Type ".help" for more information.
  1. Import base items from SDK:
> const { CasperClient, CLPublicKey, encodeBase16 } = (await import("casper-js-sdk")).default;
  1. Configure mainnet RPC and example public key of user account:
> const NODE_RPC = "https://casper-node.xyz:47777/rpc";
> const ACCOUNT_PUBLIC_KEY = "01e44b08110044928ec39baab349fee9f05c832530f73b0a2d1d8fdb63c3d12461";
  1. Convert public key into account hash:
> const publicKey = CLPublicKey.fromHex(ACCOUNT_PUBLIC_KEY);
> const accountHashStr = encodeBase16(publicKey.toAccountHash());
> console.log(accountHashStr);
'fa5c933f908608377f451a52791b5d53955d99f7bad2707bd82eef32a893db5a'
  1. 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
  1. Get address of account's main purse:
> const balanceUref = await client.nodeClient.getAccountBalanceUrefByPublicKeyHash(stateRootHash, accountHashStr);
> console.log(balanceUref);
uref-21dc39f0cd720ab29ead40fee6bb88ff0adf7ef3ab7d0463738e2b0248dbf350-007
  1. 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:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment