-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathImportInCTxBuilder.ts
More file actions
233 lines (191 loc) · 7.85 KB
/
ImportInCTxBuilder.ts
File metadata and controls
233 lines (191 loc) · 7.85 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
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { BuildTransactionError, NotSupported, TransactionType } from '@bitgo/sdk-core';
import { AtomicInCTransactionBuilder } from './atomicInCTransactionBuilder';
import {
evmSerial,
UnsignedTx,
Credential,
TransferableInput,
TransferInput,
TransferOutput,
utils as FlareUtils,
evm,
} 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');
}
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;
const firstInput = inputs[0];
const inputThreshold = firstInput.sigIndicies().length || this.transaction._threshold;
this.transaction._threshold = inputThreshold;
this.transaction._utxos = this.recoverUtxos(inputs);
const totalInputAmount = inputs.reduce((t, i) => t + i.amount(), BigInt(0));
const totalOutputAmount = output.amount.value();
const fee = totalInputAmount - totalOutputAmount;
const credentials = parsedCredentials || [];
const hasCredentials = credentials.length > 0;
if (hasCredentials && rawBytes) {
this.transaction._rawSignedBytes = rawBytes;
}
this.transaction._fee = {
fee: fee.toString(),
};
this.computeAddressesIndexFromParsed();
const addressMaps = this.transaction._utxos.map((utxo) => {
const utxoThreshold = utxo.threshold || this.transaction._threshold;
return this.createAddressMapForUtxo(utxo, utxoThreshold);
});
const flareAddressMaps = new FlareUtils.AddressMaps(addressMaps);
let txCredentials: Credential[];
if (credentials.length > 0) {
txCredentials = credentials;
} else {
txCredentials = this.transaction._utxos.map((utxo) =>
this.createCredentialForUtxo(utxo, utxo.threshold || this.transaction._threshold)
);
}
const unsignedTx = new UnsignedTx(baseTx, [], flareAddressMaps, 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
* Following AVAX P approach for UTXO handling and signature slot assignment.
* @protected
*/
protected buildFlareTransaction(): void {
if (this.transaction.hasCredentials) return;
if (this.transaction._to.length !== 1) {
throw new BuildTransactionError('to is required');
}
if (!this.transaction._fee.fee) {
throw new BuildTransactionError('fee is required');
}
if (!this.transaction._context) {
throw new BuildTransactionError('context is required');
}
if (!this.transaction._fromAddresses || this.transaction._fromAddresses.length === 0) {
throw new BuildTransactionError('fromAddresses are required');
}
if (!this.transaction._utxos || this.transaction._utxos.length === 0) {
throw new BuildTransactionError('UTXOs are required');
}
if (!this.transaction._threshold) {
throw new BuildTransactionError('threshold is required');
}
this.computeAddressesIndex();
this.validateUtxoAddresses();
const actualFeeNFlr = BigInt(this.transaction._fee.fee);
const sourceChain = 'P';
// Convert decoded UTXOs to native FlareJS Utxo objects
const assetId = utils.cb58Encode(Buffer.from(this.transaction._assetId, 'hex'));
const nativeUtxos = utils.decodedToUtxos(this.transaction._utxos, assetId);
// Validate UTXO balance is sufficient to cover the import fee
const totalUtxoAmount = nativeUtxos.reduce((sum, utxo) => {
const output = utxo.output as TransferOutput;
return sum + output.amount();
}, BigInt(0));
if (totalUtxoAmount <= actualFeeNFlr) {
throw new BuildTransactionError(
`Insufficient UTXO balance: have ${totalUtxoAmount.toString()} nFLR, need more than ${actualFeeNFlr.toString()} nFLR to cover import fee`
);
}
const importTx = evm.newImportTx(
this.transaction._context,
this.transaction._to[0],
this.transaction._fromAddresses.map((addr) => Buffer.from(addr)),
nativeUtxos,
sourceChain,
actualFeeNFlr
);
const flareUnsignedTx = importTx as UnsignedTx;
const innerTx = flareUnsignedTx.getTx() as evmSerial.ImportTx;
const utxosWithIndex = innerTx.importedInputs.map((input) => {
const inputTxid = utils.cb58Encode(Buffer.from(input.utxoID.txID.toBytes()));
const inputOutputIdx = input.utxoID.outputIdx.value().toString();
const originalUtxo = this.transaction._utxos.find(
(utxo) => utxo.txid === inputTxid && utxo.outputidx === inputOutputIdx
);
if (!originalUtxo) {
throw new BuildTransactionError(`Could not find matching UTXO for input ${inputTxid}:${inputOutputIdx}`);
}
return {
...originalUtxo,
addressesIndex: originalUtxo.addressesIndex,
addresses: originalUtxo.addresses,
threshold: originalUtxo.threshold || this.transaction._threshold,
};
});
this.transaction._utxos = utxosWithIndex;
const txCredentials = utxosWithIndex.map((utxo) => this.createCredentialForUtxo(utxo, utxo.threshold));
const addressMaps = utxosWithIndex.map((utxo) => this.createAddressMapForUtxo(utxo, utxo.threshold));
const fixedUnsignedTx = new UnsignedTx(innerTx, [], new FlareUtils.AddressMaps(addressMaps), txCredentials);
this.transaction.setTransaction(fixedUnsignedTx);
}
/**
* Recover UTXOs from imported inputs.
* Uses fromAddresses as proxy for UTXO addresses since they should be the same
* addresses controlling the multisig.
*
* @param importedInputs Array of transferable inputs
* @returns Array of decoded UTXO objects
*/
private recoverUtxos(importedInputs: TransferableInput[]): DecodedUtxoObj[] {
const proxyAddresses =
this.transaction._fromAddresses && this.transaction._fromAddresses.length > 0
? this.transaction._fromAddresses.map((addr) =>
utils.addressToString(this.transaction._network.hrp, 'P', Buffer.from(addr))
)
: [];
return importedInputs.map((input) => {
const txid = input.utxoID.toString();
const outputidx = input.utxoID.outputIdx.toString();
const transferInput = input.input as TransferInput;
const sigIndicies = transferInput.sigIndicies();
return {
outputID: SECP256K1_Transfer_Output,
amount: input.amount().toString(),
txid: utils.cb58Encode(Buffer.from(txid, 'hex')),
outputidx: outputidx,
threshold: sigIndicies.length || this.transaction._threshold,
addresses: proxyAddresses,
addressesIndex: sigIndicies,
};
});
}
}