|
| 1 | +import Algodv2 from './client/v2/algod/algod'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Wait until a transaction has been confirmed or rejected by the network, or |
| 5 | + * until 'waitRounds' number of rounds have passed. |
| 6 | + * @param client - An Algodv2 client |
| 7 | + * @param txid - The ID of the transaction to wait for. |
| 8 | + * @param waitRounds - The maximum number of rounds to wait for. |
| 9 | + * @returns A promise that, upon success, will resolve to the output of the |
| 10 | + * `pendingTransactionInformation` call for the confirmed transaction. |
| 11 | + */ |
| 12 | +export async function waitForConfirmation( |
| 13 | + client: Algodv2, |
| 14 | + txid: string, |
| 15 | + waitRounds: number |
| 16 | +): Promise<Record<string, any>> { |
| 17 | + // Wait until the transaction is confirmed or rejected, or until 'waitRounds' |
| 18 | + // number of rounds have passed. |
| 19 | + |
| 20 | + const status = await client.status().do(); |
| 21 | + if (typeof status === 'undefined') { |
| 22 | + throw new Error('Unable to get node status'); |
| 23 | + } |
| 24 | + const startRound = status['last-round'] + 1; |
| 25 | + let currentRound = startRound; |
| 26 | + |
| 27 | + /* eslint-disable no-await-in-loop */ |
| 28 | + while (currentRound < startRound + waitRounds) { |
| 29 | + const pendingInfo = await client.pendingTransactionInformation(txid).do(); |
| 30 | + |
| 31 | + if (pendingInfo['confirmed-round']) { |
| 32 | + // Got the completed Transaction |
| 33 | + return pendingInfo; |
| 34 | + } |
| 35 | + |
| 36 | + if (pendingInfo['pool-error']) { |
| 37 | + // If there was a pool error, then the transaction has been rejected! |
| 38 | + throw new Error(`Transaction Rejected: ${pendingInfo['pool-error']}`); |
| 39 | + } |
| 40 | + |
| 41 | + await client.statusAfterBlock(currentRound).do(); |
| 42 | + currentRound += 1; |
| 43 | + } |
| 44 | + /* eslint-enable no-await-in-loop */ |
| 45 | + throw new Error(`Transaction not confirmed after ${waitRounds} rounds!`); |
| 46 | +} |
0 commit comments