on 047d86f help sign in
bridge/src/lib/tank.js
123 lines 3.6 kB history raw
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, {
16 method: 'POST',
17 cache: 'no-cache',
18 headers: {
19 'Content-Type': 'application/json',
20 },
21 body: JSON.stringify(what),
22 })
23 .then(response => {
24 if (response.ok) {
25 resolve(response.json());
26 } else {
27 reject(response);
28 }
29 })
30 .catch(reject);
31 });
34const remainingTransactions = point => {
35 if (typeof point === 'string') point = Number(point);
36 return sendRequest('/point', { point: point });
37};
39const fundTransactions = signedTxs => {
40 return sendRequest('/request', { txs: signedTxs });
41};
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 (
49 web3,
50 point,
51 address,
52 cost,
53 signedTxs,
54 askForFunding,
55 gotFunding
56) => {
57 let balance = toBN(await web3.eth.getBalance(address));
58 cost = toBN(cost);
60 if (cost.gt(balance)) {
61 try {
62 if (point !== null) {
63 const fundsRemaining = await remainingTransactions(point);
64 if (fundsRemaining < signedTxs.length) {
65 throw new Error('tank: request invalid');
66 }
67 } else {
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?
72 }
74 const res = await fundTransactions(signedTxs);
75 if (!res.success) {
76 throw new Error('tank: request rejected', res);
77 } else {
78 await waitForTransactionConfirm(web3, res.txHash);
79 let newBalance = await web3.eth.getBalance(address);
80 console.log(
81 'tank: funds have confirmed',
82 balance.toString(),
83 newBalance
84 );
85 return true;
86 }
87 } catch (e) {
88 console.log('tank: funding failed', e);
89 await waitForBalance(
90 web3,
91 address,
92 cost.toString(),
93 askForFunding,
94 gotFunding
95 );
96 }
97 } else {
98 console.log(
99 'tank: already have sufficient funds',
100 cost.toString(),
101 address,
102 balance.toString()
103 );
104 }
105 return false;
106};
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();
115 return;
116 } else {
117 askForFunding(address, minBalance, balance);
118 throw new Error('retrying');
119 }
120 }, RETRY_OPTIONS);
123export { remainingTransactions, fundTransactions, ensureFundsFor };