Created
June 6, 2024 16:35
-
-
Save NotoriousPyro/f058665b9ee4e1b8e0a511b0b305b994 to your computer and use it in GitHub Desktop.
Async tx confirmer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class ConfirmTransactionFailureError extends Error { | |
constructor(signature: string) { | |
super("Failed to confirm transaction:" + signature); | |
this.name = "ConfirmTransactionFailure"; | |
} | |
} | |
export class TransactionConfirmer { | |
private subscriptionId: number; | |
private signatures = new Map<string, Logs>(); | |
constructor(connection: Connection, keypair: Keypair) { | |
this.subscriptionId = connection.onLogs( | |
keypair.publicKey, | |
(logs, __ctx) => { | |
if (this.signatures.has(logs.signature)) { | |
this.signatures.set(logs.signature, logs); | |
} | |
}, | |
"finalized" | |
); | |
} | |
public confirm = async ( | |
signature: string, | |
): Promise<Logs> => new Promise( | |
(resolve, reject) => { | |
this.signatures.set(signature, undefined); | |
let iterations = 0; | |
const interval = setInterval(() => { | |
if (iterations >= 120) { | |
clearInterval(interval); | |
this.signatures.delete(signature); | |
return reject(new ConfirmTransactionFailureError(signature)); | |
} | |
iterations++; | |
const confirmed = this.signatures.get(signature); | |
if (confirmed) { | |
const logs = structuredClone(confirmed); | |
clearInterval(interval); | |
this.signatures.delete(signature); | |
if (logs.signature !== signature) { | |
return reject(new ConfirmTransactionFailureError(`Signature mismatch logs signature: ${logs.signature} tx signature: ${signature}`)); | |
} | |
if (logs.err) { | |
return reject(logs); | |
} | |
if (logs.logs && logs.logs.length > 0 && logs.logs.slice(-1)[0].match(/success/) !== null) { | |
return resolve(logs); | |
} | |
return reject(new ConfirmTransactionFailureError(logs.signature)); | |
} | |
}, 500); | |
} | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment