This repository has been archived by the owner on Jul 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 174
/
LibcoreEthereumAccountBridge.js
260 lines (224 loc) · 6.52 KB
/
LibcoreEthereumAccountBridge.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// @flow
import invariant from "invariant";
import { BigNumber } from "bignumber.js";
import {
FeeNotLoaded,
InvalidAddress,
NotEnoughBalance
} from "@ledgerhq/errors";
import type { Unit, TokenAccount, Account } from "../types";
import type { AccountBridge } from "./types";
import { getEstimatedFees } from "../api/Fees";
import { syncAccount } from "../libcore/syncAccount";
import { isValidRecipient } from "../libcore/isValidRecipient";
import { getFeesForTransaction } from "../libcore/getFeesForTransaction";
import libcoreSignAndBroadcast from "../libcore/signAndBroadcast";
import { makeLRUCache } from "../cache";
import { apiForCurrency } from "../api/Ethereum";
export type Transaction = {
recipient: string,
amount: BigNumber,
gasPrice: ?BigNumber,
gasLimit: BigNumber,
feeCustomUnit: ?Unit,
tokenAccountId?: ?string,
useAllAmount?: boolean,
networkInfo: ?{ serverFees: { gas_price: number } }
};
const getTransactionAccount = (a, t): Account | TokenAccount => {
const { tokenAccountId } = t;
return tokenAccountId
? (a.tokenAccounts || []).find(ta => ta.id === tokenAccountId) || a
: a;
};
const asLibcoreTransaction = ({
amount,
recipient,
gasPrice,
tokenAccountId,
gasLimit,
useAllAmount
}) => ({
amount,
recipient,
tokenAccountId,
gasPrice: gasPrice || undefined,
gasLimit: gasLimit || undefined,
useAllAmount
});
const startSync = (initialAccount, _observation) => syncAccount(initialAccount);
const checkValidRecipient = makeLRUCache(
(account, recipient) => {
if (!recipient)
return Promise.reject(
new InvalidAddress("", { currencyName: account.currency.name })
);
return isValidRecipient({ currency: account.currency, recipient });
},
(currency, recipient) => `${currency.id}_${recipient}`
);
const createTransaction = a => ({
amount: BigNumber(0),
recipient: "",
gasPrice: null,
gasLimit: BigNumber(0x5208),
networkInfo: null,
feeCustomUnit: a.currency.units[1] || a.currency.units[0],
useAllAmount: false
});
const fetchTransactionNetworkInfo = async account => {
const serverFees = await getEstimatedFees(account.currency);
return {
serverFees
};
};
const getTransactionNetworkInfo = (account, transaction) =>
transaction.networkInfo;
const applyTransactionNetworkInfo = (account, transaction, networkInfo) => ({
...transaction,
networkInfo,
gasPrice:
transaction.gasPrice ||
(networkInfo.serverFees.gas_price
? BigNumber(networkInfo.serverFees.gas_price)
: null)
});
const editTransactionAmount = (account, t, amount) => ({
...t,
amount
});
const getTransactionAmount = (a, t) => t.amount;
const editTransactionRecipient = (account, t, recipient) => ({
...t,
recipient
});
const editTokenAccountId = (a, t, tokenAccountId) => ({ ...t, tokenAccountId });
const getTokenAccountId = (a, t) => t.tokenAccountId;
const getTransactionRecipient = (a, t) => t.recipient;
const editTransactionExtra = (a, t, field, value) => {
switch (field) {
case "gasLimit":
invariant(
value && BigNumber.isBigNumber(value),
"editTransactionExtra(a,t,'gasLimit',value): BigNumber value expected"
);
return { ...t, gasLimit: value };
case "gasPrice":
invariant(
!value || BigNumber.isBigNumber(value),
"editTransactionExtra(a,t,'gasPrice',value): BigNumber value expected"
);
return { ...t, gasPrice: value };
case "feeCustomUnit":
invariant(
value,
"editTransactionExtra(a,t,'feeCustomUnit',value): value is expected"
);
return { ...t, feeCustomUnit: value };
case "useAllAmount":
invariant(
typeof value === "boolean",
"editTransactionExtra(a,t,'useAllAmount',value): boolean value expected"
);
return { ...t, useAllAmount: value };
default:
return t;
}
};
const getTransactionExtra = (a, t, field) => {
switch (field) {
case "gasLimit":
return t.gasLimit;
case "gasPrice":
return t.gasPrice;
case "feeCustomUnit":
return t.feeCustomUnit;
case "useAllAmount":
return t.useAllAmount;
default:
return undefined;
}
};
const signAndBroadcast = (account, transaction, deviceId) =>
libcoreSignAndBroadcast({
account,
transaction: asLibcoreTransaction(transaction),
deviceId
});
const getFees = makeLRUCache(
async (a, t) => {
await checkValidRecipient(a, t.recipient);
return getFeesForTransaction({
account: a,
transaction: asLibcoreTransaction(t)
});
},
(a, t) =>
`${a.id}_${a.blockHeight || 0}_${t.amount.toString()}_${t.recipient}_${
t.gasLimit ? t.gasLimit.toString() : ""
}_${t.gasPrice ? t.gasPrice.toString() : ""}`
);
const checkValidTransaction = async (a, t) =>
!t.gasPrice
? Promise.reject(new FeeNotLoaded())
: t.useAllAmount ||
getMaxAmount(a, t).then(max => t.amount.isLessThanOrEqualTo(max))
? Promise.resolve(null)
: Promise.reject(new NotEnoughBalance());
const getTotalSpent = (a, t) => {
const tAccount = getTransactionAccount(a, t);
if (t.useAllAmount) {
return Promise.resolve(tAccount.balance);
}
const amount = BigNumber(t.amount || "0");
if (
amount.isZero() ||
!t.gasPrice ||
t.gasPrice.isZero() ||
t.gasLimit.isZero() ||
tAccount.type === "TokenAccount"
) {
return Promise.resolve(amount);
}
return getFees(a, t).then(totalFees => amount.plus(totalFees || 0));
};
const getMaxAmount = async (a, t) => {
const tAccount = getTransactionAccount(a, t);
if (tAccount.type === "TokenAccount") {
return Promise.resolve(tAccount.balance);
}
return getFees(a, t).then(totalFees =>
tAccount.balance.minus(totalFees || 0)
);
};
const prepareTransaction = (a, t) => {
const api = apiForCurrency(a.currency);
const tAccount = getTransactionAccount(a, t);
const o =
tAccount.type === "TokenAccount"
? api.estimateGasLimitForERC20(tAccount.token.contractAddress)
: api.estimateGasLimitForERC20(t.recipient);
return o.then(gasLimit => ({ ...t, gasLimit: BigNumber(gasLimit) }));
};
const bridge: AccountBridge<Transaction> = {
startSync,
checkValidRecipient,
createTransaction,
fetchTransactionNetworkInfo,
getTransactionNetworkInfo,
applyTransactionNetworkInfo,
editTokenAccountId,
getTokenAccountId,
editTransactionAmount,
getTransactionAmount,
editTransactionRecipient,
getTransactionRecipient,
editTransactionExtra,
getTransactionExtra,
checkValidTransaction,
getTotalSpent,
getMaxAmount,
signAndBroadcast,
prepareTransaction
};
export default bridge;