|
| 1 | +import { BigNumber } from "ethers"; |
| 2 | +import type { Logger as LoggerType } from "winston"; |
| 3 | +import type { Provider } from "@ethersproject/abstract-provider"; |
| 4 | +import type { Signer } from "ethers"; |
| 5 | +import { GasEstimator } from "@uma/financial-templates-lib"; |
| 6 | + |
| 7 | +export interface NonceBacklogConfig { |
| 8 | + // Minimum nonce difference (pending - latest) to trigger clearing |
| 9 | + nonceBacklogThreshold: number; |
| 10 | + // Fee bump percentage per attempt (e.g., 20 means 20% increase) |
| 11 | + feeBumpPercent: number; |
| 12 | + // Max attempts to replace a stuck transaction with increasing fees |
| 13 | + replacementAttempts: number; |
| 14 | +} |
| 15 | + |
| 16 | +export interface TransactionClearingParams { |
| 17 | + provider: Provider; |
| 18 | + signer: Signer; |
| 19 | + nonceBacklogConfig: NonceBacklogConfig; |
| 20 | +} |
| 21 | + |
| 22 | +type FeeData = { maxFeePerGas: BigNumber; maxPriorityFeePerGas: BigNumber } | { gasPrice: BigNumber }; |
| 23 | + |
| 24 | +function isLondonFeeData(feeData: FeeData): feeData is { maxFeePerGas: BigNumber; maxPriorityFeePerGas: BigNumber } { |
| 25 | + return "maxFeePerGas" in feeData; |
| 26 | +} |
| 27 | + |
| 28 | +export const parsePositiveInt = (value: string | undefined, defaultValue: number, name: string): number => { |
| 29 | + if (value === undefined) return defaultValue; |
| 30 | + const parsed = Number(value); |
| 31 | + if (!Number.isFinite(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { |
| 32 | + throw new Error(`${name} must be a positive integer, got: ${value}`); |
| 33 | + } |
| 34 | + return parsed; |
| 35 | +}; |
| 36 | + |
| 37 | +export const getNonceBacklogConfig = (env: NodeJS.ProcessEnv): NonceBacklogConfig => { |
| 38 | + return { |
| 39 | + nonceBacklogThreshold: parsePositiveInt(env.NONCE_BACKLOG_THRESHOLD, 1, "NONCE_BACKLOG_THRESHOLD"), |
| 40 | + feeBumpPercent: parsePositiveInt(env.NONCE_REPLACEMENT_BUMP_PERCENT, 20, "NONCE_REPLACEMENT_BUMP_PERCENT"), |
| 41 | + replacementAttempts: parsePositiveInt(env.NONCE_REPLACEMENT_ATTEMPTS, 3, "NONCE_REPLACEMENT_ATTEMPTS"), |
| 42 | + }; |
| 43 | +}; |
| 44 | + |
| 45 | +function bumpFeeData(baseFeeData: FeeData, attemptIndex: number, config: NonceBacklogConfig): FeeData { |
| 46 | + // Calculate multiplier: ((100 + percent) / 100)^(attemptIndex+1) |
| 47 | + // For attempt 0: 1.2x, attempt 1: 1.44x, attempt 2: 1.73x (with default 20%) |
| 48 | + const bumpValue = (value: BigNumber): BigNumber => { |
| 49 | + let bumped = value; |
| 50 | + for (let i = 0; i <= attemptIndex; i++) { |
| 51 | + bumped = bumped.mul(100 + config.feeBumpPercent).div(100); |
| 52 | + } |
| 53 | + return bumped; |
| 54 | + }; |
| 55 | + |
| 56 | + if (isLondonFeeData(baseFeeData)) { |
| 57 | + return { |
| 58 | + maxFeePerGas: bumpValue(baseFeeData.maxFeePerGas), |
| 59 | + maxPriorityFeePerGas: bumpValue(baseFeeData.maxPriorityFeePerGas), |
| 60 | + }; |
| 61 | + } else { |
| 62 | + return { |
| 63 | + gasPrice: bumpValue(baseFeeData.gasPrice), |
| 64 | + }; |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +async function getNonces(provider: Provider, address: string): Promise<{ latestNonce: number; pendingNonce: number }> { |
| 69 | + const [latestNonce, pendingNonce] = await Promise.all([ |
| 70 | + provider.getTransactionCount(address, "latest"), |
| 71 | + provider.getTransactionCount(address, "pending"), |
| 72 | + ]); |
| 73 | + return { latestNonce, pendingNonce }; |
| 74 | +} |
| 75 | + |
| 76 | +/** |
| 77 | + * Clears stuck transactions by sending self-transactions with higher gas fees. |
| 78 | + * @returns true if a nonce backlog was detected and clearing was attempted |
| 79 | + */ |
| 80 | +export async function clearStuckTransactions( |
| 81 | + logger: LoggerType, |
| 82 | + params: TransactionClearingParams, |
| 83 | + gasEstimator: GasEstimator |
| 84 | +): Promise<boolean> { |
| 85 | + const { provider, signer, nonceBacklogConfig } = params; |
| 86 | + const botAddress = await signer.getAddress(); |
| 87 | + |
| 88 | + const { latestNonce, pendingNonce } = await getNonces(provider, botAddress); |
| 89 | + const backlog = pendingNonce - latestNonce; |
| 90 | + |
| 91 | + if (backlog < nonceBacklogConfig.nonceBacklogThreshold) { |
| 92 | + logger.debug({ |
| 93 | + at: "TransactionClearer", |
| 94 | + message: "No nonce backlog detected", |
| 95 | + botAddress, |
| 96 | + latestNonce, |
| 97 | + pendingNonce, |
| 98 | + backlog, |
| 99 | + threshold: nonceBacklogConfig.nonceBacklogThreshold, |
| 100 | + }); |
| 101 | + return false; |
| 102 | + } |
| 103 | + |
| 104 | + logger.warn({ |
| 105 | + at: "TransactionClearer", |
| 106 | + message: "Nonce backlog detected, attempting to clear stuck transactions", |
| 107 | + botAddress, |
| 108 | + latestNonce, |
| 109 | + pendingNonce, |
| 110 | + backlog, |
| 111 | + threshold: nonceBacklogConfig.nonceBacklogThreshold, |
| 112 | + }); |
| 113 | + |
| 114 | + // Get base fee data from gas estimator |
| 115 | + const baseFeeData = gasEstimator.getCurrentFastPriceEthers(); |
| 116 | + |
| 117 | + // Clear all stuck nonces from latestNonce to pendingNonce - 1 |
| 118 | + for (let nonce = latestNonce; nonce < pendingNonce; nonce++) { |
| 119 | + let cleared = false; |
| 120 | + |
| 121 | + for (let attempt = 0; attempt < nonceBacklogConfig.replacementAttempts; attempt++) { |
| 122 | + const feeData = bumpFeeData(baseFeeData, attempt, nonceBacklogConfig); |
| 123 | + |
| 124 | + try { |
| 125 | + logger.info({ |
| 126 | + at: "TransactionClearer", |
| 127 | + message: `Attempting to clear stuck transaction (nonce ${nonce}, attempt ${attempt + 1})`, |
| 128 | + botAddress, |
| 129 | + nonce, |
| 130 | + attempt: attempt + 1, |
| 131 | + feeData: isLondonFeeData(feeData) |
| 132 | + ? { |
| 133 | + maxFeePerGas: feeData.maxFeePerGas.toString(), |
| 134 | + maxPriorityFeePerGas: feeData.maxPriorityFeePerGas.toString(), |
| 135 | + } |
| 136 | + : { gasPrice: feeData.gasPrice.toString() }, |
| 137 | + }); |
| 138 | + |
| 139 | + const tx = await signer.sendTransaction({ |
| 140 | + to: botAddress, // Self-transaction |
| 141 | + value: 0, |
| 142 | + nonce, |
| 143 | + gasLimit: 21_000, |
| 144 | + ...feeData, |
| 145 | + }); |
| 146 | + |
| 147 | + const receipt = await tx.wait(1); |
| 148 | + |
| 149 | + logger.info({ |
| 150 | + at: "TransactionClearer", |
| 151 | + message: `Successfully cleared stuck transaction (nonce ${nonce})`, |
| 152 | + botAddress, |
| 153 | + nonce, |
| 154 | + transactionHash: receipt.transactionHash, |
| 155 | + gasUsed: receipt.gasUsed.toString(), |
| 156 | + }); |
| 157 | + |
| 158 | + cleared = true; |
| 159 | + break; |
| 160 | + } catch (error) { |
| 161 | + logger.warn({ |
| 162 | + at: "TransactionClearer", |
| 163 | + message: `Failed to clear stuck transaction (nonce ${nonce}, attempt ${attempt + 1})`, |
| 164 | + botAddress, |
| 165 | + nonce, |
| 166 | + attempt: attempt + 1, |
| 167 | + error: error instanceof Error ? error.message : String(error), |
| 168 | + }); |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + if (!cleared) { |
| 173 | + logger.error({ |
| 174 | + at: "TransactionClearer", |
| 175 | + message: `Failed to clear stuck transaction after all attempts (nonce ${nonce})`, |
| 176 | + botAddress, |
| 177 | + nonce, |
| 178 | + maxAttempts: nonceBacklogConfig.replacementAttempts, |
| 179 | + }); |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + // Verify final state |
| 184 | + const { latestNonce: finalLatestNonce, pendingNonce: finalPendingNonce } = await getNonces(provider, botAddress); |
| 185 | + const finalBacklog = finalPendingNonce - finalLatestNonce; |
| 186 | + |
| 187 | + if (finalBacklog < nonceBacklogConfig.nonceBacklogThreshold) { |
| 188 | + logger.info({ |
| 189 | + at: "TransactionClearer", |
| 190 | + message: "Successfully cleared nonce backlog", |
| 191 | + botAddress, |
| 192 | + previousBacklog: backlog, |
| 193 | + finalBacklog, |
| 194 | + }); |
| 195 | + } else { |
| 196 | + logger.warn({ |
| 197 | + at: "TransactionClearer", |
| 198 | + message: "Nonce backlog still present after clearing attempt", |
| 199 | + botAddress, |
| 200 | + previousBacklog: backlog, |
| 201 | + finalBacklog, |
| 202 | + }); |
| 203 | + } |
| 204 | + |
| 205 | + return true; |
| 206 | +} |
0 commit comments