-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathatomicTransactionBuilder.ts
More file actions
415 lines (368 loc) · 14.9 KB
/
atomicTransactionBuilder.ts
File metadata and controls
415 lines (368 loc) · 14.9 KB
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { BuildTransactionError, TransactionType } from '@bitgo/sdk-core';
import { TransactionBuilder } from './transactionBuilder';
import { Transaction } from './transaction';
import { Credential, Address, utils as FlareUtils } from '@flarenetwork/flarejs';
import { DecodedUtxoObj } from './iface';
import { FlrpFeeState } from '@bitgo/public-types';
import utils from './utils';
export abstract class AtomicTransactionBuilder extends TransactionBuilder {
protected _externalChainId: Buffer;
protected recoverSigner = false;
constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
this.transaction = new Transaction(_coinConfig);
this.transaction._fee.fee = this.fixedFee;
}
/** @inheritdoc */
protected async buildImplementation(): Promise<Transaction> {
await this.buildFlareTransaction();
this.setTransactionType(this.transactionType);
if (this.hasSigner()) {
for (const keyPair of this._signer) {
await this.transaction.sign(keyPair);
}
}
return this.transaction;
}
/**
* Builds the Flare transaction. Transaction field is changed.
*/
protected abstract buildFlareTransaction(): void | Promise<void>;
protected abstract get transactionType(): TransactionType;
/**
* Fee is fix for AVM atomic tx.
*
* @returns network.txFee
* @protected
*/
protected get fixedFee(): string {
return this.transaction._network.txFee;
}
/**
* Set the transaction type
*
* @param {TransactionType} transactionType The transaction type to be set
*/
setTransactionType(transactionType: TransactionType): void {
this.transaction._type = transactionType;
}
/**
* The internal chain is the one set for the coin in coinConfig.network. The external chain is the other chain involved.
* The external chain id is the source on import and the destination on export.
*
* @param {string} chainId - id of the external chain
*/
externalChainId(chainId: string | Buffer): this {
const newTargetChainId = typeof chainId === 'string' ? utils.cb58Decode(chainId) : Buffer.from(chainId);
this.validateChainId(newTargetChainId);
this._externalChainId = newTargetChainId;
return this;
}
/**
* Set the transaction fee
*
* @param {string | bigint} feeValue - the fee value
*/
fee(feeValue: string | bigint): this {
const fee = typeof feeValue === 'string' ? feeValue : feeValue.toString();
(this.transaction as Transaction)._fee.fee = fee;
return this;
}
/**
* Set the fee state for dynamic fee calculation (P-chain transactions)
*
* @param {FlrpFeeState} state - the fee state from the network
*/
feeState(state: FlrpFeeState): this {
this.transaction._feeState = state;
return this;
}
/**
* Set the amount for the transaction
*
* @param {bigint | string} value - the amount to transfer
*/
amount(value: bigint | string): this {
const valueBigInt = typeof value === 'string' ? BigInt(value) : value;
this.validateAmount(valueBigInt);
this.transaction._amount = valueBigInt;
return this;
}
/**
* Compute addressesIndex for UTXOs following AVAX P approach.
* addressesIndex[senderIdx] = position of sender[senderIdx] in UTXO's address list
*
* IMPORTANT: UTXO addresses are sorted lexicographically by byte value to match
* on-chain storage order. The API may return addresses in arbitrary order, but
* on-chain UTXOs always store addresses in sorted order.
*
* Example:
* A = user key, B = hsm key, C = backup key
* sender (bitgoAddresses) = [ A, B, C ]
* utxo.addresses (from API) = [ B, C, A ]
* sorted utxo.addresses = [ A, B, C ] (sorted by hex value)
* addressesIndex = [ 0, 1, 2 ]
* (sender[0]=A is at position 0 in sorted UTXO, sender[1]=B is at position 1, etc.)
*
* @protected
*/
protected computeAddressesIndex(): void {
const sender = this.transaction._fromAddresses;
this.transaction._utxos.forEach((utxo) => {
if (utxo.addressesIndex && utxo.addressesIndex.length > 0) {
return;
}
if (utxo.addresses && utxo.addresses.length > 0) {
const sortedAddresses = utils.sortAddressesByHex(utxo.addresses);
utxo.addresses = sortedAddresses;
const utxoAddresses = sortedAddresses.map((a) => utils.parseAddress(a));
utxo.addressesIndex = sender.map((a) =>
utxoAddresses.findIndex((u) => Buffer.compare(Buffer.from(u), Buffer.from(a)) === 0)
);
}
});
}
/**
* Compute addressesIndex from parsed transaction data.
* Similar to computeAddressesIndex() but used when parsing existing transactions
* via initBuilder().
*
* IMPORTANT: UTXO addresses are sorted lexicographically by byte value to match
* on-chain storage order, ensuring consistency with fresh builds.
*
* @protected
*/
protected computeAddressesIndexFromParsed(): void {
const sender = this.transaction._fromAddresses;
if (!sender || sender.length === 0) return;
this.transaction._utxos.forEach((utxo) => {
if (utxo.addresses && utxo.addresses.length > 0) {
const sortedAddresses = utils.sortAddressesByHex(utxo.addresses);
utxo.addresses = sortedAddresses;
const utxoAddresses = sortedAddresses.map((a) => utils.parseAddress(a));
utxo.addressesIndex = sender.map((senderAddr) =>
utxoAddresses.findIndex((utxoAddr) => Buffer.compare(Buffer.from(utxoAddr), Buffer.from(senderAddr)) === 0)
);
}
});
}
/**
* Validate UTXOs have consistent addresses.
* Note: UTXO threshold can differ from transaction threshold - each UTXO has its own
* signature requirement based on how it was created (e.g., change outputs may have threshold=1).
* @protected
*/
protected validateUtxoAddresses(): void {
this.transaction._utxos.forEach((utxo) => {
if (!utxo) {
throw new BuildTransactionError('Utxo is undefined');
}
if (utxo.addressesIndex?.includes(-1)) {
throw new BuildTransactionError('Addresses are inconsistent: ' + utxo.txid);
}
if (utxo.threshold !== undefined && utxo.threshold <= 0) {
throw new BuildTransactionError('UTXO threshold must be positive: ' + utxo.txid);
}
});
}
/**
* Create credential with dynamic ordering based on addressesIndex from UTXO.
* Matches AVAX P behavior: signature order depends on UTXO address positions.
*
* addressesIndex[senderIdx] = utxoPosition tells us where each sender is in the UTXO.
* We create signature slots ordered by utxoPosition (smaller position = earlier slot).
*
* @param utxo - The UTXO to create credential for
* @param threshold - Number of signatures required for this specific UTXO
* @returns Credential with empty signatures ordered based on UTXO positions
* @protected
*/
protected createCredentialForUtxo(utxo: DecodedUtxoObj, threshold: number): Credential {
const sender = this.transaction._fromAddresses;
const addressesIndex = utxo.addressesIndex ?? [];
// either user (0) or recovery (2)
const firstIndex = this.recoverSigner ? 2 : 0;
const bitgoIndex = 1;
if (threshold === 1) {
if (sender && sender.length > firstIndex && addressesIndex[firstIndex] !== undefined) {
return new Credential([utils.createEmptySigWithAddress(Buffer.from(sender[firstIndex]).toString('hex'))]);
}
return new Credential([utils.createNewSig('')]);
}
// If we have valid addressesIndex, use it to determine signature order
// addressesIndex[senderIdx] = position in UTXO
// Smaller position = earlier slot in signature array
if (addressesIndex.length >= 2 && sender && sender.length >= threshold) {
let emptySignatures: ReturnType<typeof utils.createNewSig>[];
if (addressesIndex[bitgoIndex] < addressesIndex[firstIndex]) {
emptySignatures = [
utils.createNewSig(''),
utils.createEmptySigWithAddress(Buffer.from(sender[firstIndex]).toString('hex')),
];
} else {
emptySignatures = [
utils.createEmptySigWithAddress(Buffer.from(sender[firstIndex]).toString('hex')),
utils.createNewSig(''),
];
}
return new Credential(emptySignatures);
}
const emptySignatures: ReturnType<typeof utils.createNewSig>[] = [];
for (let i = 0; i < threshold; i++) {
emptySignatures.push(utils.createNewSig(''));
}
return new Credential(emptySignatures);
}
/**
* Create AddressMap based on addressesIndex following AVAX P approach.
* Maps each sender address to its signature slot based on UTXO position ordering.
*
* addressesIndex[senderIdx] = utxoPosition
* Signature slots are ordered by utxoPosition (smaller = earlier slot).
*
* @param utxo - The UTXO to create AddressMap for
* @param threshold - Number of signatures required for this specific UTXO
* @returns AddressMap that maps addresses to signature slots based on UTXO order
* @protected
*/
protected createAddressMapForUtxo(utxo: DecodedUtxoObj, threshold: number): FlareUtils.AddressMap {
const addressMap = new FlareUtils.AddressMap();
const sender = this.transaction._fromAddresses;
const addressesIndex = utxo.addressesIndex ?? [];
const firstIndex = this.recoverSigner ? 2 : 0;
const bitgoIndex = 1;
if (threshold === 1) {
if (sender && sender.length > firstIndex) {
addressMap.set(new Address(sender[firstIndex]), 0);
} else if (sender && sender.length > 0) {
addressMap.set(new Address(sender[0]), 0);
}
return addressMap;
}
if (addressesIndex.length >= 2 && sender && sender.length >= threshold) {
if (addressesIndex[bitgoIndex] < addressesIndex[firstIndex]) {
addressMap.set(new Address(sender[bitgoIndex]), 0);
addressMap.set(new Address(sender[firstIndex]), 1);
} else {
addressMap.set(new Address(sender[firstIndex]), 0);
addressMap.set(new Address(sender[bitgoIndex]), 1);
}
return addressMap;
}
if (sender && sender.length >= threshold) {
sender.slice(0, threshold).forEach((addr, i) => {
addressMap.set(new Address(addr), i);
});
}
return addressMap;
}
/**
* Create credential using the ACTUAL sigIndices from FlareJS.
*
* This method determines which sender addresses correspond to which sigIndex positions,
* then creates the credential with signatures in the correct order matching the sigIndices.
*
* sigIndices tell us which positions in the UTXO's owner addresses need to sign.
* We need to figure out which sender addresses are at those positions and create
* signature slots in the same order as sigIndices.
*
* @param utxo - The UTXO to create credential for
* @param threshold - Number of signatures required
* @param actualSigIndices - The actual sigIndices from FlareJS's built input
* @returns Credential with signatures ordered to match sigIndices
* @protected
*/
protected createCredentialForUtxoWithSigIndices(
utxo: DecodedUtxoObj,
threshold: number,
actualSigIndices: number[]
): Credential {
const sender = this.transaction._fromAddresses;
const addressesIndex = utxo.addressesIndex ?? [];
// either user (0) or recovery (2)
const firstIndex = this.recoverSigner ? 2 : 0;
if (threshold === 1) {
if (sender && sender.length > firstIndex && addressesIndex[firstIndex] !== undefined) {
return new Credential([utils.createEmptySigWithAddress(Buffer.from(sender[firstIndex]).toString('hex'))]);
}
return new Credential([utils.createNewSig('')]);
}
// For threshold >= 2, use the actual sigIndices order from FlareJS
// sigIndices[i] = position in UTXO's owner addresses that needs to sign
// addressesIndex[senderIdx] = position in UTXO's owner addresses for that sender
//
// We need to find which sender corresponds to each sigIndex and create signatures
// in the sigIndices order.
if (actualSigIndices.length >= 2 && addressesIndex.length >= 2 && sender && sender.length >= threshold) {
const emptySignatures: ReturnType<typeof utils.createNewSig>[] = [];
for (const sigIdx of actualSigIndices) {
// Find which sender address is at this UTXO position
// addressesIndex[senderIdx] tells us which UTXO position each sender is at
const senderIdx = addressesIndex.findIndex((utxoPos) => utxoPos === sigIdx);
if (senderIdx === firstIndex) {
// This sigIndex slot is for user/recovery - embed their address
emptySignatures.push(utils.createEmptySigWithAddress(Buffer.from(sender[firstIndex]).toString('hex')));
} else {
// BitGo (HSM) or unknown sender - empty signature
emptySignatures.push(utils.createNewSig(''));
}
}
return new Credential(emptySignatures);
}
// Fallback: create threshold empty signatures
const emptySignatures: ReturnType<typeof utils.createNewSig>[] = [];
for (let i = 0; i < threshold; i++) {
emptySignatures.push(utils.createNewSig(''));
}
return new Credential(emptySignatures);
}
/**
* Create AddressMap using the ACTUAL sigIndices from FlareJS.
*
* Maps sender addresses to signature slots based on the actual sigIndices order.
*
* @param utxo - The UTXO to create AddressMap for
* @param threshold - Number of signatures required
* @param actualSigIndices - The actual sigIndices from FlareJS's built input
* @returns AddressMap that maps addresses to signature slots
* @protected
*/
protected createAddressMapForUtxoWithSigIndices(
utxo: DecodedUtxoObj,
threshold: number,
actualSigIndices: number[]
): FlareUtils.AddressMap {
const addressMap = new FlareUtils.AddressMap();
const sender = this.transaction._fromAddresses;
const addressesIndex = utxo.addressesIndex ?? [];
const firstIndex = this.recoverSigner ? 2 : 0;
const bitgoIndex = 1;
if (threshold === 1) {
if (sender && sender.length > firstIndex) {
addressMap.set(new Address(sender[firstIndex]), 0);
} else if (sender && sender.length > 0) {
addressMap.set(new Address(sender[0]), 0);
}
return addressMap;
}
// For threshold >= 2, map addresses based on actual sigIndices order
if (actualSigIndices.length >= 2 && addressesIndex.length >= 2 && sender && sender.length >= threshold) {
actualSigIndices.forEach((sigIdx, slotIdx) => {
// Find which sender is at this UTXO position
const senderIdx = addressesIndex.findIndex((utxoPos) => utxoPos === sigIdx);
if (senderIdx === bitgoIndex || senderIdx === firstIndex) {
addressMap.set(new Address(sender[senderIdx]), slotIdx);
}
});
return addressMap;
}
// Fallback
if (sender && sender.length >= threshold) {
sender.slice(0, threshold).forEach((addr, i) => {
addressMap.set(new Address(addr), i);
});
}
return addressMap;
}
}