on 8adeea8 help sign in
bridge/src/lib/tank.js
141 lines 4.2 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';
6import { WALLET_TYPES } from 'lib/wallet';
8//NOTE if accessing this in a localhost configuration fails with "CORS request
9// did not succeed", you might need to visit localhost:3001 or whatever
10// explicitly and tell your browser that's safe to access.
11// https://stackoverflow.com/a/53011185/1334324
12const baseUrl = 'https://gas-tank.urbit.org:3001';
14function sendRequest(where, what) {
15 return new Promise((resolve, reject) => {
16 fetch(baseUrl + where, {
17 method: 'POST',
18 cache: 'no-cache',
19 headers: {
20 'Content-Type': 'application/json',
21 },
22 body: JSON.stringify(what),
23 })
24 .then(response => {
25 if (response.ok) {
26 resolve(response.json());
27 } else {
28 reject(response);
29 }
30 })
31 .catch(reject);
32 });
35const remainingTransactions = point => {
36 if (typeof point === 'string') point = Number(point);
37 return sendRequest('/point', { point: point });
38};
40const fundTransactions = signedTxs => {
41 return sendRequest('/request', { txs: signedTxs });
42};
44// resolves when address has at least cost balance
45// returns true if gas tank was used, false otherwise
46// askForFunding: callback that takes (address, requiredBalance, currentBalance)
47// and tells the user to get that address the required balance
48// gotFunding: optional callback that stops telling the user to go get funding
49const ensureFundsFor = async (
50 web3,
51 point,
52 address,
53 walletType,
54 cost,
55 signedTxs,
56 askForFunding,
57 gotFunding
58) => {
59 const balance = toBN(await web3.eth.getBalance(address));
60 cost = toBN(cost);
62 if (balance.gte(cost)) {
63 console.log(
64 `tank: already have sufficient funds: ${address} proposed ` +
65 `transaction(s) that will cost ${cost.toString()}wei but it ` +
66 `already has ${balance.toString()}wei`
67 );
68 return false;
69 }
71 if (walletType === WALLET_TYPES.METAMASK) {
72 console.log('tank: disabling for metamask login');
74 return false;
75 }
76 try {
77 // TODO: if we can't always (easily) provide a point, and the
78 // fundTransactions call is gonna fail anyway, should we maybe
79 // just not bother doing this check in the first place?
80 if (point !== null) {
81 const fundsRemaining = await remainingTransactions(point);
82 if (fundsRemaining < signedTxs.length) {
83 throw new Error('tank: request invalid');
84 }
85 } else {
86 console.log('tank: no point provided. skipping remaining-funds check...');
87 }
89 const res = await fundTransactions(signedTxs);
90 if (!res.success) {
91 throw new Error(`tank: request rejected ${JSON.stringify(res)}`);
92 }
94 await waitForTransactionConfirm(web3, res.txHash);
96 const newBalance = toBN(await web3.eth.getBalance(address));
98 // sanity check
99 if (newBalance.lt(cost)) {
100 throw new Error(
101 `tank: transaction funded but the new balance of ` +
102 `${newBalance.toString()}wei is still less than ` +
103 `${cost.toString()}wei.`
104 );
105 }
107 console.log(
108 `tank: funds have confirmed: ${address} now has ` +
109 `${newBalance.toString()}wei, up from ${balance.toString()}wei`
110 );
111 return true;
112 } catch (error) {
113 console.error(error);
114 await waitForBalance(
115 web3,
116 address,
117 cost.toString(),
118 askForFunding,
119 gotFunding
120 );
121 }
123 return false;
124};
126// returns a promise that resolves when address has at least minBalance
127function waitForBalance(web3, address, minBalance, askForFunding, gotFunding) {
128 minBalance = toBN(minBalance);
129 return retry(async (bail, n) => {
130 const balance = toBN(await web3.eth.getBalance(address));
131 if (balance.gte(minBalance)) {
132 gotFunding && gotFunding();
133 return;
134 } else {
135 askForFunding(address, minBalance.toString(), balance);
136 throw new Error('retrying');
137 }
138 }, RETRY_OPTIONS);
141export { remainingTransactions, fundTransactions, ensureFundsFor };