This repository has been archived by the owner on Jun 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 117
/
buildAccount.js
242 lines (213 loc) · 6.65 KB
/
buildAccount.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
// @flow
import isEqual from "lodash/isEqual";
import {
encodeAccountId,
getAccountPlaceholderName,
getNewAccountPlaceholderName,
} from "@ledgerhq/live-common/lib/account";
import type {
Account,
Operation,
CryptoCurrency,
DerivationMode,
} from "@ledgerhq/live-common/lib/types";
import { libcoreAmountToBigNumber } from "./buildBigNumber";
import type { Core, CoreWallet, CoreAccount, CoreOperation } from "./types";
const OperationTypeMap = {
"0": "OUT",
"1": "IN",
};
const sameImmutableOp = (a: Operation, b: Operation) =>
a === b ||
(a.id === b.id && // hash, accountId, type are in id
a.date.getTime() === b.date.getTime() &&
(a.fee ? a.fee.isEqualTo(b.fee) : a.fee === b.fee) &&
(a.value ? a.value.isEqualTo(b.value) : a.value === b.value) &&
isEqual(a.senders, b.senders) &&
isEqual(a.recipients, b.recipients));
function findExistingOp(ops, op) {
return ops.find(o => o.id === op.id);
}
export async function buildAccount({
core,
coreWallet,
coreAccount,
coreOperations,
currency,
accountIndex,
derivationMode,
seedIdentifier,
existingOperations,
}: {
core: Core,
coreWallet: CoreWallet,
coreAccount: CoreAccount,
coreOperations: CoreOperation[],
currency: CryptoCurrency,
accountIndex: number,
derivationMode: DerivationMode,
seedIdentifier: string,
existingOperations: Operation[],
}) {
const nativeBalance = await coreAccount.getBalance();
const balance = await libcoreAmountToBigNumber(core, nativeBalance);
const coreAccountCreationInfo = await coreWallet.getAccountCreationInfo(
accountIndex,
);
const derivations = await coreAccountCreationInfo.getDerivations();
const [, accountPath] = derivations;
const coreBlock = await coreAccount.getLastBlock();
const blockHeight = await coreBlock.getHeight();
const freshAddresses = await coreAccount.getFreshPublicAddresses();
const [coreFreshAddress] = freshAddresses;
if (!coreFreshAddress) throw new Error("expected at least one fresh address");
const [freshAddressStr, freshAddressPath] = await Promise.all([
coreFreshAddress.toString(),
coreFreshAddress.getDerivationPath(),
]);
if (!freshAddressPath) throw new Error("expected freshAddressPath");
const freshAddress = {
str: freshAddressStr,
path: `${accountPath}/${freshAddressPath}`,
};
const name =
coreOperations.length === 0
? getNewAccountPlaceholderName({
currency,
index: accountIndex,
derivationMode,
})
: getAccountPlaceholderName({
currency,
index: accountIndex,
derivationMode,
});
// retrieve xpub
const xpub = await coreAccount.getRestoreKey();
const accountId = encodeAccountId({
type: "libcore",
version: "1",
currencyId: currency.id,
xpubOrAddress: xpub,
derivationMode,
});
// build operations with the minimal diff & call to libcore possible
let operations = [];
let existingOps = existingOperations;
let immutableOpCmpDoneOnce = false;
for (let i = coreOperations.length - 1; i >= 0; i--) {
const coreOperation = coreOperations[i];
const newOp = await buildOperation({
core,
coreOperation,
accountId,
});
const existingOp = findExistingOp(existingOps, newOp);
if (existingOp && !immutableOpCmpDoneOnce) {
// an Operation is supposely immutable.
if (existingOp.blockHeight !== newOp.blockHeight) {
// except for blockHeight that can temporarily be null
operations.push(newOp);
continue; // eslint-disable-line no-continue
} else {
immutableOpCmpDoneOnce = true;
// we still check the first existing op we meet...
if (!sameImmutableOp(existingOp, newOp)) {
// this implement a failsafe in case an op changes (when we fix bugs)
// tradeoff: in such case, we assume all existingOps are to trash
console.warn("op mismatch. doing a full clear cache.");
existingOps = [];
operations.push(newOp);
continue; // eslint-disable-line no-continue
}
}
}
if (existingOp) {
// as soon as we've found a first matching op in old op list,
const j = existingOps.indexOf(existingOp);
const rest = existingOps.slice(j);
if (rest.length !== i + 1) {
// if libcore happen to have different number of ops that what we have,
// we actualy need to continue because we don't know where hole will be,
// but we can keep existingOp
operations.push(existingOp);
} else {
// otherwise we stop the libcore iteration and continue with previous data
// and we're done on the iteration
if (operations.length === 0 && j === 0) {
// special case: we preserve the operations array as much as possible
operations = existingOps;
} else {
operations = operations.concat(rest);
}
break;
}
} else {
// otherwise it's a new op
operations.push(newOp);
}
}
const raw: $Exact<Account> = {
id: accountId,
seedIdentifier,
xpub,
derivationMode,
index: accountIndex,
freshAddress: freshAddress.str,
freshAddressPath: freshAddress.path,
name,
balance,
blockHeight,
currency,
unit: currency.units[0],
operations,
pendingOperations: [],
lastSyncDate: new Date(),
};
return raw;
}
export async function buildOperation({
core,
coreOperation,
accountId,
}: {
core: Core,
coreOperation: CoreOperation,
accountId: string,
}) {
const bitcoinLikeOperation = await coreOperation.asBitcoinLikeOperation();
const bitcoinLikeTransaction = await bitcoinLikeOperation.getTransaction();
const hash = await bitcoinLikeTransaction.getHash();
const operationType = await coreOperation.getOperationType();
const type = OperationTypeMap[operationType];
const id = `${accountId}-${hash}-${type}`;
const coreValue = await coreOperation.getAmount();
let value = await libcoreAmountToBigNumber(core, coreValue);
const coreFee = await coreOperation.getFees();
if (!coreFee) throw new Error("fees should not be null");
const fee = await libcoreAmountToBigNumber(core, coreFee);
if (type === "OUT") {
value = value.plus(fee);
}
const blockHeight = await coreOperation.getBlockHeight();
const [recipients, senders] = await Promise.all([
coreOperation.getRecipients(),
coreOperation.getSenders(),
]);
const date = new Date(await coreOperation.getDate());
const op: $Exact<Operation> = {
id,
hash,
type,
value,
fee,
senders,
recipients,
blockHeight,
blockHash: null, // FIXME: why? (unused)
accountId,
date,
extra: {},
};
return op;
}