-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathImportInPTxBuilder.ts
More file actions
215 lines (186 loc) · 8.07 KB
/
ImportInPTxBuilder.ts
File metadata and controls
215 lines (186 loc) · 8.07 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
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);
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;
}
const txCredentials =
credentials.length > 0
? credentials
: this.transaction._utxos.map((utxo) => this.createCredentialForUtxo(utxo, this.transaction._threshold));
const addressMaps = this.transaction._utxos.map((utxo) =>
this.createAddressMapForUtxo(utxo, this.transaction._threshold)
);
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');
}
// 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 non-zero (fee will be deducted during import)
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));
// Validate address lengths (P-chain addresses are 20 bytes)
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
);
this.transaction.setTransaction(importTx);
}
/**
* 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 utxoId = input.utxoID;
const transferInput = input.input as TransferInput;
const addressesIndex = 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: addressesIndex.length || this.transaction._threshold,
addresses: [],
addressesIndex,
};
return utxo;
});
}
}