getNonce function

Future<num?> getNonce(
  1. num? currentNonce,
  2. String? accountIndex,
  3. String? bjj,
  4. num? tokenId,
)

Calculates the appropriate nonce based on the current token account nonce and existing transactions in the Pool. It needs to find the lowest nonce available as transactions in the pool may fail and the Coordinator only forges transactions in the order set by nonces.

@param {Number} currentNonce - The current token account nonce returned by the Coordinator (optional) @param {String} accountIndex - The account index @param {String} bjj - The account's BabyJubJub @param {Number} tokenId - The token id of the token in the transaction

@return {Number} nonce

Implementation

Future<num?> getNonce(
    num? currentNonce, String? accountIndex, String? bjj, num? tokenId) async {
  if (currentNonce != null) {
    return currentNonce;
  }

  final accountData = await api.getAccount(accountIndex!);
  var nonce = accountData.nonce;

  final List<dynamic> poolTxs = await getPoolTransactions(accountIndex, bjj);

  poolTxs.removeWhere((tx) => tx.token.id == tokenId);
  final List poolTxsNonces =
      poolTxs.where((tx) => tx.nonce).toList(); //map((tx) => tx.nonce);
  poolTxs.sort();

  // return current nonce if no transactions are pending
  if (poolTxsNonces.length > 0) {
    while (poolTxsNonces.indexOf(nonce) != -1) {
      nonce = nonce! + 1;
    }
  }

  return nonce;
}