solana/web3.js/src/util/send-and-confirm-transaction.js

65 lines
1.7 KiB
JavaScript
Raw Normal View History

2018-10-06 10:36:59 -07:00
// @flow
import invariant from 'assert';
2018-10-25 08:18:59 -07:00
import {Connection} from '../connection';
import {Transaction} from '../transaction';
2018-10-06 10:36:59 -07:00
import {sleep} from './sleep';
2018-10-25 08:18:59 -07:00
import type {Account} from '../account';
import type {TransactionSignature} from '../transaction';
import {DEFAULT_TICKS_PER_SLOT, NUM_TICKS_PER_SECOND} from '../timing';
2018-10-06 10:36:59 -07:00
/**
* Sign, send and confirm a transaction
*/
export async function sendAndConfirmTransaction(
connection: Connection,
transaction: Transaction,
...signers: Array<Account>
): Promise<TransactionSignature> {
let sendRetries = 10;
let signature;
2018-10-06 10:36:59 -07:00
for (;;) {
const start = Date.now();
signature = await connection.sendTransaction(transaction, ...signers);
// Wait up to a couple slots for a confirmation
2019-04-10 14:40:49 -07:00
let status = null;
let statusRetries = 6;
for (;;) {
status = await connection.getSignatureStatus(signature);
if (status) {
break;
}
if (--statusRetries <= 0) {
break;
}
// Sleep for approximately half a slot
await sleep((500 * DEFAULT_TICKS_PER_SLOT) / NUM_TICKS_PER_SECOND);
}
2019-04-10 14:40:49 -07:00
if (status && 'Ok' in status) {
break;
2018-10-23 08:35:20 -07:00
}
if (--sendRetries <= 0) {
const duration = (Date.now() - start) / 1000;
throw new Error(
`Transaction '${signature}' was not confirmed in ${duration.toFixed(
2,
2019-04-10 14:40:49 -07:00
)} seconds (${JSON.stringify(status)})`,
);
}
2018-10-23 08:35:20 -07:00
2019-04-10 14:40:49 -07:00
if (status && status.Err && !('AccountInUse' in status.Err)) {
throw new Error(`Transaction ${signature} failed (${JSON.stringify(status)})`);
2018-10-06 10:36:59 -07:00
}
// Retry in 0..100ms to try to avoid another AccountInUse collision
await sleep(Math.random() * 100);
2018-10-06 10:36:59 -07:00
}
invariant(signature !== undefined);
return signature;
2018-10-06 10:36:59 -07:00
}