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

Minor improvements #369

Merged
merged 5 commits into from
Nov 27, 2024
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
36 changes: 24 additions & 12 deletions src/signers/abstract-signer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,17 +114,6 @@ export abstract class AbstractSigner<P extends null | Provider = null | Provider
pop.nonce = await this.getNonce('pending');
}

if (pop.gasLimit == null || pop.gasLimit === 0n) {
if (pop.type == 0) pop.gasLimit = await this.estimateGas(pop);
else {
//Special cases for type 2 tx to bypass address out of scope in the node
const temp = pop.to;
pop.to = '0x0000000000000000000000000000000000000000';
pop.gasLimit = getBigInt(2 * Number(await this.estimateGas(pop)));
pop.to = temp;
}
}

// Populate the chain ID
const network = await (<Provider>this.provider).getNetwork();

Expand All @@ -134,6 +123,29 @@ export abstract class AbstractSigner<P extends null | Provider = null | Provider
} else {
pop.chainId = network.chainId;
}

// Create a base transaction object to be used for gas estimation and access list creation
const baseTx: QuaiTransactionLike = {
chainId: pop.chainId,
type: pop.type,
from: pop.from,
nonce: pop.nonce,
};
if (pop.to) baseTx.to = pop.to;
if (pop.data) baseTx.data = pop.data;
if (pop.value) baseTx.value = pop.value;

if (pop.gasLimit == null || pop.gasLimit === 0n) {
if (pop.type == 0) {
pop.gasLimit = await this.estimateGas(baseTx);
} else {
//Special cases for type 2 tx to bypass address out of scope in the node
baseTx.to = '0x0000000000000000000000000000000000000000';
pop.gasLimit = getBigInt(2 * Number(await this.estimateGas(baseTx)));
baseTx.to = pop.to;
}
}

if (pop.gasPrice == null || pop.minerTip == null) {
const feeData = await provider.getFeeData(zone, true);

Expand All @@ -148,7 +160,7 @@ export abstract class AbstractSigner<P extends null | Provider = null | Provider
if (tx.accessList) {
pop.accessList = tx.accessList;
} else {
pop.accessList = await this.createAccessList(pop as QuaiTransactionRequest);
pop.accessList = await this.createAccessList(baseTx as QuaiTransactionRequest);
}
}
//@TOOD: Don't await all over the place; save them up for
Expand Down
25 changes: 25 additions & 0 deletions src/transaction/abstract-coinselector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export interface CoinSelectionConfig {
target?: bigint;
fee?: bigint;
includeLocked?: boolean;
maxDenomination?: number;
// Any future parameters can be added here
}

