stacks.js icon indicating copy to clipboard operation
stacks.js copied to clipboard

Incorrect nonce set while building transaction with makeUnsignedContractCall

Open bilalanees98 opened this issue 2 years ago • 2 comments

What version of Stacks.js are you using?

v6.5.0

Describe the bug

Nonce set by stacks.js is wrong, resulting in a BadNonce error on broadcast.

How to reproduce

Assuming we have a fresh account with funds and nonce = 0. 1- Build a contract call transaction for any contract without setting the nonce in txOptions 2- broadcast the transaction. 3- Wait 3-5 mins 4- Build another contract call transaction with same account again without setting the nonce in txOptions. 5- broadcast 2nd tx. 6- BadNonce/ConflictingNonceInMempool error gets thrown.

Expected behavior

Possible next nonce should be used and the broadcast should complete without an error.

Investigation

  • All the builder fns in stacks/transactions use the getNonce fn.
  • getNonce uses the getAccountApiUrl fn to get the nonce. https://github.com/hirosystems/stacks.js/blob/c9e420e521cdc02d7ec81ea082f62d0a2d6c5e27/packages/transactions/src/builders.ts#L87
  • getAccountApiUrl fn uses this endpoint: https://stacks-node-api.testnet.stacks.co/v2/accounts/ST3QJKVMNZJ897FBDJT7YRQR0AJAS77C6N04SVV51?proof=0.
  • This only returns updated nonces when the tx has settled on-chain.

Instead I think the possible next nonce value should be fetched from this endpoint: https://api.testnet.hiro.so/extended/v1/address/ST3QJKVMNZJ897FBDJT7YRQR0AJAS77C6N04SVV51/nonces. As this endpoint takes into consideration both on-chain data and txs in mempool.

Furthermore, this change needs to be reflected across all builder fns including sponsorTransaction fn

bilalanees98 avatar May 02 '23 13:05 bilalanees98

Great issue write-up -- thanks! 🙏 Yes, I agree. We'll prioritize this 👍

janniks avatar May 03 '23 13:05 janniks

Since this would be sort of a breaking change (since the new endpoint requires an API, not just a Stacks node) I'll add this to an upcoming refactor of Stacks.js (Network and API clients)

janniks avatar Sep 18 '23 11:09 janniks