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
/
libcore.js
272 lines (241 loc) · 7.19 KB
/
libcore.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
261
262
263
264
265
266
267
268
269
270
271
272
// @flow
import invariant from "invariant";
import { BigNumber } from "bignumber.js";
import {
AmountRequired,
NotEnoughBalance,
NotEnoughBalanceToDelegate,
NotEnoughBalanceInParentAccount,
FeeNotLoaded,
FeeTooHigh,
NotSupportedLegacyAddress,
InvalidAddressBecauseDestinationIsAlsoSource,
RecommendSubAccountsToEmpty,
RecommendUndelegation
} from "@ledgerhq/errors";
import { validateRecipient } from "../../../bridge/shared";
import type { Account, AccountBridge, CurrencyBridge } from "../../../types";
import type { Transaction } from "../types";
import { scanAccounts } from "../../../libcore/scanAccounts";
import { getAccountNetworkInfo } from "../../../libcore/getAccountNetworkInfo";
import { sync } from "../../../libcore/syncAccount";
import { getFeesForTransaction } from "../../../libcore/getFeesForTransaction";
import broadcast from "../libcore-broadcast";
import signOperation from "../libcore-signOperation";
import { makeLRUCache } from "../../../cache";
import { isAccountBalanceSignificant } from "../../../account";
import { withLibcore } from "../../../libcore/access";
import { libcoreBigIntToBigNumber } from "../../../libcore/buildBigNumber";
import { getCoreAccount } from "../../../libcore/getCoreAccount";
import {
fetchAllBakers,
hydrateBakers,
asBaker,
isAccountDelegating
} from "../bakers";
import { getEnv } from "../../../env";
type EstimateGasLimitAndStorage = (
Account,
string
) => Promise<{ gasLimit: BigNumber, storage: BigNumber }>;
export const estimateGasLimitAndStorage: EstimateGasLimitAndStorage = makeLRUCache(
(account, addr) =>
withLibcore(async core => {
const { coreAccount } = await getCoreAccount(core, account);
const tezosLikeAccount = await coreAccount.asTezosLikeAccount();
const gasLimit = await libcoreBigIntToBigNumber(
await tezosLikeAccount.getEstimatedGasLimit(addr)
);
// for babylon network 257 is the current cost of sending to new account.
const storage = BigNumber(257);
/*
const storage = await libcoreBigIntToBigNumber(
await tezosLikeAccount.getStorage(addr)
);
*/
return { gasLimit, storage };
}),
(a, addr) => a.id + "|" + addr
);
const calculateFees = makeLRUCache(
async (a, t) => {
return getFeesForTransaction({
account: a,
transaction: t
});
},
(a, t) =>
`${a.id}_${t.amount.toString()}_${t.recipient}_${
t.gasLimit ? t.gasLimit.toString() : ""
}_${t.fees ? t.fees.toString() : ""}_${
t.storageLimit ? t.storageLimit.toString() : ""
}_${String(t.useAllAmount)}`
);
const createTransaction = () => ({
family: "tezos",
mode: "send",
amount: BigNumber(0),
fees: null,
gasLimit: null,
storageLimit: null,
recipient: "",
networkInfo: null,
useAllAmount: false
});
const updateTransaction = (t, patch) => ({ ...t, ...patch });
const getTransactionStatus = async (a, t) => {
const errors = {};
const warnings = {};
const subAcc = !t.subAccountId
? null
: a.subAccounts && a.subAccounts.find(ta => ta.id === t.subAccountId);
invariant(
t.mode === "send" || !subAcc,
"delegation features not supported for sub accounts"
);
const account = subAcc || a;
if (t.mode !== "undelegate") {
if (account.freshAddress === t.recipient) {
errors.recipient = new InvalidAddressBecauseDestinationIsAlsoSource();
} else {
const { recipientError, recipientWarning } = await validateRecipient(
a.currency,
t.recipient
);
if (recipientError) {
errors.recipient = recipientError;
}
if (recipientWarning) {
warnings.recipient = recipientWarning;
}
}
}
if (
!getEnv("LEGACY_KT_SUPPORT_TO_YOUR_OWN_RISK") &&
t.recipient.startsWith("KT") &&
!errors.recipient
) {
errors.recipient = new NotSupportedLegacyAddress();
}
let estimatedFees = BigNumber(0);
let amount = t.amount;
if (!t.fees) {
errors.fees = new FeeNotLoaded();
} else if (!errors.recipient) {
await calculateFees(a, t).then(
res => {
estimatedFees = res.estimatedFees;
amount = res.value;
},
error => {
if (error.name === "NotEnoughBalance") {
errors.amount = error;
} else {
throw error;
}
}
);
}
if (!errors.amount && subAcc && estimatedFees.gt(a.balance)) {
errors.amount = new NotEnoughBalanceInParentAccount();
}
let totalSpent = !t.useAllAmount
? t.amount.plus(estimatedFees)
: account.balance;
if (
!errors.recipient &&
!errors.amount &&
(amount.lt(0) || totalSpent.gt(account.balance))
) {
errors.amount = new NotEnoughBalance();
totalSpent = BigNumber(0);
amount = BigNumber(0);
}
if (t.mode === "send") {
if (!errors.amount && amount.eq(0)) {
errors.amount = new AmountRequired();
} else if (amount.gt(0) && estimatedFees.times(10).gt(amount)) {
warnings.feeTooHigh = new FeeTooHigh();
}
const thresholdWarning = 0.5 * 10 ** a.currency.units[0].magnitude;
if (
!subAcc &&
!errors.amount &&
account.balance.minus(totalSpent).lt(thresholdWarning)
) {
if (isAccountDelegating(account)) {
warnings.amount = new RecommendUndelegation();
} else if ((a.subAccounts || []).some(isAccountBalanceSignificant)) {
warnings.amount = new RecommendSubAccountsToEmpty();
}
}
} else {
// delegation case, we remap NotEnoughBalance to a more precise error
if (errors.amount instanceof NotEnoughBalance) {
errors.amount = new NotEnoughBalanceToDelegate();
}
}
return Promise.resolve({
errors,
warnings,
estimatedFees,
amount,
totalSpent
});
};
const prepareTransaction = async (a, t) => {
let networkInfo = t.networkInfo;
if (!networkInfo) {
const ni = await getAccountNetworkInfo(a);
invariant(ni.family === "tezos", "tezos networkInfo expected");
networkInfo = ni;
}
let gasLimit = t.gasLimit;
let storageLimit = t.storageLimit;
if (!gasLimit || !storageLimit) {
const { recipientError } =
t.mode === "undelegate"
? {}
: await validateRecipient(a.currency, t.recipient);
if (!recipientError) {
const r = await estimateGasLimitAndStorage(a, t.recipient);
gasLimit = r.gasLimit;
storageLimit = r.storage;
}
}
let fees = t.fees || networkInfo.fees;
if (
t.networkInfo !== networkInfo ||
t.gasLimit !== gasLimit ||
t.storageLimit !== storageLimit ||
t.fees !== fees
) {
return { ...t, networkInfo, storageLimit, gasLimit, fees };
}
return t;
};
const preload = async () => {
const bakers = await fetchAllBakers();
return { bakers };
};
const hydrate = (data: mixed) => {
if (!data || typeof data !== "object") return;
const { bakers } = data;
if (!bakers || typeof bakers !== "object" || !Array.isArray(bakers)) return;
hydrateBakers(bakers.map(asBaker).filter(Boolean));
};
const currencyBridge: CurrencyBridge = {
preload,
hydrate,
scanAccounts
};
const accountBridge: AccountBridge<Transaction> = {
createTransaction,
updateTransaction,
prepareTransaction,
getTransactionStatus,
sync,
signOperation,
broadcast
};
export default { currencyBridge, accountBridge };