diff --git a/package.json b/package.json index a9b62b4..c93ff0a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "zkbob-client-js", - "version": "5.5.1", + "version": "5.5.2", "description": "zkBob integration library", "repository": "git@github.com:zkBob/libzkbob-client-js.git", "author": "Dmitry Vdovin ", diff --git a/src/client-provider.ts b/src/client-provider.ts index 5a39642..f0fc201 100644 --- a/src/client-provider.ts +++ b/src/client-provider.ts @@ -192,7 +192,7 @@ export class ZkBobProvider { return Object.keys(this.pools); } - // swithing to the another pool + // switching to the another pool public switchToPool(poolAlias: string) { if (!this.pools[poolAlias]) { throw new InternalError(`Cannot activate unknown pool ${poolAlias}`); diff --git a/src/networks/evm/index.ts b/src/networks/evm/index.ts index 8bcc5eb..84680ba 100644 --- a/src/networks/evm/index.ts +++ b/src/networks/evm/index.ts @@ -17,14 +17,20 @@ import { RpcManagerDelegate, MultiRpcManager } from '../rpcman'; import { ZkBobState } from '../../state'; import { CommittedForcedExit, FinalizedForcedExit, ForcedExitRequest } from '../../emergency'; -const RETRY_COUNT = 10; const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; const ZERO_ADDRESS1 = '0x0000000000000000000000000000000000000001'; export enum PoolSelector { Transact = "af989083", AppendDirectDeposit = "1dc4cb33", - } +} + +export enum ZkBobContractType { + Pool = "pool", + DD = "direct deposit", + Token = "token", + Accounting = "accounting" +} export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcManagerDelegate { // These properties can be undefined when backend in the disabled state @@ -87,7 +93,7 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa return this.web3; } - private poolContract(): Contract { + /*private poolContract(): Contract { if (!this.pool) { throw new InternalError(`EvmNetwork: pool contract object is undefined`); } @@ -117,15 +123,31 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa } return this.accounting; + }*/ + + private contractByType(type: ZkBobContractType): Contract { + let res: Contract | undefined; + switch (type) { + case ZkBobContractType.Pool: res = this.pool; break; + case ZkBobContractType.DD: res = this.dd; break; + case ZkBobContractType.Token: res = this.token; break; + case ZkBobContractType.Accounting: res = this.accounting; break; + } + + if (!res) { + throw new InternalError(`EvmNetwork: ${type} contract object is undefined`); + } + + return res; } - private contractCallRetry(contract: Contract, address: string, method: string, args: any[] = []): Promise { + private contractCallRetry(contractType: ZkBobContractType, address: string, method: string, args: any[] = []): Promise { return this.commonRpcRetry(async () => { + const contract = this.contractByType(contractType); contract.options.address = address; return await contract.methods[method](...args).call() }, - `[EvmNetwork] Contract call (${method}) error`, - RETRY_COUNT + `[EvmNetwork] Contract call (${method}) error` ); } @@ -158,40 +180,40 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa // ------------------------------------------------------------------------------- public async getTokenName(tokenAddress: string): Promise { - return this.contractCallRetry(this.tokenContract(), tokenAddress, 'name'); + return this.contractCallRetry(ZkBobContractType.Token, tokenAddress, 'name'); } public async getTokenDecimals(tokenAddress: string): Promise { - const res = await this.contractCallRetry(this.tokenContract(), tokenAddress, 'decimals'); + const res = await this.contractCallRetry(ZkBobContractType.Token, tokenAddress, 'decimals'); return Number(res); } public async getDomainSeparator(tokenAddress: string): Promise { - return this.contractCallRetry(this.tokenContract(), tokenAddress, 'DOMAIN_SEPARATOR'); + return this.contractCallRetry(ZkBobContractType.Token, tokenAddress, 'DOMAIN_SEPARATOR'); } public async getTokenNonce(tokenAddress: string, address: string): Promise { - const res = await this.contractCallRetry(this.tokenContract(), tokenAddress, 'nonces', [address]); + const res = await this.contractCallRetry(ZkBobContractType.Token, tokenAddress, 'nonces', [address]); return Number(res); } public async getTokenBalance(tokenAddress: string, address: string): Promise { // in token base units - const res = await this.contractCallRetry(this.tokenContract(), tokenAddress, 'balanceOf', [address]); + const res = await this.contractCallRetry(ZkBobContractType.Token, tokenAddress, 'balanceOf', [address]); return BigInt(res); } public async allowance(tokenAddress: string, owner: string, spender: string): Promise { - const res = await this.contractCallRetry(this.tokenContract(), tokenAddress, 'allowance', [owner, spender]); + const res = await this.contractCallRetry(ZkBobContractType.Token, tokenAddress, 'allowance', [owner, spender]); return BigInt(res); } public async permit2NonceBitmap(permit2Address: string, owner: string, wordPos: bigint): Promise { - const res = await this.contractCallRetry(this.tokenContract(), permit2Address, 'nonceBitmap', [owner, wordPos]); + const res = await this.contractCallRetry(ZkBobContractType.Token, permit2Address, 'nonceBitmap', [owner, wordPos]); return BigInt(res); } public async erc3009AuthState(tokenAddress: string, authorizer: string, nonce: bigint): Promise { - const res = await this.contractCallRetry(this.tokenContract(), tokenAddress, 'authorizationState', [authorizer, `0x${nonce.toString(16)}`]); + const res = await this.contractCallRetry(ZkBobContractType.Token, tokenAddress, 'authorizationState', [authorizer, `0x${nonce.toString(16)}`]); return BigInt(res); } @@ -203,7 +225,7 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa amount: bigint, gasFactor?: number ): Promise { - const encodedTx = await this.tokenContract().methods.approve(spender, BigInt(amount)).encodeABI(); + const encodedTx = await this.contractByType(ZkBobContractType.Token).methods.approve(spender, BigInt(amount)).encodeABI(); let txObject: TransactionConfig = { from: holder, to: tokenAddress, @@ -212,10 +234,10 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa const gas = await this.commonRpcRetry(async () => { return Number(await this.activeWeb3().eth.estimateGas(txObject)); - }, 'Unable to estimate gas', RETRY_COUNT); + }, 'Unable to estimate gas'); const gasPrice = await this.commonRpcRetry(async () => { return Number(await this.activeWeb3().eth.getGasPrice()); - }, 'Unable to get gas price', RETRY_COUNT); + }, 'Unable to get gas price'); txObject.gas = gas; txObject.gasPrice = `0x${BigInt(Math.ceil(gasPrice * (gasFactor ?? 1.0))).toString(16)}`; txObject.nonce = await this.getNativeNonce(holder); @@ -224,13 +246,13 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa const receipt = await this.commonRpcRetry(async () => { return this.activeWeb3().eth.sendSignedTransaction(signedTx.rawTransaction ?? ''); - }, 'Unable to send approve tx', 0); // do not retry sending to avoid any side effects + }, 'Unable to send approve tx', true); // do not retry sending to avoid any side effects return receipt.transactionHash; } public async isSupportNonce(tokenAddress: string): Promise { - const tokenContract = this.tokenContract(); + const tokenContract = this.contractByType(ZkBobContractType.Token); return this.isMethodSupportedByContract(tokenContract, tokenAddress, 'nonces', [ZERO_ADDRESS]); } @@ -240,27 +262,27 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa // ------------------------------------------------------------------------------- public async getPoolId(poolAddress: string): Promise { - return Number(await this.contractCallRetry(this.poolContract(), poolAddress, 'pool_id')); + return Number(await this.contractCallRetry(ZkBobContractType.Pool, poolAddress, 'pool_id')); } public async getDenominator(poolAddress: string): Promise { - return BigInt(await this.contractCallRetry(this.poolContract(), poolAddress, 'denominator')); + return BigInt(await this.contractCallRetry(ZkBobContractType.Pool, poolAddress, 'denominator')); } public async poolState(poolAddress: string, index?: bigint): Promise<{index: bigint, root: bigint}> { let idx: string; if (index === undefined) { - idx = await this.contractCallRetry(this.poolContract(), poolAddress, 'pool_index'); + idx = await this.contractCallRetry(ZkBobContractType.Pool, poolAddress, 'pool_index'); } else { idx = index?.toString(); } - let root = BigInt(await this.contractCallRetry(this.poolContract(), poolAddress, 'roots', [idx])); + let root = BigInt(await this.contractCallRetry(ZkBobContractType.Pool, poolAddress, 'roots', [idx])); if (root == 0n) { // it's seems the RPC node got behind the actual blockchain state // let's try to find the best one and retry root request const switched = await this.switchToTheBestRPC(); if (switched) { - root = await this.contractCallRetry(this.poolContract(), poolAddress, 'roots', [idx]); + root = await this.contractCallRetry(ZkBobContractType.Pool, poolAddress, 'roots', [idx]); } if (root == 0n) { console.warn(`[EvmNetwork] cannot retrieve root at index ${idx} (is it exist?)`); @@ -271,24 +293,24 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa } public async poolLimits(poolAddress: string, address: string | undefined): Promise { - let contract: Contract; + let contract: ZkBobContractType; let contractAddress: string; - if (await this.isMethodSupportedByContract(this.poolContract(), poolAddress, 'accounting')) { + if (await this.isMethodSupportedByContract(this.contractByType(ZkBobContractType.Pool), poolAddress, 'accounting')) { // Current contract deployments (getLimitsFor implemented in the separated ZkBobAccounting contract) let accountingAddress = this.accountingAddresses.get(poolAddress); if (!accountingAddress) { - accountingAddress = await this.contractCallRetry(this.poolContract(), poolAddress, 'accounting'); + accountingAddress = await this.contractCallRetry(ZkBobContractType.Pool, poolAddress, 'accounting'); if (accountingAddress) { this.accountingAddresses.set(poolAddress, accountingAddress) } else { throw new InternalError(`Cannot retrieve accounting contract address for the pool ${poolAddress}`); } } - contract = this.accountingContract(); + contract = ZkBobContractType.Accounting; contractAddress = accountingAddress; } else { // Fallback for the old deployments (getLimitsFor implemented in pool contract) - contract = this.poolContract(); + contract = ZkBobContractType.Pool; contractAddress = poolAddress; } @@ -296,25 +318,25 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa } public async isSupportForcedExit(poolAddress: string): Promise { - const poolContract = this.poolContract(); + const poolContract = this.contractByType(ZkBobContractType.Pool); return this.isMethodSupportedByContract(poolContract, poolAddress, 'committedForcedExits', ['0']); } public async nullifierValue(poolAddress: string, nullifier: bigint): Promise { - const res = await this.contractCallRetry(this.poolContract(), poolAddress, 'nullifiers', [nullifier]); + const res = await this.contractCallRetry(ZkBobContractType.Pool, poolAddress, 'nullifiers', [nullifier]); return BigInt(res); } public async committedForcedExitHash(poolAddress: string, nullifier: bigint): Promise { - const res = await this.contractCallRetry(this.poolContract(), poolAddress, 'committedForcedExits', [nullifier.toString()]); + const res = await this.contractCallRetry(ZkBobContractType.Pool, poolAddress, 'committedForcedExits', [nullifier.toString()]); return BigInt(res); } public async createCommitForcedExitTx(poolAddress: string, forcedExit: ForcedExitRequest): Promise { const method = 'commitForcedExit(address,address,uint256,uint256,uint256,uint256,uint256[8])'; - const encodedTx = await this.poolContract().methods[method]( + const encodedTx = await this.contractByType(ZkBobContractType.Pool).methods[method]( forcedExit.operator, forcedExit.to, forcedExit.amount.toString(), @@ -335,7 +357,7 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa } public async committedForcedExit(poolAddress: string, nullifier: bigint): Promise { - const pool = this.poolContract(); + const pool = this.contractByType(ZkBobContractType.Pool); pool.options.address = poolAddress; const commitEventAbi = poolContractABI.find((val) => val.name == 'CommitForcedExit'); @@ -386,7 +408,7 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa } public async executedForcedExit(poolAddress: string, nullifier: bigint): Promise { - const pool = this.poolContract(); + const pool = this.contractByType(ZkBobContractType.Pool); pool.options.address = poolAddress; const executeEventAbi = poolContractABI.find((val) => val.name == 'ForcedExit'); @@ -424,7 +446,7 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa public async createExecuteForcedExitTx(poolAddress: string, forcedExit: CommittedForcedExit): Promise { const method = 'executeForcedExit(uint256,address,address,uint256,uint256,uint256,bool)'; - const encodedTx = await this.poolContract().methods[method]( + const encodedTx = await this.contractByType(ZkBobContractType.Pool).methods[method]( forcedExit.nullifier.toString(), forcedExit.operator, forcedExit.to, @@ -443,7 +465,7 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa public async createCancelForcedExitTx(poolAddress: string, forcedExit: CommittedForcedExit): Promise { const method = 'executeForcedExit(uint256,address,address,uint256,uint256,uint256,bool)'; - const encodedTx = await this.poolContract().methods[method]( + const encodedTx = await this.contractByType(ZkBobContractType.Pool).methods[method]( forcedExit.nullifier.toString(), forcedExit.operator, forcedExit.to, @@ -463,7 +485,7 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa public async getTokenSellerContract(poolAddress: string): Promise { let tokenSellerAddr = this.tokenSellerAddresses.get(poolAddress); if (!tokenSellerAddr) { - tokenSellerAddr = await this.contractCallRetry(this.poolContract(), poolAddress, 'tokenSeller'); + tokenSellerAddr = await this.contractCallRetry(ZkBobContractType.Pool, poolAddress, 'tokenSeller'); if (tokenSellerAddr) { this.tokenSellerAddresses.set(poolAddress, tokenSellerAddr); } else { @@ -482,7 +504,7 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa public async getDirectDepositQueueContract(poolAddress: string): Promise { let ddContractAddr = this.ddContractAddresses.get(poolAddress); if (!ddContractAddr) { - ddContractAddr = await this.contractCallRetry(this.poolContract(), poolAddress, 'direct_deposit_queue'); + ddContractAddr = await this.contractCallRetry(ZkBobContractType.Pool, poolAddress, 'direct_deposit_queue'); if (ddContractAddr) { this.ddContractAddresses.set(poolAddress, ddContractAddr); } else { @@ -494,7 +516,7 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa } public async getDirectDepositFee(ddQueueAddress: string): Promise { - const fee = await this.contractCallRetry(this.directDepositContract(), ddQueueAddress, 'directDepositFee'); + const fee = await this.contractCallRetry(ZkBobContractType.DD, ddQueueAddress, 'directDepositFee'); return BigInt(fee); } @@ -505,7 +527,7 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa fallbackAddress: string, ): Promise { const zkAddrBytes = `0x${Buffer.from(bs58.decode(zkAddress.substring(zkAddress.indexOf(':') + 1))).toString('hex')}`; - const encodedTx = await this.directDepositContract().methods["directDeposit(address,uint256,bytes)"](fallbackAddress, amount, zkAddrBytes).encodeABI(); + const encodedTx = await this.contractByType(ZkBobContractType.DD).methods["directDeposit(address,uint256,bytes)"](fallbackAddress, amount, zkAddrBytes).encodeABI(); return { to: ddQueueAddress, @@ -521,7 +543,7 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa fallbackAddress: string, ): Promise { const zkAddrBytes = `0x${Buffer.from(bs58.decode(zkAddress.substring(zkAddress.indexOf(':') + 1))).toString('hex')}`; - const encodedTx = await this.directDepositContract().methods["directNativeDeposit(address,bytes)"](fallbackAddress, zkAddrBytes).encodeABI(); + const encodedTx = await this.contractByType(ZkBobContractType.DD).methods["directNativeDeposit(address,bytes)"](fallbackAddress, zkAddrBytes).encodeABI(); return { to: ddQueueAddress, @@ -531,7 +553,7 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa } public async getDirectDeposit(ddQueueAddress: string, idx: number, state: ZkBobState): Promise { - const ddInfo = await this.contractCallRetry(this.directDepositContract(), ddQueueAddress, 'getDirectDeposit', [idx]); + const ddInfo = await this.contractCallRetry(ZkBobContractType.DD, ddQueueAddress, 'getDirectDeposit', [idx]); const ddStatusCode = Number(ddInfo.status); if (ddStatusCode != 0) { return { @@ -554,7 +576,7 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa } public async getDirectDepositNonce(ddQueueAddress: string): Promise { - const res = await this.contractCallRetry(this.directDepositContract(), ddQueueAddress, 'directDepositNonce'); + const res = await this.contractCallRetry(ZkBobContractType.DD, ddQueueAddress, 'directDepositNonce'); return Number(res); } @@ -691,13 +713,13 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa private async getTransaction(txHash: string): Promise { return this.commonRpcRetry(() => { return this.activeWeb3().eth.getTransaction(txHash); - }, 'Cannot get tx', RETRY_COUNT); + }, 'Cannot get tx'); } private async getTransactionReceipt(txHash: string): Promise { return this.commonRpcRetry(() => { return this.activeWeb3().eth.getTransactionReceipt(txHash); - }, 'Cannot get tx receipt', RETRY_COUNT); + }, 'Cannot get tx receipt'); } public async getTxRevertReason(txHash: string): Promise { @@ -727,19 +749,19 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa public async getChainId(): Promise { return this.commonRpcRetry(async () => { return this.activeWeb3().eth.getChainId(); - }, 'Cannot get chain ID', RETRY_COUNT); + }, 'Cannot get chain ID'); } public async getNativeBalance(address: string): Promise { return this.commonRpcRetry(async () => { return BigInt(await this.activeWeb3().eth.getBalance(address)); - }, 'Cannot get native balance', RETRY_COUNT); + }, 'Cannot get native balance'); } public async getNativeNonce(address: string): Promise { return this.commonRpcRetry(async () => { return Number(await this.activeWeb3().eth.getTransactionCount(address)) - }, 'Cannot get native nonce', RETRY_COUNT); + }, 'Cannot get native nonce'); } public async getTxDetails(index: number, poolTxHash: string, state: ZkBobState): Promise { @@ -892,14 +914,14 @@ export class EvmNetwork extends MultiRpcManager implements NetworkBackend, RpcMa public async getBlockNumber(): Promise { return this.commonRpcRetry(() => { return this.activeWeb3().eth.getBlockNumber(); - }, '[EvmNetwork]: Cannot get block number', RETRY_COUNT); + }, '[EvmNetwork]: Cannot get block number'); } public async getBlockNumberFrom(rpcurl: string): Promise { const tmpWeb3 = new Web3(rpcurl); return this.commonRpcRetry(() => { return tmpWeb3.eth.getBlockNumber(); - }, `[EvmNetwork]: Cannot get block number from ${rpcurl}`, 2); + }, `[EvmNetwork]: Cannot get block number from ${rpcurl}`, true); } public async waitForBlock(blockNumber: number, timeoutSec?: number): Promise { diff --git a/src/networks/rpcman.ts b/src/networks/rpcman.ts index 57e1537..6fb24fb 100644 --- a/src/networks/rpcman.ts +++ b/src/networks/rpcman.ts @@ -1,5 +1,6 @@ import { InternalError } from "../errors"; +const ATTEMPT_RETRIES_CNT = 5; const RPC_ISSUES_THRESHOLD = 20; // number of errors needed to switch RPC export interface RpcManagerDelegate { @@ -13,6 +14,7 @@ export class MultiRpcManager { private curRpcIdx: number; private curRpcIssues = 0; private badRpcs: number[] = []; // RPC indexes which are considered to be unstable or unavailable + protected switchingAttempts = 0; public delegate?: RpcManagerDelegate; constructor(rpcUrls: string[]) { @@ -25,27 +27,30 @@ export class MultiRpcManager { } // Performs RPC interaction within several attempts. The errors will registered automatically - protected async commonRpcRetry(closure: () => any, errorPattern: string, retriesCnt: number): Promise { - let cnt = 0; + protected async commonRpcRetry(closure: () => any, errorPattern: string, disableRetries: boolean = false): Promise { + let totalAttempts = 0; const attemptMinDelayMs = 500; - let lastErr; + const startAttemptsCnt = this.switchingAttempts; do { - const startTs = Date.now(); - try { - return await closure(); - } catch (e) { - lastErr = e; - console.error(`${errorPattern ?? 'Error occured'} [attempt #${cnt + 1}]: ${e.message}`); - this.registerRpcIssue(); - - const delay = Date.now() - startTs; - if (delay < attemptMinDelayMs) { - await new Promise(f => setTimeout(f, attemptMinDelayMs - delay)); + let cnt = 0; + do { + const startTs = Date.now(); + try { + return await closure(); + } catch (e) { + console.error(`${errorPattern ?? 'Error occured'} [attempt #${totalAttempts + 1}]: ${e.message}`); + this.registerRpcIssue(); + + const delay = Date.now() - startTs; + if (delay < attemptMinDelayMs) { + await new Promise(f => setTimeout(f, attemptMinDelayMs - delay)); + } } - } - } while (++cnt < retriesCnt); + totalAttempts++; + } while (!disableRetries && ++cnt < ATTEMPT_RETRIES_CNT); + } while (!disableRetries && (this.switchingAttempts - startAttemptsCnt) < this.rpcUrls.length); - throw new InternalError(`MultRpcManager: ${lastErr.message}`) + throw new InternalError(`MultRpcManager: ${disableRetries ? 'RPC interaction error' : 'all RPCs are unavailable'}`) } // ----------------------=========< RPC switching >=========---------------------- @@ -78,6 +83,7 @@ export class MultiRpcManager { console.log(`[MultiRpcManager]: RPC ${this.curRpcUrl()} marked as bad (${this.curRpcIssues} issues registered)`); } + this.switchingAttempts++; let newRpcIndex = index ?? this.curRpcIdx; if (index === undefined && this.rpcUrls.length > 1) { diff --git a/src/networks/tron/index.ts b/src/networks/tron/index.ts index 2efb65d..e805927 100644 --- a/src/networks/tron/index.ts +++ b/src/networks/tron/index.ts @@ -14,7 +14,6 @@ import { CommittedForcedExit, FinalizedForcedExit, ForcedExitRequest } from '../ const TronWeb = require('tronweb') const bs58 = require('bs58') -const RETRY_COUNT = 5; const DEFAULT_ENERGY_FEE = 420; const DEFAULT_FEE_LIMIT = 100_000_000; const ZERO_ADDRESS = 'T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb'; @@ -139,8 +138,7 @@ export class TronNetwork extends MultiRpcManager implements NetworkBackend, RpcM return this.commonRpcRetry(async () => { return await contract[method](...args).call() }, - `[TronNetwork] Contract call (${method}) error`, - RETRY_COUNT, + `[TronNetwork] Contract call (${method}) error` ); } @@ -150,7 +148,7 @@ export class TronNetwork extends MultiRpcManager implements NetworkBackend, RpcM if (isSupport === undefined) { const contract = await this.commonRpcRetry(() => { return this.tronWeb.trx.getContract(contractAddress); - }, 'Unable to retrieve smart contract object', RETRY_COUNT); + }, 'Unable to retrieve smart contract object'); const methods = contract.abi.entrys; if (Array.isArray(methods)) { isSupport = methods.find((val) => val.name == methodName) !== undefined; @@ -630,7 +628,7 @@ export class TronNetwork extends MultiRpcManager implements NetworkBackend, RpcM try { const txInfo = await this.commonRpcRetry(async () => { return this.activeTronweb().trx.getTransactionInfo(txHash); - }, '[TronNetwork] Cannot get transaction', RETRY_COUNT); + }, '[TronNetwork] Cannot get transaction'); if (txInfo && txInfo.receipt) { if (txInfo.result && txInfo.result == 'FAILED') { @@ -673,7 +671,7 @@ export class TronNetwork extends MultiRpcManager implements NetworkBackend, RpcM public async getNativeBalance(address: string): Promise { return this.commonRpcRetry(async () => { return BigInt(await this.activeTronweb().trx.getBalance(address)); - }, '[TronNetwork] Cannot get native balance', RETRY_COUNT); + }, '[TronNetwork] Cannot get native balance'); } public async getNativeNonce(address: string): Promise { @@ -684,7 +682,7 @@ export class TronNetwork extends MultiRpcManager implements NetworkBackend, RpcM try { const tronTransaction = await this.commonRpcRetry(async () => { return this.activeTronweb().trx.getTransaction(poolTxHash); - }, '[TronNetwork] Cannot get transaction', RETRY_COUNT); + }, '[TronNetwork] Cannot get transaction'); const txState = await this.getTransactionState(poolTxHash); const timestamp = tronTransaction?.raw_data?.timestamp const contract = tronTransaction?.raw_data?.contract; @@ -771,7 +769,7 @@ export class TronNetwork extends MultiRpcManager implements NetworkBackend, RpcM try { const txInfo = await this.commonRpcRetry(async () => { return this.activeTronweb().trx.getTransactionInfo(txHash); - }, '[TronNetwork] Cannot get transaction', RETRY_COUNT); + }, '[TronNetwork] Cannot get transaction'); if (txInfo && txInfo.receipt) { // tx is on the blockchain (assume mined) @@ -817,7 +815,7 @@ export class TronNetwork extends MultiRpcManager implements NetworkBackend, RpcM try { const chainParams = await this.commonRpcRetry(async () => { return this.activeTronweb().trx.getChainParameters(); - }, '[TronNetwork] Cannot get chain parameters', RETRY_COUNT); + }, '[TronNetwork] Cannot get chain parameters'); for (let aParam of chainParams) { if (aParam.key == 'getEnergyFee') { this.energyFee = Number(aParam.value); @@ -839,7 +837,7 @@ export class TronNetwork extends MultiRpcManager implements NetworkBackend, RpcM try { const accResources = await this.commonRpcRetry(async () => { return this.activeTronweb().trx.getAccountResources(address); - }, '[TronNetwork] Cannot get account resources', RETRY_COUNT); + }, '[TronNetwork] Cannot get account resources'); return Number(accResources.EnergyLimit ?? 0) - Number(accResources.EnergyUsed ?? 0); } catch(err) { console.warn(`Cannot get account energy: ${err}`); @@ -895,7 +893,7 @@ export class TronNetwork extends MultiRpcManager implements NetworkBackend, RpcM return this.commonRpcRetry(async () => { const block = await this.activeTronweb().trx.getCurrentBlock(); return block.block_header.raw_data.number; - }, '[TronNetwork] Cannot get block number', RETRY_COUNT); + }, '[TronNetwork] Cannot get block number'); } public async getBlockNumberFrom(rpcurl: string): Promise { @@ -906,7 +904,7 @@ export class TronNetwork extends MultiRpcManager implements NetworkBackend, RpcM return this.commonRpcRetry(async () => { const block = await tmpTronweb.trx.getCurrentBlock(); return block.block_header.raw_data.number; - }, `[TronNetwork] Cannot get block number from ${rpcurl}`, 2); + }, `[TronNetwork] Cannot get block number from ${rpcurl}`, true); } public async waitForBlock(blockNumber: number, timeoutSec?: number): Promise { diff --git a/yarn.lock b/yarn.lock index 0615178..12e1f20 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3463,11 +3463,6 @@ envinfo@^7.7.3: resolved "https://registry.yarnpkg.com/envinfo/-/envinfo-7.8.1.tgz#06377e3e5f4d379fea7ac592d5ad8927e0c4d475" integrity sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw== -err-code@^2.0.2: - version "2.0.3" - resolved "https://registry.yarnpkg.com/err-code/-/err-code-2.0.3.tgz#23c2f3b756ffdfc608d30e27c9a941024807e7f9" - integrity sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA== - error-ex@^1.3.1: version "1.3.2" resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" @@ -5856,14 +5851,6 @@ progress@^2.0.0: resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.3.tgz#7e8cf8d8f5b8f239c1bc68beb4eb78567d572ef8" integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== -promise-retry@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/promise-retry/-/promise-retry-2.0.1.tgz#ff747a13620ab57ba688f5fc67855410c370da22" - integrity sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g== - dependencies: - err-code "^2.0.2" - retry "^0.12.0" - promise-throttle@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/promise-throttle/-/promise-throttle-1.1.2.tgz#8a59d0424b6f9673aa8405c8b6bd4b5e4f7f71db" @@ -6147,11 +6134,6 @@ restore-cursor@^2.0.0: onetime "^2.0.0" signal-exit "^3.0.2" -retry@^0.12.0: - version "0.12.0" - resolved "https://registry.yarnpkg.com/retry/-/retry-0.12.0.tgz#1b42a6266a21f07421d1b0b54b7dc167b01c013b" - integrity sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow== - reusify@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76"