Skip to content
Open
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
1 change: 1 addition & 0 deletions packages/bitcoin-wallet-snap/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- `onAmountInput` now rejects the full spendable balance unless the amount covers the fee, matching `getMaxSendableAmount`; amount probes no longer drain the wallet ([#645](https://github.com/MetaMask/internal-snaps/pull/645))
- `onAmountInput` now estimates the send fee and rejects amounts that cannot cover it, including when `toAddress` is omitted ([#586](https://github.com/MetaMask/internal-snaps/pull/586))

### Removed
Expand Down
2 changes: 1 addition & 1 deletion packages/bitcoin-wallet-snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/MetaMask/internal-snaps.git"
},
"source": {
"shasum": "fm73uO5u8Y4zhm5IYxVPrgkZfo6Uu2p98/hA1A+u/+s=",
"shasum": "uJAvBUE9Ytm2xq0M4P5GZWspFQT1LvNgXuzcjTJaqQk=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
36 changes: 34 additions & 2 deletions packages/bitcoin-wallet-snap/src/handlers/RpcHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,11 @@ describe('RpcHandler', () => {
});
});

it('accepts the full balance as a drain amount', async () => {
it('rejects the full balance because the fee cannot be covered', async () => {
mockSendFlowUseCases.buildProbePsbt.mockRejectedValue(
new Error('Insufficient funds: 150000000 sat available'),
);

const drainRequest: JsonRpcRequest = {
id: 1,
jsonrpc: '2.0',
Expand All @@ -704,7 +708,10 @@ describe('RpcHandler', () => {
'1.5',
undefined,
);
expect(result).toStrictEqual({ valid: true, errors: [] });
expect(result).toStrictEqual({
valid: false,
errors: [{ code: SendErrorCodes.InsufficientBalanceToCoverFee }],
});
});

it('passes a provided toAddress to the fee check', async () => {
Expand Down Expand Up @@ -907,6 +914,31 @@ describe('RpcHandler', () => {
expect(result).toStrictEqual({ amount: '1.4999' });
});

it('returns an amount that onAmountInput accepts', async () => {
mockFundableUpTo(spendableSats - feeSats);
const createAmountRequest = (value: string): JsonRpcRequest => ({
id: 2,
jsonrpc: '2.0',
method: RpcMethod.OnAmountInput,
params: { value, accountId: validAccountId, assetId },
});

const { amount } = (await handler.route(origin, createRequest())) as {
amount: string;
};
const accepted = await handler.route(origin, createAmountRequest(amount));
const rejected = await handler.route(
origin,
createAmountRequest('1.49990001'),
);

expect(accepted).toStrictEqual({ valid: true, errors: [] });
expect(rejected).toStrictEqual({
valid: false,
errors: [{ code: SendErrorCodes.InsufficientBalanceToCoverFee }],
});
});

it('returns 0 when no amount covers the fee', async () => {
mockFundableUpTo(-1n);

Expand Down
85 changes: 50 additions & 35 deletions packages/bitcoin-wallet-snap/src/handlers/RpcHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
InexistentMethodError,
ValidationError,
} from '../entities';
import type { CodifiedError, Logger } from '../entities';
import type { BitcoinAccount, CodifiedError, Logger } from '../entities';
import type {
AccountUseCases,
SendFlowUseCases,
Expand Down Expand Up @@ -369,24 +369,17 @@
return INVALID_RESPONSE;
}

try {
await this.#sendFlowUseCases.buildProbePsbt(
bitcoinAccount,
value,
toAddress,
);
} catch (error) {
// The balance alone is sufficient, so a funding failure is a fee shortfall.
if ((error as CodifiedError).message.includes('Insufficient funds')) {
return {
valid: false,
errors: [{ code: SendErrorCodes.InsufficientBalanceToCoverFee }],
};
}
throw error;
const probe = await this.#probeAmount(bitcoinAccount, value, toAddress);

// The balance alone is sufficient, so a funding failure is a fee shortfall.
if (probe === 'insufficient') {
return {
valid: false,
errors: [{ code: SendErrorCodes.InsufficientBalanceToCoverFee }],
};
}

return NO_ERRORS_RESPONSE;
return probe === 'dust' ? INVALID_RESPONSE : NO_ERRORS_RESPONSE;
} catch (error) {
// We do not track this error as it is a user input.

Expand All @@ -398,6 +391,35 @@
}
}

/**
* Probes whether an exact amount can be funded and classifies the failure.
*
* @param account - The account sending the funds.
* @param amount - The amount to send, in BTC units.
* @param toAddress - The destination, when it is already known.
* @returns `fundable`, `insufficient` when the amount and fee exceed the
* balance, or `dust` when the amount is below the dust limit.
*/
async #probeAmount(
account: BitcoinAccount,
amount: string,
toAddress?: string,
): Promise<'fundable' | 'insufficient' | 'dust'> {
try {
await this.#sendFlowUseCases.buildProbePsbt(account, amount, toAddress);
return 'fundable';
} catch (error) {
const { message } = error as CodifiedError;
if (message.includes('Insufficient funds')) {
return 'insufficient';
}
if (/dust/iu.test(message)) {
return 'dust';
}
throw error;
}
}

/**
* Returns the maximum amount that would pass `onAmountInput`.
*
Expand Down Expand Up @@ -430,32 +452,25 @@
return { amount: '0' };
}

// Exclude the full balance so the probe adds a recipient instead of
// draining the wallet, which would fold the fee into the output.
let low = 0n;
let high = spendableSats - 1n;
let high = spendableSats;
let maxSats = 0n;

while (low <= high) {
const mid = (low + high) / 2n;
const probe = await this.#probeAmount(
account,
formatBtcAmount(mid),
toAddress,
);

Check warning on line 465 in packages/bitcoin-wallet-snap/src/handlers/RpcHandler.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unexpected `await` inside a loop.

See more on https://sonarcloud.io/project/issues?id=MetaMask_internal-snaps&issues=AaHqRPjJ1dtB1APrwYBl&open=AaHqRPjJ1dtB1APrwYBl&pullRequest=645

try {
await this.#sendFlowUseCases.buildProbePsbt(
account,
formatBtcAmount(mid),
toAddress,
);
if (probe === 'fundable') {
maxSats = mid;
low = mid + 1n;
} catch (error) {
const { message } = error as CodifiedError;
if (message.includes('Insufficient funds')) {
high = mid - 1n;
} else if (/dust/iu.test(message)) {
low = mid + 1n;
} else {
throw error;
}
} else if (probe === 'insufficient') {
high = mid - 1n;
} else {
low = mid + 1n;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,24 +191,29 @@ describe('SendFlowUseCases', () => {
expect(probeTxBuilder.finish).toHaveBeenCalled();
});

it('drains to the recipient when the amount equals the balance', async () => {
it('adds the full balance as a recipient instead of draining', async () => {
(mockFeeEstimates.get as Mock).mockReturnValue(7);

await useCases.buildProbePsbt(probeAccount, '0.0002', 'recipientAddress');

expect(probeTxBuilder.drainWallet).toHaveBeenCalled();
expect(probeTxBuilder.drainTo).toHaveBeenCalledWith('recipientAddress');
expect(probeTxBuilder.addRecipient).not.toHaveBeenCalled();
expect(probeTxBuilder.addRecipient).toHaveBeenCalledWith(
'20000',
'recipientAddress',
);
expect(probeTxBuilder.drainWallet).not.toHaveBeenCalled();
expect(probeTxBuilder.drainTo).not.toHaveBeenCalled();
});

it('drains to the account address when no recipient is known', async () => {
it('adds the full balance to the account address when no recipient is known', async () => {
(mockFeeEstimates.get as Mock).mockReturnValue(7);

await useCases.buildProbePsbt(probeAccount, '0.0002');

expect(probeTxBuilder.drainWallet).toHaveBeenCalled();
expect(probeTxBuilder.drainTo).toHaveBeenCalledWith('myAddress');
expect(probeTxBuilder.addRecipient).not.toHaveBeenCalled();
expect(probeTxBuilder.addRecipient).toHaveBeenCalledWith(
'20000',
'myAddress',
);
expect(probeTxBuilder.drainWallet).not.toHaveBeenCalled();
});

it('uses the account address when no recipient is known', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,9 @@ export class SendFlowUseCases {
/**
* Builds a PSBT to probe whether the amount plus fee can be funded.
*
* Always adds the amount as a recipient, even when it equals the balance, so
* the probe prices the same transaction that validation accepts.
*
* @param account - The account sending the funds.
* @param amount - The amount to send, in BTC units.
* @param toAddress - The destination, when it is already known.
Expand All @@ -208,6 +211,7 @@ export class SendFlowUseCases {
account,
amountInSats,
recipient,
{ drain: false },
);
return psbt;
}
Expand All @@ -216,6 +220,7 @@ export class SendFlowUseCases {
account: BitcoinAccount,
amountInSats: bigint,
recipient: string,
{ drain = true }: { drain?: boolean } = {},
): Promise<{ psbt: Psbt; feeRate: number }> {
const feeRate = await this.#getFeeRate(account.network);
const frozenUTXOs = await this.#accountRepository.getFrozenUTXOs(
Expand All @@ -224,7 +229,7 @@ export class SendFlowUseCases {

const builder = account.buildTx().feeRate(feeRate).unspendable(frozenUTXOs);

if (amountInSats === account.balance.trusted_spendable.to_sat()) {
if (drain && amountInSats === account.balance.trusted_spendable.to_sat()) {
builder.drainWallet().drainTo(recipient);
} else {
builder.addRecipient(amountInSats.toString(), recipient);
Expand Down
Loading