From 48b7cd67b8cb1103d0c252bf1ff0a5f600c634e0 Mon Sep 17 00:00:00 2001 From: Ulisses Ferreira Date: Wed, 11 Nov 2026 10:18:53 +0000 Subject: [PATCH] feat(bitcoin): add `getMaxSendableAmount` client request method --- packages/bitcoin-wallet-snap/CHANGELOG.md | 4 + .../bitcoin-wallet-snap/snap.manifest.json | 2 +- .../src/handlers/RpcHandler.test.ts | 129 ++++++++++++++++++ .../src/handlers/RpcHandler.ts | 77 +++++++++++ .../bitcoin-wallet-snap/src/handlers/types.ts | 8 ++ .../src/handlers/validation.ts | 11 ++ 6 files changed, 230 insertions(+), 1 deletion(-) diff --git a/packages/bitcoin-wallet-snap/CHANGELOG.md b/packages/bitcoin-wallet-snap/CHANGELOG.md index 8633a1a03..660e91baa 100644 --- a/packages/bitcoin-wallet-snap/CHANGELOG.md +++ b/packages/bitcoin-wallet-snap/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Add the `getMaxSendableAmount` client request method, returning the maximum amount that can be sent for BTC: the spendable balance minus the network fee, or `0` when no amount can pass ([#587](https://github.com/MetaMask/internal-snaps/pull/587)) + ### Changed - `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)) diff --git a/packages/bitcoin-wallet-snap/snap.manifest.json b/packages/bitcoin-wallet-snap/snap.manifest.json index c382b4110..7b4abeba2 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": "ExOBCFPw5U1WWEjAfEj+GZ/+ZrBemTKNT4uIjAs0etM=", + "shasum": "fm73uO5u8Y4zhm5IYxVPrgkZfo6Uu2p98/hA1A+u/+s=", "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 11d721217..3c25ba7e7 100644 --- a/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.test.ts +++ b/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.test.ts @@ -7,6 +7,7 @@ import type { Mock } from 'vitest'; import { mock } from 'vitest-mock-extended'; import type { Logger, BitcoinAccount } from '../entities'; +import { ValidationError } from '../entities'; import type { AccountUseCases, SendFlowUseCases } from '../use-cases'; import { Caip19Asset } from './caip'; import * as Mappings from './mappings'; @@ -827,6 +828,134 @@ describe('RpcHandler', () => { }); }); + describe('getMaxSendableAmount', () => { + const spendableSats = 150_000_000n; + const feeSats = 10_000n; + const assetId = 'bip122:000000000019d6689c085ae165831e93/slip44:0'; + + const createRequest = (toAddress?: string): JsonRpcRequest => ({ + id: 1, + jsonrpc: '2.0', + method: RpcMethod.GetMaxSendableAmount, + params: { + accountId: validAccountId, + assetId, + ...(toAddress === undefined ? {} : { toAddress }), + }, + }); + + const parseSats = (amount: string): bigint => { + const [whole = '0', fraction = ''] = amount.split('.'); + return BigInt(whole) * 100_000_000n + BigInt(fraction.padEnd(8, '0')); + }; + + const mockFundableUpTo = (maxFundableSats: bigint): void => { + mockSendFlowUseCases.buildProbePsbt.mockImplementation( + async (_account, amount) => { + if (parseSats(amount) <= maxFundableSats) { + return mockPsbt; + } + throw new Error('Insufficient funds: 149990000 sat available'); + }, + ); + }; + + beforeEach(() => { + const trustedSpendable = mock(); + trustedSpendable.to_sat.mockReturnValue(spendableSats); + + mockAccountsUseCases.get.mockResolvedValue({ + network: 'bitcoin', + addressType: 'p2wpkh', + balance: { trusted_spendable: trustedSpendable }, + } as unknown as BitcoinAccount); + + (Amount.from_btc as Mock).mockImplementation( + (btc): { to_sat: () => bigint } => ({ + to_sat: (): bigint => BigInt(Math.round(btc * 100_000_000)), + }), + ); + }); + + it('binary searches the max amount fundable with the fee for a known toAddress', async () => { + mockFundableUpTo(spendableSats - feeSats); + const toAddress = 'bc1qux9xtsj6mr4un7yg9kgd7tv8kndvlhv2gv5yc8'; + + const result = await handler.route(origin, createRequest(toAddress)); + + expect(mockSendFlowUseCases.buildProbePsbt).toHaveBeenCalledWith( + expect.objectContaining({ network: 'bitcoin' }), + expect.any(String), + toAddress, + ); + expect( + mockSendFlowUseCases.buildProbePsbt.mock.calls.length, + ).toBeGreaterThan(1); + expect(result).toStrictEqual({ amount: '1.4999' }); + }); + + it('binary searches the max amount fundable with the fee when toAddress is omitted', async () => { + mockFundableUpTo(spendableSats - feeSats); + + const result = await handler.route(origin, createRequest()); + + expect(mockSendFlowUseCases.buildProbePsbt).toHaveBeenCalledWith( + expect.objectContaining({ network: 'bitcoin' }), + expect.any(String), + undefined, + ); + expect(result).toStrictEqual({ amount: '1.4999' }); + }); + + it('returns 0 when no amount covers the fee', async () => { + mockFundableUpTo(-1n); + + const result = await handler.route(origin, createRequest()); + + expect(result).toStrictEqual({ amount: '0' }); + }); + + it('returns 0 when the fundable amount is below the dust limit', async () => { + mockFundableUpTo(100n); + + const result = await handler.route(origin, createRequest()); + + expect(result).toStrictEqual({ amount: '0' }); + }); + + it('returns 0 without probing when the spendable balance is zero', async () => { + const trustedSpendable = mock(); + trustedSpendable.to_sat.mockReturnValue(0n); + mockAccountsUseCases.get.mockResolvedValue({ + network: 'bitcoin', + addressType: 'p2wpkh', + balance: { trusted_spendable: trustedSpendable }, + } as unknown as BitcoinAccount); + + const result = await handler.route(origin, createRequest()); + + expect(mockSendFlowUseCases.buildProbePsbt).not.toHaveBeenCalled(); + expect(result).toStrictEqual({ amount: '0' }); + }); + + it('returns 0 when every probe reports a dust limit error', async () => { + mockSendFlowUseCases.buildProbePsbt.mockRejectedValue( + new Error('Output below the dust limit'), + ); + + const result = await handler.route(origin, createRequest()); + + expect(result).toStrictEqual({ amount: '0' }); + }); + + it('rejects an invalid toAddress', async () => { + await expect( + handler.route(origin, createRequest('invalid-address')), + ).rejects.toThrow(ValidationError); + expect(mockSendFlowUseCases.buildProbePsbt).not.toHaveBeenCalled(); + }); + }); + describe('verifyMessage', () => { const request: JsonRpcRequest = { id: 1, diff --git a/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.ts b/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.ts index dbeacf00c..8e25501ab 100644 --- a/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.ts +++ b/packages/bitcoin-wallet-snap/src/handlers/RpcHandler.ts @@ -35,12 +35,15 @@ import type { SignProofOfOwnershipMessageBatchRequest, SignProofOfOwnershipMessageBatchResult, } from '../use-cases'; +import { formatBtcAmount } from '../utils/format-btc'; import { scopeToNetwork } from './caip'; import type { TransactionFee } from './mappings'; import { mapPsbtToTransaction, mapToTransactionFees } from './mappings'; import { parsePsbt } from './parsers'; import type { ConfirmSendRequest, + GetMaxSendableAmountRequest, + GetMaxSendableAmountResponse, OnAddressInputRequest, OnAmountInputRequest, } from './types'; @@ -49,6 +52,7 @@ import { NO_ERRORS_RESPONSE, INVALID_RESPONSE, ConfirmSendRequestStruct, + GetMaxSendableAmountRequestStruct, OnAddressInputRequestStruct, OnAmountInputRequestStruct, RpcMethod, @@ -192,6 +196,10 @@ export class RpcHandler { assert(params, OnAmountInputRequestStruct); return this.#onAmountInput(params); } + case RpcMethod.GetMaxSendableAmount: { + assert(params, GetMaxSendableAmountRequestStruct); + return this.#getMaxSendableAmount(params); + } case RpcMethod.ConfirmSend: { assert(params, ConfirmSendRequestStruct); return await this.#confirmSend(params); @@ -390,6 +398,75 @@ export class RpcHandler { } } + /** + * Returns the maximum amount that would pass `onAmountInput`. + * + * Binary searches the largest amount whose probe PSBT can be funded, pricing + * the fee with the same config as `onAmountInput`. The probe PSBT is never + * signed. + * + * @param request - The request params. + * @returns The maximum sendable amount, or `0` when none can pass. + * @throws {ValidationError} When `toAddress` is not a valid destination. + */ + async #getMaxSendableAmount( + request: GetMaxSendableAmountRequest, + ): Promise { + const { accountId, toAddress } = request; + const account = await this.#accountUseCases.get(accountId); + + if ( + toAddress !== undefined && + !validateAddress(toAddress, account.network, this.#logger).valid + ) { + throw new ValidationError('Invalid Bitcoin address', { + toAddress, + network: account.network, + }); + } + + const spendableSats = account.balance.trusted_spendable.to_sat(); + if (spendableSats <= 0n) { + 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 maxSats = 0n; + + while (low <= high) { + const mid = (low + high) / 2n; + + try { + await this.#sendFlowUseCases.buildProbePsbt( + account, + formatBtcAmount(mid), + toAddress, + ); + 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; + } + } + } + + const amount = formatBtcAmount(maxSats); + if (maxSats <= 0n || !validateDustLimit(amount, account).valid) { + return { amount: '0' }; + } + + return { amount }; + } + #verifyMessage( address: string, message: string, diff --git a/packages/bitcoin-wallet-snap/src/handlers/types.ts b/packages/bitcoin-wallet-snap/src/handlers/types.ts index 1a9dbebda..5855e617c 100644 --- a/packages/bitcoin-wallet-snap/src/handlers/types.ts +++ b/packages/bitcoin-wallet-snap/src/handlers/types.ts @@ -2,10 +2,18 @@ import type { Infer } from 'superstruct'; import type { ConfirmSendRequestStruct, + GetMaxSendableAmountRequestStruct, + GetMaxSendableAmountResponseStruct, OnAddressInputRequestStruct, OnAmountInputRequestStruct, } from './validation'; export type OnAddressInputRequest = Infer; export type OnAmountInputRequest = Infer; +export type GetMaxSendableAmountRequest = Infer< + typeof GetMaxSendableAmountRequestStruct +>; +export type GetMaxSendableAmountResponse = Infer< + typeof GetMaxSendableAmountResponseStruct +>; export type ConfirmSendRequest = Infer; diff --git a/packages/bitcoin-wallet-snap/src/handlers/validation.ts b/packages/bitcoin-wallet-snap/src/handlers/validation.ts index 88cfa9db5..6dd5deea0 100644 --- a/packages/bitcoin-wallet-snap/src/handlers/validation.ts +++ b/packages/bitcoin-wallet-snap/src/handlers/validation.ts @@ -34,6 +34,7 @@ export const RpcMethod = { VerifyMessage: 'verifyMessage', OnAddressInput: 'onAddressInput', OnAmountInput: 'onAmountInput', + GetMaxSendableAmount: 'getMaxSendableAmount', ConfirmSend: 'confirmSend', SignRewardsMessage: 'signRewardsMessage', SignProofOfOwnership: 'signProofOfOwnership', @@ -74,6 +75,12 @@ export const OnAmountInputRequestStruct = object({ toAddress: optional(NonEmptyStringStruct), }); +export const GetMaxSendableAmountRequestStruct = object({ + accountId: UuidStruct, + assetId: CaipAssetTypeStruct, + toAddress: optional(NonEmptyStringStruct), +}); + export const ConfirmSendRequestStruct = object({ fromAccountId: UuidStruct, toAddress: NonEmptyStringStruct, @@ -348,6 +355,10 @@ export function validateDustLimit( const PositiveNumberStringStruct = pattern(string(), /^(?!0\d)(\d+(\.\d+)?)$/u); +export const GetMaxSendableAmountResponseStruct = object({ + amount: PositiveNumberStringStruct, +}); + /** * Parses a base64-encoded rewards message in the format 'rewards,{address},{timestamp}' *