9

I want get the balance of an account address at a particular nonce.

I only know how to get the latest balance of an account address and its latest nonce (total number of transactions sent from that account address) with this:

const { nonce, data: balance } = await api.query.system.account(ADDR); 
console.log(`latest balance of account address ${ADDR} is ${balance.free} and its latest nonce is ${nonce}`);

Thank you for reading.

1 Answer 1

11

You can get the balance of an account at any given block hash. For example:

const { nonce, data: balance } = await api.query.system.account.at(HASH, ADDR); 

Or, alternatively, you can create a new api object that corresponds to the state at block with hash HASH:

let atApi = await api.at(HASH);
const { nonce, data: balance } = await atApi.query.system.account(ADDR); 

Knowing this, your question is reduced and answered in two steps:

  1. First, you need to find the block hash at which the account address nonce number that you are interested in occurred.
  2. Then, using the above examples, you can read the account balance at that identified block hash.

To find the hash corresponding to the nonce you are interested in, you can either do a linear or binary search, but this entirely depends on which range you want to search. And how you do it exactly the same as described in the above steps:

for (let x = rangeStart; x > rangeStart; x--) {
    const nonceAtBlock = (await api.query.system.account.at(currentHash, ADDR)).nonce;
    if (nonceAtBlock.eq(7)) { 
        // found the nonce! 
        break; 
    }
    // go to the parent block's hash and check that. 
    const parentHash = (await api.rpc.chain.getBlock(currentHash)).block.header.parentHash;
    currentHash = parentHash;
}
1
  • Thank you for your help. That is fantastic.
    – Lee
    Mar 19, 2022 at 22:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.