Expand Down Expand Up @@ -113,4 +114,28 @@ 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'} direction - The direction to sort ('asc' for ascending, 'desc' for descending).
* @returns {UTXO[]} The sorted UTXOs.
*/
protected 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;
});
}
}
24 changes: 0 additions & 24 deletions src/transaction/coinselector-fewest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,28 +331,4 @@ 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;
});
}
}
64 changes: 32 additions & 32 deletions src/wallet/qi-hdwallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ export class QiHDWallet extends AbstractHDWallet<QiAddressInfo> {
* @ignore
* @type {number}
*/
protected static _GAP_LIMIT: number = 2;
protected static _GAP_LIMIT: number = 5;

/**
* @ignore
Expand Down Expand Up @@ -218,7 +218,9 @@ export class QiHDWallet extends AbstractHDWallet<QiAddressInfo> {
* @returns {string[]} The payment codes for all open channels.
*/
get openChannels(): string[] {
return Array.from(this._addressesMap.keys()).filter((key) => !key.startsWith('BIP44:'));
return Array.from(this._addressesMap.keys()).filter(
(key) => !key.startsWith('BIP44:') && key !== QiHDWallet.PRIVATE_KEYS_PATH,
);
}

/**
Expand Down Expand Up @@ -286,23 +288,20 @@ export class QiHDWallet extends AbstractHDWallet<QiAddressInfo> {
zone: Zone,
isChange: boolean,
): QiAddressInfo {
// scan the wallet outpoints for the new address. If the address is found, set the status to USED
const outpointInfo = this._availableOutpoints.find((outpoint) => outpoint.address === addressNode.address);
const status = outpointInfo ? AddressStatus.USED : AddressStatus.UNUSED;

const derivationPath = isChange ? 'BIP44:change' : 'BIP44:external';
const qiAddressInfo: QiAddressInfo = {
zone,
account,
derivationPath,
address: addressNode.address,
pubKey: addressNode.publicKey,
account,
index: addressNode.index,
change: isChange,
zone,
status,
derivationPath: isChange ? 'BIP44:change' : 'BIP44:external',
status: AddressStatus.UNKNOWN,
lastSyncedBlock: null,
};

this._addressesMap.get(isChange ? 'BIP44:change' : 'BIP44:external')!.push(qiAddressInfo); // _addressesMap is initialized within the constructor
this._addressesMap.get(derivationPath)!.push(qiAddressInfo); // _addressesMap is initialized within the constructor
return qiAddressInfo;
}

Expand Down Expand Up @@ -550,7 +549,6 @@ export class QiHDWallet extends AbstractHDWallet<QiAddressInfo> {
blockNumber?: number,
): Promise<bigint> {
return this.getOutpoints(zone)
.filter((utxo) => utxo.zone === zone)
.filter((utxo) => utxo.outpoint.lock === 0 || utxo.outpoint.lock! < blockNumber!)
.reduce((total, utxo) => {
const denominationValue = denominations[utxo.outpoint.denomination];
Expand Down Expand Up @@ -833,8 +831,6 @@ export class QiHDWallet extends AbstractHDWallet<QiAddressInfo> {
}

let attempts = 0;
let finalFee = 0n;
let satisfiedFeeEstimation = false;
const MAX_FEE_ESTIMATION_ATTEMPTS = 5;

while (attempts < MAX_FEE_ESTIMATION_ATTEMPTS) {
Expand All @@ -845,10 +841,10 @@ export class QiHDWallet extends AbstractHDWallet<QiAddressInfo> {
changeAddresses,
);

finalFee = await this.provider.estimateFeeForQi(feeEstimationTx);
const estimatedFee = await this.provider.estimateFeeForQi(feeEstimationTx);

// Get new selection with updated fee 2x
selection = fewestCoinSelector.performSelection({ target: spendTarget, fee: finalFee * 3n });
selection = fewestCoinSelector.performSelection({ target: spendTarget, fee: estimatedFee * 3n });

// Determine if new addresses are needed for the change outputs
const changeAddressesNeeded = selection.changeOutputs.length - changeAddresses.length;
Expand Down Expand Up @@ -890,19 +886,12 @@ export class QiHDWallet extends AbstractHDWallet<QiAddressInfo> {

// If we need 5 or fewer new outputs, we can break the loop
if ((changeAddressesNeeded <= 0 && spendAddressesNeeded <= 0) || totalNewOutputsNeeded <= 5) {
finalFee *= 3n; // Increase the fee 3x to ensure it's accepted
satisfiedFeeEstimation = true;
break;
}

attempts++;
}

// If we didn't satisfy the fee estimation, increase the fee 10x to ensure it's accepted
if (!satisfiedFeeEstimation) {
finalFee *= 10n;
}

// Proceed with creating and signing the transaction
const chainId = (await this.provider.getNetwork()).chainId;
const tx = await this.prepareTransaction(
Expand Down Expand Up @@ -1614,9 +1603,11 @@ export class QiHDWallet extends AbstractHDWallet<QiAddressInfo> {
* @param {string} paymentCode - The payment code.
* @returns {QiAddressInfo[]} The gap payment channel addresses for the payment code.
*/
public getGapPaymentChannelAddresses(paymentCode: string): QiAddressInfo[] {
public getGapPaymentChannelAddressesForZone(paymentCode: string, zone: Zone): QiAddressInfo[] {
return (
this._addressesMap.get(paymentCode)?.filter((addressInfo) => addressInfo.status === AddressStatus.UNUSED) ||
this._addressesMap
.get(paymentCode)
?.filter((addressInfo) => addressInfo.status === AddressStatus.UNUSED && addressInfo.zone === zone) ||
[]
);
}
Expand Down Expand Up @@ -1664,6 +1655,7 @@ export class QiHDWallet extends AbstractHDWallet<QiAddressInfo> {
*/
public static async deserialize(serialized: SerializedQiHDWallet): Promise<QiHDWallet> {
super.validateSerializedWallet(serialized);

// create the wallet instance
const mnemonic = Mnemonic.fromPhrase(serialized.phrase);
const path = (this as any).parentPath(serialized.coinType);
Expand All @@ -1672,18 +1664,23 @@ export class QiHDWallet extends AbstractHDWallet<QiAddressInfo> {

// validate and import all the wallet addresses
for (const addressInfo of serialized.addresses) {
wallet.validateAddressInfo(addressInfo);
let key = addressInfo.derivationPath;
if (isHexString(key, 32)) {
key = QiHDWallet.PRIVATE_KEYS_PATH;
} else if (!key.startsWith('BIP44:')) {
wallet._addressesMap.set(key, []);
} else if (key.includes('BIP44')) {
// only validate if it's not a private key or a BIP44 path
wallet.validateAddressInfo(addressInfo);
} else {
// payment code addresses require different derivation validation
wallet.validateBaseAddressInfo(addressInfo);
wallet.validateExtendedProperties(addressInfo);
}
const existingAddresses = wallet._addressesMap.get(key);
if (existingAddresses && existingAddresses.some((addr) => addr.address === addressInfo.address)) {
throw new Error(`Address ${addressInfo.address} already exists in the wallet`);
if (!existingAddresses) {
wallet._addressesMap.set(key, [addressInfo]);
} else if (!existingAddresses.some((addr) => addr.address === addressInfo.address)) {
existingAddresses!.push(addressInfo);
}
wallet._addressesMap.get(key)!.push(addressInfo);
}

// validate and import the counter party payment code info
Expand All @@ -1692,10 +1689,13 @@ export class QiHDWallet extends AbstractHDWallet<QiAddressInfo> {
throw new Error(`Invalid payment code: ${paymentCode}`);
}
for (const pcInfo of paymentCodeInfoArray) {
wallet.validateAddressInfo(pcInfo);
// Basic property validation
wallet.validateBaseAddressInfo(pcInfo);
wallet.validateExtendedProperties(pcInfo);
}
wallet._paymentCodeSendAddressMap.set(paymentCode, paymentCodeInfoArray);
}

return wallet;
}

Expand Down
Loading