/
wait.ts
58 lines (52 loc) · 2.06 KB
/
wait.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import Algodv2 from './client/v2/algod/algod';
/**
* Wait until a transaction has been confirmed or rejected by the network, or
* until 'waitRounds' number of rounds have passed.
* @param client - An Algodv2 client
* @param txid - The ID of the transaction to wait for.
* @param waitRounds - The maximum number of rounds to wait for.
* @returns A promise that, upon success, will resolve to the output of the
* `pendingTransactionInformation` call for the confirmed transaction.
*/
export async function waitForConfirmation(
client: Algodv2,
txid: string,
waitRounds: number
): Promise<Record<string, any>> {
// Wait until the transaction is confirmed or rejected, or until 'waitRounds'
// number of rounds have passed.
const status = await client.status().do();
if (typeof status === 'undefined') {
throw new Error('Unable to get node status');
}
const startRound = status['last-round'] + 1;
let currentRound = startRound;
/* eslint-disable no-await-in-loop */
while (currentRound < startRound + waitRounds) {
let poolError = false;
try {
const pendingInfo = await client.pendingTransactionInformation(txid).do();
if (pendingInfo['confirmed-round']) {
// Got the completed Transaction
return pendingInfo;
}
if (pendingInfo['pool-error']) {
// If there was a pool error, then the transaction has been rejected
poolError = true;
throw new Error(`Transaction Rejected: ${pendingInfo['pool-error']}`);
}
} catch (err) {
// Ignore errors from PendingTransactionInformation, since it may return 404 if the algod
// instance is behind a load balancer and the request goes to a different algod than the
// one we submitted the transaction to
if (poolError) {
// Rethrow error only if it's because the transaction was rejected
throw err;
}
}
await client.statusAfterBlock(currentRound).do();
currentRound += 1;
}
/* eslint-enable no-await-in-loop */
throw new Error(`Transaction not confirmed after ${waitRounds} rounds`);
}