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
4 changes: 4 additions & 0 deletions packages/bitcoin-wallet-snap/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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))
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": "ExOBCFPw5U1WWEjAfEj+GZ/+ZrBemTKNT4uIjAs0etM=",
"shasum": "fm73uO5u8Y4zhm5IYxVPrgkZfo6Uu2p98/hA1A+u/+s=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
129 changes: 129 additions & 0 deletions packages/bitcoin-wallet-snap/src/handlers/RpcHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<Amount>();
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<Amount>();
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,
Expand Down
77 changes: 77 additions & 0 deletions packages/bitcoin-wallet-snap/src/handlers/RpcHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,15 @@
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';
Expand All @@ -49,6 +52,7 @@
NO_ERRORS_RESPONSE,
INVALID_RESPONSE,
ConfirmSendRequestStruct,
GetMaxSendableAmountRequestStruct,
OnAddressInputRequestStruct,
OnAmountInputRequestStruct,
RpcMethod,
Expand Down Expand Up @@ -192,6 +196,10 @@
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);
Expand Down Expand Up @@ -390,6 +398,75 @@
}
}

/**
* 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<GetMaxSendableAmountResponse> {
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,
);

Check warning on line 447 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=AaHqJwAU-tEZSJsXxi0S&open=AaHqJwAU-tEZSJsXxi0S&pullRequest=587
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,
Expand Down
8 changes: 8 additions & 0 deletions packages/bitcoin-wallet-snap/src/handlers/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,18 @@ import type { Infer } from 'superstruct';

import type {
ConfirmSendRequestStruct,
GetMaxSendableAmountRequestStruct,
GetMaxSendableAmountResponseStruct,
OnAddressInputRequestStruct,
OnAmountInputRequestStruct,
} from './validation';

export type OnAddressInputRequest = Infer<typeof OnAddressInputRequestStruct>;
export type OnAmountInputRequest = Infer<typeof OnAmountInputRequestStruct>;
export type GetMaxSendableAmountRequest = Infer<
typeof GetMaxSendableAmountRequestStruct
>;
export type GetMaxSendableAmountResponse = Infer<
typeof GetMaxSendableAmountResponseStruct
>;
export type ConfirmSendRequest = Infer<typeof ConfirmSendRequestStruct>;
11 changes: 11 additions & 0 deletions packages/bitcoin-wallet-snap/src/handlers/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export const RpcMethod = {
VerifyMessage: 'verifyMessage',
OnAddressInput: 'onAddressInput',
OnAmountInput: 'onAmountInput',
GetMaxSendableAmount: 'getMaxSendableAmount',
ConfirmSend: 'confirmSend',
SignRewardsMessage: 'signRewardsMessage',
SignProofOfOwnership: 'signProofOfOwnership',
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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}'
*
Expand Down
Loading