-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathImportInPTxBuilder.ts
More file actions
271 lines (228 loc) · 9.97 KB
/
ImportInPTxBuilder.ts
File metadata and controls
271 lines (228 loc) · 9.97 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
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { BuildTransactionError, NotSupported, TransactionType } from '@bitgo/sdk-core';
import { AtomicTransactionBuilder } from './atomicTransactionBuilder';
import {
pvmSerial,
UnsignedTx,
TransferableInput,
TransferOutput,
TransferInput,
utils as FlareUtils,
Credential,
pvm,
} from '@flarenetwork/flarejs';
import utils from './utils';
import { DecodedUtxoObj, FlareTransactionType, SECP256K1_Transfer_Output, Tx } from './iface';
export class ImportInPTxBuilder extends AtomicTransactionBuilder {
constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
this._externalChainId = utils.cb58Decode(this.transaction._network.cChainBlockchainID);
this.transaction._blockchainID = Buffer.from(utils.cb58Decode(this.transaction._network.blockchainID)).toString(
'hex'
);
}
protected get transactionType(): TransactionType {
return TransactionType.Import;
}
/**
* @param {string | string[]} senderPubKey - C-chain address(es) with C- prefix
* @throws {BuildTransactionError} if any address is not a C-chain address
*/
fromPubKey(senderPubKey: string | string[]): this {
const pubKeys = Array.isArray(senderPubKey) ? senderPubKey : [senderPubKey];
const invalidAddress = pubKeys.find((addr) => !addr.startsWith('C-'));
if (invalidAddress) {
throw new BuildTransactionError(`Invalid fromAddress: expected C-chain address (C-...), got ${invalidAddress}`);
}
this.transaction._fromAddresses = pubKeys.map((addr) => utils.parseAddress(addr));
return this;
}
/**
* @param {string[]} addresses - Array of P-chain addresses (bech32 format with P- prefix)
* @throws {BuildTransactionError} if any address is not a P-chain address
*/
to(addresses: string[]): this {
const invalidAddress = addresses.find((addr) => !addr.startsWith('P-'));
if (invalidAddress) {
throw new BuildTransactionError(`Invalid toAddress: expected P-chain address (P-...), got ${invalidAddress}`);
}
this.transaction._to = addresses.map((addr) => utils.parseAddress(addr));
return this;
}
initBuilder(tx: Tx, rawBytes?: Buffer, parsedCredentials?: Credential[]): this {
const importTx = tx as pvmSerial.ImportTx;
if (!this.verifyTxType(importTx._type)) {
throw new NotSupported('Transaction cannot be parsed or has an unsupported transaction type');
}
const outputs = importTx.baseTx.outputs;
if (outputs.length !== 1) {
throw new BuildTransactionError('Transaction can have one external output');
}
const output = outputs[0];
const assetId = output.assetId.toBytes();
if (Buffer.compare(assetId, Buffer.from(this.transaction._assetId, 'hex')) !== 0) {
throw new Error('The Asset ID of the output does not match the transaction');
}
const transferOutput = output.output as TransferOutput;
const outputOwners = transferOutput.outputOwners;
this.transaction._locktime = outputOwners.locktime.value();
this.transaction._threshold = outputOwners.threshold.value();
this.transaction._fromAddresses = outputOwners.addrs.map((addr) => Buffer.from(addr.toBytes()));
this._externalChainId = Buffer.from(importTx.sourceChain.toBytes());
this.transaction._utxos = this.recoverUtxos(importTx.ins, outputOwners.addrs);
const totalInputAmount = importTx.ins.reduce((sum, input) => sum + input.amount(), BigInt(0));
const outputAmount = transferOutput.amount();
const fee = totalInputAmount - outputAmount;
this.transaction._fee.fee = fee.toString();
const credentials = parsedCredentials || [];
const hasCredentials = credentials.length > 0;
if (rawBytes && hasCredentials) {
this.transaction._rawSignedBytes = rawBytes;
}
this.computeAddressesIndexFromParsed();
const txCredentials =
credentials.length > 0
? credentials
: this.transaction._utxos.map((utxo) => {
const utxoThreshold = utxo.threshold || this.transaction._threshold;
return this.createCredentialForUtxo(utxo, utxoThreshold);
});
const addressMaps = this.transaction._utxos.map((utxo) => {
const utxoThreshold = utxo.threshold || this.transaction._threshold;
return this.createAddressMapForUtxo(utxo, utxoThreshold);
});
const unsignedTx = new UnsignedTx(importTx, [], new FlareUtils.AddressMaps(addressMaps), txCredentials);
this.transaction.setTransaction(unsignedTx);
return this;
}
static verifyTxType(txnType: string): boolean {
return txnType === FlareTransactionType.PvmImportTx;
}
verifyTxType(txnType: string): boolean {
return ImportInPTxBuilder.verifyTxType(txnType);
}
/**
* Build the import transaction for P-chain (importing FROM C-chain)
* @protected
*/
protected async buildFlareTransaction(): Promise<void> {
if (this.transaction.hasCredentials) return;
if (!this.transaction._utxos || this.transaction._utxos.length === 0) {
throw new BuildTransactionError('UTXOs are required');
}
if (!this.transaction._feeState) {
throw new BuildTransactionError('Fee state 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._to || this.transaction._to.length === 0) {
throw new BuildTransactionError('toAddresses are required');
}
if (!this.transaction._threshold) {
throw new BuildTransactionError('threshold is required');
}
if (this.transaction._locktime === undefined) {
throw new BuildTransactionError('locktime is required');
}
this.computeAddressesIndex();
this.validateUtxoAddresses();
const assetId = utils.cb58Encode(Buffer.from(this.transaction._assetId, 'hex'));
const nativeUtxos = utils.decodedToUtxos(this.transaction._utxos, assetId);
const totalUtxoAmount = nativeUtxos.reduce((sum, utxo) => {
const output = utxo.output as TransferOutput;
return sum + output.amount();
}, BigInt(0));
if (totalUtxoAmount === BigInt(0)) {
throw new BuildTransactionError('UTXOs have zero total balance');
}
const toAddresses = this.transaction._to.map((addr) => Buffer.from(addr));
const fromAddresses = this.transaction._fromAddresses.map((addr) => Buffer.from(addr));
const invalidToAddress = toAddresses.find((addr) => addr.length !== 20);
if (invalidToAddress) {
throw new BuildTransactionError(`Invalid toAddress length: expected 20 bytes, got ${invalidToAddress.length}`);
}
const invalidFromAddress = fromAddresses.find((addr) => addr.length !== 20);
if (invalidFromAddress) {
throw new BuildTransactionError(
`Invalid fromAddress length: expected 20 bytes, got ${invalidFromAddress.length}`
);
}
const importTx = pvm.e.newImportTx(
{
feeState: this.transaction._feeState,
fromAddressesBytes: fromAddresses,
sourceChainId: this.transaction._network.cChainBlockchainID,
toAddressesBytes: toAddresses,
utxos: nativeUtxos,
threshold: this.transaction._threshold,
locktime: this.transaction._locktime,
},
this.transaction._context
);
const flareUnsignedTx = importTx as UnsignedTx;
const innerTx = flareUnsignedTx.getTx() as pvmSerial.ImportTx;
const utxosWithIndex = innerTx.ins.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 output addresses as proxy for UTXO addresses since they should be the same
* addresses controlling the multisig (just potentially in different on-chain order).
*
* @param importedInputs Array of transferable inputs
* @param outputAddrs Output owner addresses to use as proxy for UTXO addresses
* @returns Array of decoded UTXO objects
*/
private recoverUtxos(
importedInputs: TransferableInput[],
outputAddrs?: { toBytes(): Uint8Array }[]
): DecodedUtxoObj[] {
const proxyAddresses = outputAddrs
? outputAddrs.map((addr) =>
utils.addressToString(
this.transaction._network.hrp,
this.transaction._network.alias,
Buffer.from(addr.toBytes())
)
)
: [];
return importedInputs.map((input) => {
const utxoId = input.utxoID;
const transferInput = input.input as TransferInput;
const sigIndicies = transferInput.sigIndicies();
const utxo: DecodedUtxoObj = {
outputID: SECP256K1_Transfer_Output,
amount: transferInput.amount().toString(),
txid: utils.cb58Encode(Buffer.from(utxoId.txID.toBytes())),
outputidx: utxoId.outputIdx.value().toString(),
threshold: sigIndicies.length || this.transaction._threshold,
addresses: proxyAddresses,
addressesIndex: sigIndicies,
};
return utxo;
});
}
}