Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement aggregate() method #367

Merged
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
152 changes: 152 additions & 0 deletions src/_tests/unit/qihdwallet-aggregate.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import assert from 'assert';
import { loadTests } from '../utils.js';
import { QiHDWallet } from '../../wallet/qi-hdwallet.js';
import { Mnemonic } from '../../wallet/mnemonic.js';
import { Zone } from '../../constants/zones.js';
import { UTXO } from '../../quais.js';

// Custom error class for controlled exit
class TestCompletionError extends Error {
constructor(public readonly capturedArgs: any[]) {
super('Test completed successfully');
this.name = 'TestCompletionError';
}
}

function sortByDenomination(inputs: UTXO[], order: 'asc' | 'desc' = 'asc') {
return inputs.sort((a, b) =>
order === 'asc' ? (a.denomination || 0) - (b.denomination || 0) : (b.denomination || 0) - (a.denomination || 0),
);
}

interface AggregateTestCase {
mnemonic: string;
zone: Zone;
outpointInfos: Array<{
outpoint: {
txhash: string;
index: number;
denomination: number;
lock?: number;
};
address: string;
zone: Zone;
account: number;
}>;
addressesToAdd: Array<{
account: number;
addressIndex: number;
}>;
fee: number;
expected: {
selection: {
inputs: Array<{
txhash: string;
index: number;
address: string;
denomination: number;
}>;
spendOutputs: Array<{
denomination: number;
}>;
changeOutputs: Array<{
denomination: number;
}>;
};
inputPubKeys: string[];
sendAddresses: string[];
changeAddresses: string[];
};
}

describe('QiHDWallet.aggregate', () => {
const testCases = loadTests<AggregateTestCase>('qi-wallet-aggregate');

testCases.forEach((testCase) => {
it(`should correctly aggregate UTXOs for wallet with mnemonic`, async () => {
// Create wallet from mnemonic
const mnemonic = Mnemonic.fromPhrase(testCase.mnemonic);
const wallet = QiHDWallet.fromMnemonic(mnemonic);

// Mock provider with minimal implementation
wallet.connect({
getNetwork: async () => ({ chainId: BigInt(1) }),
} as any);

// Add addresses to wallet before importing outpoints
for (const addressToAdd of testCase.addressesToAdd) {
wallet.addAddress(addressToAdd.account, addressToAdd.addressIndex);
}

// Import test outpoints
wallet.importOutpoints(testCase.outpointInfos);

// Spy on prepareTransaction and throw custom error to exit early
wallet['prepareTransaction'] = async (...args) => {
throw new TestCompletionError(args);
};

try {
await wallet.aggregate(testCase.zone as any);
assert.fail('Expected TestCompletionError to be thrown');
} catch (error) {
if (error instanceof TestCompletionError) {
const [selection, inputPubKeys, sendAddresses, changeAddresses] = error.capturedArgs;

const sortedInputs = sortByDenomination(selection.inputs, 'desc');
const sortedExpectedInputs = sortByDenomination(
testCase.expected.selection.inputs as UTXO[],
'desc',
);

// Verify selection with complete input properties
assert.deepStrictEqual(
sortedInputs.map((input: UTXO) => ({
txhash: input.txhash,
index: input.index,
address: input.address,
denomination: input.denomination,
})),
sortedExpectedInputs,
`inputs: expected: ${JSON.stringify(sortedExpectedInputs, null, 2)}, \nactual: ${JSON.stringify(sortedInputs, null, 2)}`,
);

// Verify spendOutputs
assert.deepStrictEqual(
selection.spendOutputs.map((output: UTXO) => ({ denomination: output.denomination })),
testCase.expected.selection.spendOutputs,
`spendOutputs: expected: ${JSON.stringify(testCase.expected.selection.spendOutputs, null, 2)}, \nactual: ${JSON.stringify(selection.spendOutputs, null, 2)}`,
);

// Verify changeOutputs
assert.deepStrictEqual(
selection.changeOutputs.map((output: UTXO) => ({ denomination: output.denomination })),
testCase.expected.selection.changeOutputs,
`changeOutputs: expected: ${JSON.stringify(testCase.expected.selection.changeOutputs, null, 2)}, \nactual: ${JSON.stringify(selection.changeOutputs, null, 2)}`,
);

// Verify input public keys
assert.deepStrictEqual(
inputPubKeys,
testCase.expected.inputPubKeys,
`inputPubKeys: expected: ${JSON.stringify(testCase.expected.inputPubKeys, null, 2)}, \nactual: ${JSON.stringify(inputPubKeys, null, 2)}`,
);

// Verify addresses
assert.deepStrictEqual(
sendAddresses,
testCase.expected.sendAddresses,
`sendAddresses: expected: ${JSON.stringify(testCase.expected.sendAddresses, null, 2)}, \nactual: ${JSON.stringify(sendAddresses, null, 2)}`,
);
assert.deepStrictEqual(
changeAddresses,
testCase.expected.changeAddresses,
`changeAddresses: expected: ${JSON.stringify(testCase.expected.changeAddresses, null, 2)}, \nactual: ${JSON.stringify(changeAddresses, null, 2)}`,
);
} else {
throw error;
}
}
});
});
});
17 changes: 0 additions & 17 deletions src/transaction/abstract-coinselector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ export interface CoinSelectionConfig {
target?: bigint;
fee?: bigint;
includeLocked?: boolean;
maxDenomination?: number;
// Any future parameters can be added here
}

