Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions modules/sdk-coin-flr/test/unit/flr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -606,9 +606,9 @@ describe('flr', function () {
const hopDestinationAddress =
'P-costwo15msvr27szvhhpmah0c38gcml7vm29xjh7tcek8~P-costwo1cwrdtrgf4xh80ncu7palrjw7gn4mpj0n4dxghh~P-costwo1zt9n96hey4fsvnde35n3k4kt5pu7c784dzewzd';
const hopAddress = '0x28A05933dC76e4e6c25f35D5c9b2A58769700E76';
const importTxFee = 1261000; // Updated to match FlarePTestnet txFee
// Adjusted amount to work backwards from hop amount (50000000): 50000000 - 1261000 = 48739000 nanoFLR
const amount = 48739000000000000;
const importTxFee = 200000; // Match FlarePTestnet txFee from networks.ts
// Adjusted amount to work backwards from hop amount (50000000): 50000000 - 200000 = 49800000 nanoFLR
const amount = 49800000000000000;
const txParams = {
recipients: [{ amount, address: hopDestinationAddress }],
wallet: wallet,
Expand Down Expand Up @@ -826,7 +826,7 @@ describe('flr', function () {
recipients: [
{
address: 'P-costwo1different~P-costwo1address~P-costwo1here',
amount: '48739000000000000',
amount: '49800000000000000', // 50000000 - 200000 (txFee) = 49800000 nanoFLR = 49800000000000000 wei
},
],
};
Expand Down
1 change: 1 addition & 0 deletions modules/sdk-coin-flrp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"@bitgo/sdk-test": "^9.1.20"
},
"dependencies": {
"@bitgo/public-types": "5.61.0",
"@bitgo/sdk-core": "^36.25.0",
"@bitgo/secp256k1": "^1.8.0",
"@bitgo/statics": "^58.19.0",
Expand Down
131 changes: 36 additions & 95 deletions modules/sdk-coin-flrp/src/lib/ExportInCTxBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,47 +5,30 @@ import {
evmSerial,
UnsignedTx,
Credential,
BigIntPr,
Int,
Id,
TransferableOutput,
Address,
TransferOutput,
OutputOwners,
utils as FlareUtils,
evm,
} from '@flarenetwork/flarejs';
import utils from './utils';
import { DecodedUtxoObj, Tx, FlareTransactionType } from './iface';
import { Tx, FlareTransactionType, ExportEVMOptions } from './iface';

export class ExportInCTxBuilder extends AtomicInCTransactionBuilder {
private _amount: bigint;
private _nonce: bigint;

constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
}

/**
* Utxos are not required in Export Tx in C-Chain.
* Override utxos to prevent used by throwing a error.
* UTXOs are not required for Export Tx from C-Chain (uses EVM balance instead).
* Override to prevent usage by throwing an error.
*
* @param {DecodedUtxoObj[]} value ignored
* @param {string[]} _utxoHexStrings - ignored, UTXOs not used for C-chain exports
* @throws {BuildTransactionError} always throws as UTXOs are not applicable
*/
utxos(value: DecodedUtxoObj[]): this {
throw new BuildTransactionError('utxos are not required in Export Tx in C-Chain');
}

/**
* Amount is a bigint that specifies the quantity of the asset that this output owns. Must be positive.
* The transaction output amount add a fixed fee that will be paid upon import.
*
* @param {bigint | string} amount The withdrawal amount
*/
amount(amount: bigint | string): this {
const amountBigInt = typeof amount === 'string' ? BigInt(amount) : amount;
this.validateAmount(amountBigInt);
this._amount = amountBigInt;
return this;
utxos(_utxoHexStrings: string[]): this {
throw new BuildTransactionError('UTXOs are not required for Export Tx from C-Chain');
}

/**
Expand Down Expand Up @@ -81,8 +64,6 @@ export class ExportInCTxBuilder extends AtomicInCTransactionBuilder {
throw new NotSupported('Transaction cannot be parsed or has an unsupported transaction type');
}

// The outputs is a multisign P-Chain address result.
// It's expected to have only one output to the destination P-Chain address.
const outputs = baseTx.exportedOutputs;
if (outputs.length !== 1) {
throw new BuildTransactionError('Transaction can have one output');
Expand All @@ -93,8 +74,6 @@ export class ExportInCTxBuilder extends AtomicInCTransactionBuilder {
throw new BuildTransactionError('AssetID mismatch');
}

// The inputs is not an utxo.
// It's expected to have only one input from C-Chain address.
const inputs = baseTx.ins;
if (inputs.length !== 1) {
throw new BuildTransactionError('Transaction can have one input');
Expand All @@ -107,27 +86,17 @@ export class ExportInCTxBuilder extends AtomicInCTransactionBuilder {
const inputAmount = input.amount.value();
const outputAmount = transferOutput.amount();
const fee = inputAmount - outputAmount;
this._amount = outputAmount;
// Subtract fixedFee from total fee to get the gas-based feeRate
// buildFlareTransaction will add fixedFee back when building the transaction
this.transaction._fee.feeRate = Number(fee) - Number(this.fixedFee);
this.transaction._amount = outputAmount;
this.transaction._fee.fee = fee.toString();
this.transaction._fee.size = 1;
this.transaction._fromAddresses = [Buffer.from(input.address.toBytes())];
this.transaction._locktime = transferOutput.getLocktime();

this._nonce = input.nonce.value();

// 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;
}

// Create proper UnsignedTx wrapper with credentials
const fromAddress = new Address(this.transaction._fromAddresses[0]);
const addressMap = new FlareUtils.AddressMap([
[fromAddress, 0],
Expand Down Expand Up @@ -160,80 +129,52 @@ export class ExportInCTxBuilder extends AtomicInCTransactionBuilder {
*/
protected buildFlareTransaction(): void {
if (this.transaction.hasCredentials) return;
if (this._amount === undefined) {
throw new Error('amount is required');
if (this.transaction._amount === undefined) {
throw new BuildTransactionError('amount is required');
}
if (this.transaction._fromAddresses.length !== 1) {
throw new Error('sender is one and required');
throw new BuildTransactionError('sender is one and required');
}
if (this.transaction._to.length === 0) {
throw new Error('to is required');
throw new BuildTransactionError('to is required');
}
if (!this.transaction._fee.feeRate) {
throw new Error('fee rate is required');
if (!this.transaction._fee.fee) {
throw new BuildTransactionError('fee rate is required');
}
if (this._nonce === undefined) {
throw new Error('nonce is required');
throw new BuildTransactionError('nonce is required');
}
if (!this.transaction._context) {
throw new BuildTransactionError('context is required');
}

// For EVM exports, total fee = feeRate (gas-based fee) + fixedFee (P-chain import fee)
// This matches the AVAX implementation where fixedFee covers the import cost
const txFee = BigInt(this.fixedFee);
const fee = BigInt(this.transaction._fee.feeRate) + txFee;
this.transaction._fee.fee = fee.toString();
this.transaction._fee.size = 1;

const fee = BigInt(this.transaction._fee.fee);
const fromAddressBytes = this.transaction._fromAddresses[0];
const fromAddress = new Address(fromAddressBytes);
const assetId = utils.flareIdString(this.transaction._assetId);
const amount = new BigIntPr(this._amount + fee);
const nonce = new BigIntPr(this._nonce);
const input = new evmSerial.Input(fromAddress, amount, assetId, nonce);
// Map all destination P-chain addresses for multisig support
// Sort addresses alphabetically by hex representation (required by Avalanche/Flare protocol)
const sortedToAddresses = [...this.transaction._to].sort((a, b) => {
const aHex = Buffer.from(a).toString('hex');
const bHex = Buffer.from(b).toString('hex');
return aHex.localeCompare(bHex);
});
const toAddresses = sortedToAddresses.map((addr) => new Address(addr));

const exportTx = new evmSerial.ExportTx(
new Int(this.transaction._networkID),
utils.flareIdString(this.transaction._blockchainID),
new Id(new Uint8Array(this._externalChainId)),
[input],
[
new TransferableOutput(
assetId,
new TransferOutput(
new BigIntPr(this._amount),
new OutputOwners(
new BigIntPr(this.transaction._locktime),
new Int(this.transaction._threshold),
toAddresses
)
)
),
]
);

// Create address maps with proper EVM address format
const addressMap = new FlareUtils.AddressMap([
[fromAddress, 0],
[fromAddress, 1], // Map the same address to both indices since it's used in both places
]);
const addressMaps = new FlareUtils.AddressMaps([addressMap]); // Single map is sufficient

// Create unsigned transaction with proper address mapping
const unsignedTx = new UnsignedTx(
exportTx,
[], // Empty UTXOs array, will be filled during processing
addressMaps,
[new Credential([utils.createNewSig('')])] // Empty credential for signing
const exportEVMOptions: ExportEVMOptions = {
threshold: this.transaction._threshold,
locktime: this.transaction._locktime,
};

const exportTx = evm.newExportTxFromBaseFee(
this.transaction._context,
fee / BigInt(1e9),
this.transaction._amount,
this.transaction._context.pBlockchainID,
fromAddressBytes,
toAddresses.map((addr) => Buffer.from(addr.toBytes())),
BigInt(this._nonce),
utils.flareIdString(this.transaction._assetId).toString(),
exportEVMOptions
);

this.transaction.setTransaction(unsignedTx);
this.transaction.setTransaction(exportTx);
}

/**
Expand Down
Loading