1// /lib/tank: functions for funding transactions
3import retry from 'async-retry';
4import { toBN } from 'web3-utils';
5import { RETRY_OPTIONS, waitForTransactionConfirm } from './txn';
7//NOTE if accessing this in a localhost configuration fails with "CORS request
8// did not succeed", you might need to visit localhost:3001 or whatever
9// explicitly and tell your browser that's safe to access.
10// https://stackoverflow.com/a/53011185/1334324
11const baseUrl = 'https://localhost:3001';
13function sendRequest(where, what) {
14 return new Promise((resolve, reject) => {
15 fetch(baseUrl + where, {
19 'Content-Type': 'application/json',
21 body: JSON.stringify(what),
25 resolve(response.json());
34const remainingTransactions = point => {
35 if (typeof point === 'string') point = Number(point);
36 return sendRequest('/point', { point: point });
39const fundTransactions = signedTxs => {
40 return sendRequest('/request', { txs: signedTxs });
43// resolves when address has at least cost balance
44// returns true if gas tank was used, false otherwise
45// askForFunding: callback that takes (address, requiredBalance, currentBalance)
46// and tells the user to get that address the required balance
47// gotFunding: optional callback that stops telling the user to go get funding
48const ensureFundsFor = async (
57 let balance = toBN(await web3.eth.getBalance(address));
60 if (cost.gt(balance)) {
63 const fundsRemaining = await remainingTransactions(point);
64 if (fundsRemaining < signedTxs.length) {
65 throw new Error('tank: request invalid');
68 console.log('tank: skipping remaining-funds check');
69 //TODO if we can't always (easily) provide a point, and the
70 // fundTransactions call is gonna fail anyway, should we maybe
71 // just not bother doing this check in the first place?
74 const res = await fundTransactions(signedTxs);
76 throw new Error('tank: request rejected', res);
78 await waitForTransactionConfirm(web3, res.txHash);
79 let newBalance = await web3.eth.getBalance(address);
81 'tank: funds have confirmed',
88 console.log('tank: funding failed', e);
99 'tank: already have sufficient funds',
108// returns a promise that resolves when address has at least minBalance
109function waitForBalance(web3, address, minBalance, askForFunding, gotFunding) {
110 minBalance = toBN(minBalance);
111 return retry(async (bail, n) => {
112 const balance = toBN(await web3.eth.getBalance(address));
113 if (balance.gte(minBalance)) {
114 gotFunding && gotFunding();
117 askForFunding(address, minBalance, balance);
118 throw new Error('retrying');
123export { remainingTransactions, fundTransactions, ensureFundsFor };
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list