-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathImportInCTxBuilder.ts
More file actions
282 lines (242 loc) · 9.19 KB
/
ImportInCTxBuilder.ts
File metadata and controls
282 lines (242 loc) · 9.19 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
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,
avmSerial,
} 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;
const feeSize = this.calculateFeeSize(baseTx);
// 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,
};
// 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 proper UnsignedTx wrapper with credentials
const toAddress = new Address(output.address.toBytes());
const addressMap = new FlareUtils.AddressMap([[toAddress, 0]]);
const addressMaps = new FlareUtils.AddressMaps([addressMap]);
// When credentials were extracted, use them directly to preserve existing signatures
let txCredentials: Credential[];
if (credentials.length > 0) {
txCredentials = credentials;
} else {
// Create empty credential with threshold number of signature slots
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 fee is already calculated (from initBuilder), the transaction is already built
if (this.transaction._fee.fee) 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 fee
const feeRate = BigInt(this.transaction._fee.feeRate);
const feeSize = this.calculateFeeSize();
const fee = feeRate * BigInt(feeSize);
this.transaction._fee.fee = fee.toString();
this.transaction._fee.size = feeSize;
// Create EVM output using proper FlareJS class
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]
);
// Create unsigned transaction with all potential signers in address map
const addressMap = new FlareUtils.AddressMap();
this.transaction._fromAddresses.forEach((addr, i) => {
addressMap.set(new Address(addr), i);
});
const addressMaps = new FlareUtils.AddressMaps([addressMap]);
const unsignedTx = new UnsignedTx(
importTx,
[], // Empty UTXOs array, will be filled during processing
addressMaps,
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 empty credential for each input with threshold signers
const emptySignatures = sigIndices.map(() => utils.createNewSig(''));
const credential = new Credential(emptySignatures);
credentials.push(credential);
});
return {
inputs,
credentials,
amount: totalAmount,
};
}
/**
* Calculate the fee size for the transaction
* For C-chain imports, the feeRate is treated as an absolute fee value
*/
private calculateFeeSize(tx?: evmSerial.ImportTx): number {
// If tx is provided, calculate based on actual transaction size
if (tx) {
const codec = avmSerial.getAVMManager().getDefaultCodec();
return tx.toBytes(codec).length;
}
// For C-chain imports, treat feeRate as the absolute fee (multiplier of 1)
return 1;
}
/**
* 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))
),
};
});
}
}