From 93eb8e08cd24f9faa9d2dddb39f90ad9179aa954 Mon Sep 17 00:00:00 2001 From: Ulisses Ferreira Date: Tue, 17 Nov 2026 15:59:12 +0000 Subject: [PATCH] fix(bitcoin): align `onAmountInput` with `getMaxSendableAmount` --- packages/bitcoin-wallet-snap/CHANGELOG.md | 1 + .../bitcoin-wallet-snap/snap.manifest.json | 2 +- .../src/handlers/RpcHandler.test.ts | 36 +++++++- .../src/handlers/RpcHandler.ts | 85 +++++++++++-------- .../src/use-cases/SendFlowUseCases.test.ts | 21 +++-- .../src/use-cases/SendFlowUseCases.ts | 7 +- 6 files changed, 105 insertions(+), 47 deletions(-) diff --git a/packages/bitcoin-wallet-snap/CHANGELOG.md b/packages/bitcoin-wallet-snap/CHANGELOG.md index 660e91baa..d7dcb7943 100644 --- a/packages/bitcoin-wallet-snap/CHANGELOG.md +++ b/packages/bitcoin-wallet-snap/CHANGELOG.md @@ -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 diff --git a/packages/bitcoin-wallet-snap/snap.manifest.json b/packages/bitcoin-wallet-snap/snap.manifest.json index 7b4abeba2..862d9e27e 100644 --- a/packages/bitcoin-wallet-snap/snap.manifest.json +++ b/packages/bitcoin-wallet-snap/snap.manifest.json @@ -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", diff --git a/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.test.ts b/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.test.ts index 3c25ba7e7..7e42dbf2b 100644 --- a/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.test.ts +++ b/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.test.ts @@ -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', @@ -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 () => { @@ -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); diff --git a/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.ts b/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.ts index 8e25501ab..e3e7ab36c 100644 --- a/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.ts +++ b/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.ts @@ -28,7 +28,7 @@ import { InexistentMethodError, ValidationError, } from '../entities'; -import type { CodifiedError, Logger } from '../entities'; +import type { BitcoinAccount, CodifiedError, Logger } from '../entities'; import type { AccountUseCases, SendFlowUseCases, @@ -369,24 +369,17 @@ export class RpcHandler { 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. @@ -398,6 +391,35 @@ export class RpcHandler { } } + /** + * 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`. * @@ -430,32 +452,25 @@ export class RpcHandler { 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, + ); - 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; } } diff --git a/packages/bitcoin-wallet-snap/src/use-cases/SendFlowUseCases.test.ts b/packages/bitcoin-wallet-snap/src/use-cases/SendFlowUseCases.test.ts index d3c15c561..e62dd5fd0 100644 --- a/packages/bitcoin-wallet-snap/src/use-cases/SendFlowUseCases.test.ts +++ b/packages/bitcoin-wallet-snap/src/use-cases/SendFlowUseCases.test.ts @@ -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 () => { diff --git a/packages/bitcoin-wallet-snap/src/use-cases/SendFlowUseCases.ts b/packages/bitcoin-wallet-snap/src/use-cases/SendFlowUseCases.ts index cdb5c909c..f056636d1 100644 --- a/packages/bitcoin-wallet-snap/src/use-cases/SendFlowUseCases.ts +++ b/packages/bitcoin-wallet-snap/src/use-cases/SendFlowUseCases.ts @@ -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. @@ -208,6 +211,7 @@ export class SendFlowUseCases { account, amountInSats, recipient, + { drain: false }, ); return psbt; } @@ -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( @@ -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);