Expand Down Expand Up @@ -114,20 +113,4 @@ export abstract class AbstractCoinSelector {
throw new Error('No UTXOs available');
}
}

/**
* Sorts UTXOs by their denomination.
*
* @param {UTXO[]} utxos - The UTXOs to sort.
* @param {'asc' | 'desc'} order - The direction to sort ('asc' for ascending, 'desc' for descending).
* @returns {UTXO[]} The sorted UTXOs.
*/
protected sortUTXOsByDenomination(utxos: UTXO[], order: 'asc' | 'desc' = 'asc'): UTXO[] {
return [...utxos].sort((a, b) => {
const aValue = BigInt(a.denomination !== null ? denominations[a.denomination] : 0);
const bValue = BigInt(b.denomination !== null ? denominations[b.denomination] : 0);
const diff = order === 'asc' ? aValue - bValue : bValue - aValue;
return diff > BigInt(0) ? 1 : diff < BigInt(0) ? -1 : 0;
});
}
}
24 changes: 24 additions & 0 deletions src/transaction/coinselector-fewest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,4 +331,28 @@ export class FewestCoinSelector extends AbstractCoinSelector {

this.changeOutputs = this.createChangeOutputs(changeAmount);
}

/**
* Sorts UTXOs by their denomination.
*
* @param {UTXO[]} utxos - The UTXOs to sort.
* @param {'asc' | 'desc'} direction - The direction to sort ('asc' for ascending, 'desc' for descending).
* @returns {UTXO[]} The sorted UTXOs.
*/
private sortUTXOsByDenomination(utxos: UTXO[], direction: 'asc' | 'desc'): UTXO[] {
if (direction === 'asc') {
return [...utxos].sort((a, b) => {
const diff =
BigInt(a.denomination !== null ? denominations[a.denomination] : 0) -
BigInt(b.denomination !== null ? denominations[b.denomination] : 0);
return diff > BigInt(0) ? 1 : diff < BigInt(0) ? -1 : 0;
});
}
return [...utxos].sort((a, b) => {
const diff =
BigInt(b.denomination !== null ? denominations[b.denomination] : 0) -
BigInt(a.denomination !== null ? denominations[a.denomination] : 0);
return diff > BigInt(0) ? 1 : diff < BigInt(0) ? -1 : 0;
});
}
}
Loading
Loading