-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathImportInCTxBuilder.ts
More file actions
354 lines (308 loc) · 12.9 KB
/
ImportInCTxBuilder.ts
File metadata and controls
354 lines (308 loc) · 12.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
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { BuildTransactionError, NotSupported, TransactionType } from '@bitgo/sdk-core';
import { AtomicInCTransactionBuilder } from './atomicInCTransactionBuilder';
import {
evmSerial,
UnsignedTx,
Credential,
BigIntPr,
Int,
Id,
TransferableInput,
Address,
utils as FlareUtils,
} from '@flarenetwork/flarejs';
import utils from './utils';
import { DecodedUtxoObj, FlareTransactionType, SECP256K1_Transfer_Output, Tx } from './iface';
export class ImportInCTxBuilder extends AtomicInCTransactionBuilder {
constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
}
/**
* C-chain address who is target of the import.
* Address format is eth like
* @param {string} cAddress
*/
to(cAddress: string): this {
this.transaction._to = [utils.parseAddress(cAddress)];
return this;
}
protected get transactionType(): TransactionType {
return TransactionType.Import;
}
initBuilder(tx: Tx, rawBytes?: Buffer, parsedCredentials?: Credential[]): this {
const baseTx = tx as evmSerial.ImportTx;
if (!this.verifyTxType(baseTx._type)) {
throw new NotSupported('Transaction cannot be parsed or has an unsupported transaction type');
}
// The outputs is a single C-Chain address result.
// It's expected to have only one output to the destination C-Chain address.
const outputs = baseTx.Outs;
if (outputs.length !== 1) {
throw new BuildTransactionError('Transaction can have one output');
}
const output = outputs[0];
if (Buffer.from(output.assetId.toBytes()).toString('hex') !== this.transaction._assetId) {
throw new Error('AssetID are not equals');
}
this.transaction._to = [Buffer.from(output.address.toBytes())];
const inputs = baseTx.importedInputs;
this.transaction._utxos = this.recoverUtxos(inputs);
// Calculate total input and output amounts
const totalInputAmount = inputs.reduce((t, i) => t + i.amount(), BigInt(0));
const totalOutputAmount = output.amount.value();
// Calculate fee based on input/output difference
const fee = totalInputAmount - totalOutputAmount;
// Use credentials passed from TransactionBuilderFactory (properly extracted using codec)
const credentials = parsedCredentials || [];
const hasCredentials = credentials.length > 0;
// If it's a signed transaction, store the original raw bytes to preserve exact format
if (hasCredentials && rawBytes) {
this.transaction._rawSignedBytes = rawBytes;
}
// Extract threshold from first input's sigIndicies (number of required signatures)
const firstInput = inputs[0];
const inputThreshold = firstInput.sigIndicies().length || this.transaction._threshold;
this.transaction._threshold = inputThreshold;
// Create a temporary UnsignedTx for accurate fee size calculation
// This includes the full structure (ImportTx, AddressMaps, Credentials)
const tempAddressMap = new FlareUtils.AddressMap();
for (let i = 0; i < inputThreshold; i++) {
if (this.transaction._fromAddresses && this.transaction._fromAddresses[i]) {
tempAddressMap.set(new Address(this.transaction._fromAddresses[i]), i);
}
}
const tempAddressMaps = new FlareUtils.AddressMaps([tempAddressMap]);
const tempCredentials =
credentials.length > 0 ? credentials : [new Credential(Array(inputThreshold).fill(utils.createNewSig('')))];
const tempUnsignedTx = new UnsignedTx(baseTx, [], tempAddressMaps, tempCredentials);
// Calculate cost units using the full UnsignedTx structure
const feeSize = this.calculateImportCost(tempUnsignedTx);
// Use integer division to ensure feeRate can be converted back to BigInt
const feeRate = Math.floor(Number(fee) / feeSize);
this.transaction._fee = {
fee: fee.toString(),
feeRate: feeRate,
size: feeSize,
};
// Create AddressMaps based on signature slot order (matching credential order), not sorted addresses
// This matches the approach used in credentials: addressesIndex determines signature order
// AddressMaps should map addresses to signature slots in the same order as credentials
// If _fromAddresses is available, create AddressMap based on UTXO order (matching credential order)
// Otherwise, fall back to mapping just the output address
const firstUtxo = this.transaction._utxos[0];
let addressMap: FlareUtils.AddressMap;
if (
firstUtxo &&
firstUtxo.addresses &&
firstUtxo.addresses.length > 0 &&
this.transaction._fromAddresses &&
this.transaction._fromAddresses.length >= this.transaction._threshold
) {
// Use centralized method for AddressMap creation
addressMap = this.createAddressMapForUtxo(firstUtxo, this.transaction._threshold);
} else {
// Fallback: map output address to slot 0 (for C-chain imports, output is the destination)
// Or map addresses sequentially if _fromAddresses is available but UTXO addresses are not
addressMap = new FlareUtils.AddressMap();
if (this.transaction._fromAddresses && this.transaction._fromAddresses.length >= this.transaction._threshold) {
this.transaction._fromAddresses.slice(0, this.transaction._threshold).forEach((addr, i) => {
addressMap.set(new Address(addr), i);
});
} else {
// Last resort: map output address
const toAddress = new Address(output.address.toBytes());
addressMap.set(toAddress, 0);
}
}
const addressMaps = new FlareUtils.AddressMaps([addressMap]);
// When credentials were extracted, use them directly to preserve existing signatures
// For initBuilder, _fromAddresses may not be set yet, so use all zeros for credential slots
let txCredentials: Credential[];
if (credentials.length > 0) {
txCredentials = credentials;
} else {
// Create empty credential with threshold number of signature slots (all zeros)
const emptySignatures: ReturnType<typeof utils.createNewSig>[] = [];
for (let i = 0; i < inputThreshold; i++) {
emptySignatures.push(utils.createNewSig(''));
}
txCredentials = [new Credential(emptySignatures)];
}
const unsignedTx = new UnsignedTx(baseTx, [], addressMaps, txCredentials);
this.transaction.setTransaction(unsignedTx);
return this;
}
static verifyTxType(txnType: string): boolean {
return txnType === FlareTransactionType.EvmImportTx;
}
verifyTxType(txnType: string): boolean {
return ImportInCTxBuilder.verifyTxType(txnType);
}
/**
* Build the import in C-chain transaction
* @protected
*/
protected buildFlareTransaction(): void {
// if tx has credentials or was already recovered from raw, tx shouldn't change
if (this.transaction.hasCredentials) return;
if (this.transaction._to.length !== 1) {
throw new Error('to is required');
}
if (!this.transaction._fee.feeRate) {
throw new Error('fee rate is required');
}
const { inputs, amount, credentials } = this.createInputs();
// Calculate import cost units (matching AVAXP's costImportTx approach)
// Create a temporary UnsignedTx with full amount to calculate fee size
// This includes the full structure (ImportTx, AddressMaps, Credentials) for accurate size calculation
const tempOutput = new evmSerial.Output(
new Address(this.transaction._to[0]),
new BigIntPr(amount),
new Id(new Uint8Array(Buffer.from(this.transaction._assetId, 'hex')))
);
const tempImportTx = new evmSerial.ImportTx(
new Int(this.transaction._networkID),
new Id(new Uint8Array(Buffer.from(this.transaction._blockchainID, 'hex'))),
new Id(new Uint8Array(this._externalChainId)),
inputs,
[tempOutput]
);
// Create AddressMaps for fee calculation (same as final transaction)
const firstUtxo = this.transaction._utxos[0];
const tempAddressMap = firstUtxo
? this.createAddressMapForUtxo(firstUtxo, this.transaction._threshold)
: new FlareUtils.AddressMap();
const tempAddressMaps = new FlareUtils.AddressMaps([tempAddressMap]);
// Create temporary UnsignedTx with full structure for accurate fee calculation
const tempUnsignedTx = new UnsignedTx(tempImportTx, [], tempAddressMaps, credentials);
// Calculate feeSize once using full UnsignedTx (matching AVAXP approach)
const feeSize = this.calculateImportCost(tempUnsignedTx);
const feeRate = BigInt(this.transaction._fee.feeRate);
const fee = feeRate * BigInt(feeSize);
// Validate that we have enough funds to cover the fee
if (amount <= fee) {
throw new BuildTransactionError(
`Insufficient funds: have ${amount.toString()}, need more than ${fee.toString()} for fee`
);
}
this.transaction._fee.fee = fee.toString();
this.transaction._fee.size = feeSize;
// Create EVM output using proper FlareJS class with amount minus fee
const output = new evmSerial.Output(
new Address(this.transaction._to[0]),
new BigIntPr(amount - fee),
new Id(new Uint8Array(Buffer.from(this.transaction._assetId, 'hex')))
);
// Create the import transaction
const importTx = new evmSerial.ImportTx(
new Int(this.transaction._networkID),
new Id(new Uint8Array(Buffer.from(this.transaction._blockchainID, 'hex'))),
new Id(new Uint8Array(this._externalChainId)),
inputs,
[output]
);
// Reuse the AddressMaps already calculated for fee calculation
const unsignedTx = new UnsignedTx(
importTx,
[], // Empty UTXOs array, will be filled during processing
tempAddressMaps,
credentials
);
this.transaction.setTransaction(unsignedTx);
}
/**
* Create inputs from UTXOs
* @return {
* inputs: TransferableInput[];
* credentials: Credential[];
* amount: bigint;
* }
*/
protected createInputs(): {
inputs: TransferableInput[];
credentials: Credential[];
amount: bigint;
} {
const sender = this.transaction._fromAddresses.slice();
if (this.recoverSigner) {
// switch first and last signer
const tmp = sender.pop();
sender.push(sender[0]);
if (tmp) {
sender[0] = tmp;
}
}
let totalAmount = BigInt(0);
const inputs: TransferableInput[] = [];
const credentials: Credential[] = [];
this.transaction._utxos.forEach((utxo) => {
const amount = BigInt(utxo.amount);
totalAmount += amount;
// Create signature indices for threshold
const sigIndices: number[] = [];
for (let i = 0; i < this.transaction._threshold; i++) {
sigIndices.push(i);
}
// Use fromNative to create TransferableInput (same pattern as ImportInPTxBuilder)
// fromNative expects cb58-encoded strings for txId and assetId
const txIdCb58 = utxo.txid; // Already cb58 encoded
const assetIdCb58 = utils.cb58Encode(Buffer.from(this.transaction._assetId, 'hex'));
const transferableInput = TransferableInput.fromNative(
txIdCb58,
Number(utxo.outputidx),
assetIdCb58,
amount,
sigIndices
);
inputs.push(transferableInput);
// Create credential with empty signatures for slot identification
// Match avaxp behavior: dynamic ordering based on addressesIndex from UTXO
// Use centralized method for credential creation
credentials.push(this.createCredentialForUtxo(utxo, this.transaction._threshold));
});
return {
inputs,
credentials,
amount: totalAmount,
};
}
/**
* @param unsignedTx The UnsignedTx to calculate the cost for (includes ImportTx, AddressMaps, and Credentials)
* @returns The total cost units
*/
private calculateImportCost(unsignedTx: UnsignedTx): number {
const signedTxBytes = unsignedTx.getSignedTx().toBytes();
const txBytesGas = 1;
let bytesCost = signedTxBytes.length * txBytesGas;
const costPerSignature = 1000;
const importTx = unsignedTx.getTx() as evmSerial.ImportTx;
importTx.importedInputs.forEach((input: TransferableInput) => {
const inCost = costPerSignature * input.sigIndicies().length;
bytesCost += inCost;
});
const fixedFee = 10000;
return bytesCost + fixedFee;
}
/**
* Recover UTXOs from imported inputs
* @param importedInputs Array of transferable inputs
* @returns Array of decoded UTXO objects
*/
private recoverUtxos(importedInputs: TransferableInput[]): DecodedUtxoObj[] {
return importedInputs.map((input) => {
const txid = input.utxoID.toString();
const outputidx = input.utxoID.outputIdx.toString();
return {
outputID: SECP256K1_Transfer_Output,
amount: input.amount().toString(),
txid: utils.cb58Encode(Buffer.from(txid, 'hex')),
outputidx: outputidx,
threshold: this.transaction._threshold,
addresses: this.transaction._fromAddresses.map((addr) =>
utils.addressToString(this.transaction._network.hrp, this.transaction._network.alias, Buffer.from(addr))
),
};
});
}
}