From a596e99b4a66651348868a5328cf09011e2da323 Mon Sep 17 00:00:00 2001 From: Michael Vines Date: Sat, 6 Oct 2018 10:36:59 -0700 Subject: [PATCH] feat: Add sendAndConfirmTransaction --- .../src/util/send-and-confirm-transaction.js | 32 +++++++++++++++++++ web3.js/src/util/sleep.js | 6 ++++ 2 files changed, 38 insertions(+) create mode 100644 web3.js/src/util/send-and-confirm-transaction.js create mode 100644 web3.js/src/util/sleep.js diff --git a/web3.js/src/util/send-and-confirm-transaction.js b/web3.js/src/util/send-and-confirm-transaction.js new file mode 100644 index 0000000000..d81f7537dc --- /dev/null +++ b/web3.js/src/util/send-and-confirm-transaction.js @@ -0,0 +1,32 @@ +// @flow + +import {Connection, Transaction} from '..'; + +import {sleep} from './sleep'; + +import type {Account} from '..'; + +/** + * Sign, send and confirm a transaction + */ +export async function sendAndConfirmTransaction( + connection: Connection, + from: Account, + transaction: Transaction, + runtimeErrorOk: boolean = false +): Promise { + const signature = await connection.sendTransaction(from, transaction); + + // Wait up to a couple seconds for a confirmation + let i = 4; + for (;;) { + const status = await connection.getSignatureStatus(signature); + if (status == 'Confirmed') return; + if (runtimeErrorOk && status == 'ProgramRuntimeError') return; + await sleep(500); + if (--i < 0) { + throw new Error(`Transaction '${signature}' was not confirmed (${status})`); + } + } +} + diff --git a/web3.js/src/util/sleep.js b/web3.js/src/util/sleep.js new file mode 100644 index 0000000000..961d48c457 --- /dev/null +++ b/web3.js/src/util/sleep.js @@ -0,0 +1,6 @@ +// @flow + +// zzz +export function sleep(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); +}