From 6a6b61c49191bfc0895584dc4e767df878987307 Mon Sep 17 00:00:00 2001 From: discountry Date: Sun, 7 Dec 2025 22:36:37 +0800 Subject: [PATCH] fix nonce --- src/exchanges/lighter/gateway.ts | 5 ++++- src/exchanges/lighter/nonce-manager.ts | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/exchanges/lighter/gateway.ts b/src/exchanges/lighter/gateway.ts index e88a322..03ef8d9 100644 --- a/src/exchanges/lighter/gateway.ts +++ b/src/exchanges/lighter/gateway.ts @@ -199,6 +199,7 @@ export class LighterGateway { private readonly l1Address: string | null; private loggedCreateOrderPayload = false; private readonly logTxInfo: boolean; + private readonly primaryApiKeyIndex: number; private lastWsPositionUpdateAt = 0; private readonly lastWsPositionByMarket = new Map(); private httpPositionsEmptyLogged = false; @@ -296,6 +297,7 @@ export class LighterGateway { if (this.forcedSpotPreset && this.apiKeyIndices.length > 1) { this.apiKeyIndices.splice(1); // stick to the first key to avoid nonce drift } + this.primaryApiKeyIndex = this.apiKeyIndices[0]!; this.nonceManager = new HttpNonceManager({ accountIndex: options.accountIndex, apiKeyIndices: this.apiKeyIndices, @@ -361,7 +363,8 @@ export class LighterGateway { const maxAttempts = 3; for (let attempt = 0; attempt < maxAttempts; attempt++) { - const { apiKeyIndex, nonce } = this.nonceManager.next(); + const { apiKeyIndex, nonce } = + this.primaryApiKeyIndex != null ? this.nonceManager.nextFor(this.primaryApiKeyIndex) : this.nonceManager.next(); try { const signed = await this.signer.signCreateOrder({ ...signParams, diff --git a/src/exchanges/lighter/nonce-manager.ts b/src/exchanges/lighter/nonce-manager.ts index 03231d0..bba64e0 100644 --- a/src/exchanges/lighter/nonce-manager.ts +++ b/src/exchanges/lighter/nonce-manager.ts @@ -67,6 +67,20 @@ export class HttpNonceManager implements LighterNonceManager { this.slots.set(apiKeyIndex, { apiKeyIndex, next: nonce, lastIssued: null }); } + nextFor(apiKeyIndex: number): { apiKeyIndex: number; nonce: bigint } { + if (!this.slots.size) { + throw new Error("Nonce manager not initialized"); + } + const slot = this.slots.get(apiKeyIndex); + if (!slot) { + throw new Error(`Nonce slot for API key index ${apiKeyIndex} is not initialized`); + } + const nonce = slot.next; + slot.lastIssued = nonce; + slot.next = nonce + 1n; + return { apiKeyIndex, nonce }; + } + private async refreshAll(force: boolean): Promise { await Promise.all( this.apiKeyIndices.map(async (index) => {