2018-11-28 11:56:50 -08:00
|
|
|
// @flow
|
|
|
|
|
|
|
|
import {Connection} from '../connection';
|
2019-11-11 13:01:10 -05:00
|
|
|
import type {Commitment} from '../connection';
|
2018-11-28 11:56:50 -08:00
|
|
|
import {sleep} from './sleep';
|
|
|
|
import type {TransactionSignature} from '../transaction';
|
2019-03-19 12:44:55 -07:00
|
|
|
import {DEFAULT_TICKS_PER_SLOT, NUM_TICKS_PER_SECOND} from '../timing';
|
2018-11-28 11:56:50 -08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Sign, send and confirm a raw transaction
|
|
|
|
*/
|
|
|
|
export async function sendAndConfirmRawTransaction(
|
|
|
|
connection: Connection,
|
|
|
|
rawTransaction: Buffer,
|
2019-11-11 13:01:10 -05:00
|
|
|
commitment: ?Commitment,
|
2018-11-28 11:56:50 -08:00
|
|
|
): Promise<TransactionSignature> {
|
|
|
|
const start = Date.now();
|
2020-04-06 17:56:26 +08:00
|
|
|
const statusCommitment = commitment || connection.commitment || 'max';
|
2018-11-28 11:56:50 -08:00
|
|
|
let signature = await connection.sendRawTransaction(rawTransaction);
|
|
|
|
|
2019-03-19 12:44:55 -07:00
|
|
|
// Wait up to a couple slots for a confirmation
|
2019-04-10 14:40:49 -07:00
|
|
|
let status = null;
|
2019-03-19 12:44:55 -07:00
|
|
|
let statusRetries = 6;
|
2018-11-28 11:56:50 -08:00
|
|
|
for (;;) {
|
2020-04-06 17:56:26 +08:00
|
|
|
status = (await connection.getSignatureStatus(signature)).value;
|
2019-04-10 14:40:49 -07:00
|
|
|
if (status) {
|
2020-04-06 17:56:26 +08:00
|
|
|
if (statusCommitment === 'max' && status.confirmations === null) {
|
|
|
|
break;
|
|
|
|
} else if (statusCommitment === 'recent') {
|
|
|
|
break;
|
|
|
|
}
|
2018-11-28 11:56:50 -08:00
|
|
|
}
|
|
|
|
|
2019-03-19 12:44:55 -07:00
|
|
|
// Sleep for approximately half a slot
|
|
|
|
await sleep((500 * DEFAULT_TICKS_PER_SLOT) / NUM_TICKS_PER_SECOND);
|
|
|
|
|
2018-11-28 11:56:50 -08:00
|
|
|
if (--statusRetries <= 0) {
|
|
|
|
const duration = (Date.now() - start) / 1000;
|
|
|
|
throw new Error(
|
|
|
|
`Raw Transaction '${signature}' was not confirmed in ${duration.toFixed(
|
|
|
|
2,
|
2019-04-10 14:40:49 -07:00
|
|
|
)} seconds (${JSON.stringify(status)})`,
|
2018-11-28 11:56:50 -08:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-04 21:35:08 +08:00
|
|
|
if (status && !status.err) {
|
2018-11-28 11:56:50 -08:00
|
|
|
return signature;
|
|
|
|
}
|
|
|
|
|
2019-04-23 09:53:26 -07:00
|
|
|
throw new Error(
|
|
|
|
`Raw transaction ${signature} failed (${JSON.stringify(status)})`,
|
|
|
|
);
|
2018-11-28 11:56:50 -08:00
|
|
|
}
|