Skip to content

Commit

Permalink
feat(tx-nonce): make a global singleton for fetching nonce for approv…
Browse files Browse the repository at this point in the history
…al txns
  • Loading branch information
imsk17 committed Sep 3, 2024
1 parent 3aa88ad commit 680be84
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 15 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"@ton/crypto": "^3.2.0",
"@ton/ton": "^13.9.0",
"@xp/cosmos-client": "git+https://github.com/XP-NETWORK/cosmos-client#bleeding-edge",
"async-mutex": "^0.5.0",
"axios": "^1.6.7",
"chalk": "4",
"dotenv": "^16.4.5",
Expand Down
16 changes: 16 additions & 0 deletions src/deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { DirectSecp256k1Wallet } from "@cosmjs/proto-signing";
import { HttpAgent } from "@dfinity/agent";
import { Ed25519KeyIdentity } from "@dfinity/identity";
import type { EntityManager } from "@mikro-orm/sqlite";
import { Mutex } from "async-mutex";
import axios, { type AxiosInstance } from "axios";
import { ERC20Staking__factory } from "./contractsTypes/evm";
import { cosmWasmHandler } from "./handler/cosmos";
Expand Down Expand Up @@ -387,6 +388,20 @@ export async function configDeps(
const storageSigner = new NonceManager(
new Wallet(secrets.evmWallet.privateKey, storageProvider),
);
const nonce = { n: await storageSigner.getNonce(), used: false };
const lock = new Mutex();

const fetchNonce = async () => {
const release = await lock.acquire();
if (nonce.used) {
nonce.n = nonce.n + 1;
nonce.used = false;
return [nonce.n, release] as const;
}
nonce.used = true;
return [nonce.n, release] as const;
};

const storage = BridgeStorage__factory.connect(
config.storageConfig.contractAddress,
storageSigner,
Expand Down Expand Up @@ -477,6 +492,7 @@ export async function configDeps(
em,
storageSigner,
serverLinkHandler,
fetchNonce,
staking: await configStakingHandler(
em.fork(),
config.stakingConfig,
Expand Down
22 changes: 8 additions & 14 deletions src/handler/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { setTimeout } from "node:timers/promises";
import type { EntityManager } from "@mikro-orm/sqlite";
import type { MutexInterface } from "async-mutex";
import type { AxiosInstance } from "axios";
import type { NonceManager } from "ethers";
import type { TSupportedChainTypes, TSupportedChains } from "../config";
import type { BridgeStorage } from "../contractsTypes/evm";
import { LockedEvent } from "../persistence/entities/locked";
Expand All @@ -18,7 +18,7 @@ import { retry } from "./utils";
export async function listenEvents(
chains: Array<THandler>,
storage: BridgeStorage,
storageSigner: NonceManager,
fetchNonce: () => Promise<readonly [number, MutexInterface.Releaser]>,
em: EntityManager,
serverLinkHandler: AxiosInstance | undefined,
log: LogInstance,
Expand Down Expand Up @@ -104,24 +104,25 @@ export async function listenEvents(
);
return;
}
let tx_nonce: number | undefined = undefined;

const approvalFn = async () => {
try {
const tx = await Promise.race([
(async () => {
log.info(`Using nonce: ${tx_nonce}`);
return await (
const [nonce, release] = await fetchNonce();
log.info(`Using nonce: ${nonce}`);
const response = await (
await deps.storage.approveLockNft(
inft.transactionHash,
chain.chainIdent,
signature.signature,
signature.signer,
{
nonce: tx_nonce,
nonce,
},
)
).wait();
release();
return response;
})(),
setTimeout(20 * 1000),
]);
Expand All @@ -133,13 +134,6 @@ export async function listenEvents(
if (err_.shortMessage?.includes("Signature already used")) {
return null;
}
if (err_.shortMessage?.includes("Invalid transaction nonce")) {
tx_nonce = (await storageSigner.getNonce()) + 1;
log.warn(
`Invalid nonce for ${inft.transactionHash}. Incrementing nonce and retrying`,
tx_nonce,
);
}
log.error(err_, "Error while approving lock");
throw err;
}
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ async function main() {
listenEvents(
deps.chains,
deps.storage,
deps.storageSigner,
deps.fetchNonce,
deps.em.fork(),
deps.serverLinkHandler,
logger,
Expand Down
7 changes: 7 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1804,6 +1804,13 @@ astring@^1.8.4:
resolved "https://registry.yarnpkg.com/astring/-/astring-1.8.6.tgz#2c9c157cf1739d67561c56ba896e6948f6b93731"
integrity sha512-ISvCdHdlTDlH5IpxQJIex7BWBywFWgjJSVdwst+/iQCoEYnyOaQ95+X1JGshuBjGp6nxKUy1jMgE3zPqN7fQdg==

async-mutex@^0.5.0:
version "0.5.0"
resolved "https://registry.yarnpkg.com/async-mutex/-/async-mutex-0.5.0.tgz#353c69a0b9e75250971a64ac203b0ebfddd75482"
integrity sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==
dependencies:
tslib "^2.4.0"

asynckit@^0.4.0:
version "0.4.0"
resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
Expand Down

0 comments on commit 680be84

Please sign in to comment.