Skip to content
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
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

- Populate the optional `transaction_type` property on the transaction lifecycle tracking events. ([#393](https://github.com/MetaMask/internal-snaps/pull/393))

## [3.1.0]

### Added
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import type { KeyringAccount } from '@metamask/keyring-api';
import { FeeType, BtcAccountType, BtcScope } from '@metamask/keyring-api';
import {
FeeType,
BtcAccountType,
BtcScope,
TransactionType,
} from '@metamask/keyring-api';
import type { Snap } from '@metamask/snaps-jest';
import { installSnap } from '@metamask/snaps-jest';

Expand Down Expand Up @@ -97,6 +102,7 @@ describe('OnClientRequestHandler', () => {
chain_id_caip: BtcScope.Regtest,
message: 'Snap transaction submitted',
origin: ORIGIN,
transaction_type: TransactionType.Send,
tx_id: transactionId,
},
});
Expand All @@ -117,6 +123,7 @@ describe('OnClientRequestHandler', () => {
message: 'Snap transaction finalized',
chain_id_caip: BtcScope.Regtest,
account_type: BtcAccountType.P2wpkh,
transaction_type: TransactionType.Send,
tx_id: transactionId,
},
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import type { KeyringAccount } from '@metamask/keyring-api';
import { BtcAccountType, BtcScope } from '@metamask/keyring-api';
import {
BtcAccountType,
BtcScope,
TransactionType,
} from '@metamask/keyring-api';
import type { Snap } from '@metamask/snaps-jest';
import { installSnap } from '@metamask/snaps-jest';

Expand Down Expand Up @@ -93,6 +97,7 @@ describe('CronHandler', () => {
message: 'Snap transaction received',
chain_id_caip: BtcScope.Regtest,
account_type: BtcAccountType.P2wpkh,
transaction_type: TransactionType.Receive,
tx_id: txid,
},
});
Expand All @@ -116,6 +121,7 @@ describe('CronHandler', () => {
message: 'Snap transaction received',
chain_id_caip: BtcScope.Regtest,
account_type: BtcAccountType.P2wpkh,
transaction_type: TransactionType.Receive,
tx_id: txid,
},
});
Expand Down
6 changes: 3 additions & 3 deletions packages/bitcoin-wallet-snap/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ module.exports = {
coverageThreshold: {
global: {
branches: 76.02,
functions: 64.28,
lines: 83.34,
statements: 83.11,
functions: 64.39,
lines: 83.4,
statements: 83.18,
},
},
};
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": "9NN98un9yylKPM/JFLrwaVhv6lKFDfBMXOBkPifOPik=",
"shasum": "TpgI53gTWDVp3HpUr/jO13/WzJJhOUuxJjjLOVNs15o=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
3 changes: 2 additions & 1 deletion packages/bitcoin-wallet-snap/src/entities/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ export type * from './config';
export * from './chain';
export * from './currency';
export * from './send-flow';
export type * from './transaction';
export { mapToTransactionType } from './transaction';
export type { TransactionBuilder } from './transaction';
export * from './snap';
export type * from './meta-protocols';
export type * from './translator';
Expand Down
14 changes: 13 additions & 1 deletion packages/bitcoin-wallet-snap/src/entities/snap.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { AddressType, Network, WalletTx } from '@metamask/bitcoindevkit';
import type { JsonSLIP10Node, SLIP10Node } from '@metamask/key-tree';
import type { TransactionType } from '@metamask/keyring-api';
import type {
ComponentOrElement,
GetClientStatusResult,
Expand Down Expand Up @@ -276,12 +277,14 @@ export type SnapClient = {
* @param account The correlated bitcoin account
* @param tx The transaction we want to capture metrics for
* @param origin The origin/source that triggered this event
* @param transactionType The classification of the transaction.
*/
emitTrackingEvent(
eventType: TransactionBroadcastEventType,
account: BitcoinAccount,
tx: WalletTx,
origin: string,
transactionType: TransactionType,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: miss the JSDoc for transactionType

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documentation updated with commit: a4239f8

): Promise<void>;

/**
Expand All @@ -291,8 +294,13 @@ export type SnapClient = {
*
* @param account The account the transaction belongs to.
* @param origin The origin/source that triggered this event.
* @param transactionType The classification of the transaction.
*/
trackTransactionAdded(account: BitcoinAccount, origin: string): Promise<void>;
trackTransactionAdded(
account: BitcoinAccount,
origin: string,
transactionType: TransactionType,
): Promise<void>;

/**
* Track a "Transaction Approved" event when the user approves a transaction.
Expand All @@ -301,10 +309,12 @@ export type SnapClient = {
*
* @param account The account the transaction belongs to.
* @param origin The origin/source that triggered this event.
* @param transactionType The classification of the transaction.
*/
trackTransactionApproved(
account: BitcoinAccount,
origin: string,
transactionType: TransactionType,
): Promise<void>;

/**
Expand All @@ -314,10 +324,12 @@ export type SnapClient = {
*
* @param account The account the transaction belongs to.
* @param origin The origin/source that triggered this event.
* @param transactionType The classification of the transaction.
*/
trackTransactionRejected(
account: BitcoinAccount,
origin: string,
transactionType: TransactionType,
): Promise<void>;

/**
Expand Down
35 changes: 35 additions & 0 deletions packages/bitcoin-wallet-snap/src/entities/transaction.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import type { Amount, Transaction } from '@metamask/bitcoindevkit';
import { TransactionType } from '@metamask/keyring-api';
import { mock } from 'jest-mock-extended';

import type { BitcoinAccount } from './account';
import { mapToTransactionType } from './transaction';

describe('mapToTransactionType', () => {
const createAccount = (sentBtc: number): BitcoinAccount => {
const sentAmount = mock<Amount>();
jest.spyOn(sentAmount, 'to_btc').mockReturnValue(sentBtc);

const account = mock<BitcoinAccount>();
jest
.spyOn(account, 'sentAndReceived')
.mockReturnValue([sentAmount, mock<Amount>()]);
return account;
};

it('classifies a transaction that spends funds as a send', () => {
const account = createAccount(1);

expect(mapToTransactionType(account, mock<Transaction>())).toBe(
TransactionType.Send,
);
});

it('classifies a transaction that spends nothing as a receive', () => {
const account = createAccount(0);

expect(mapToTransactionType(account, mock<Transaction>())).toBe(
TransactionType.Receive,
);
});
});
30 changes: 29 additions & 1 deletion packages/bitcoin-wallet-snap/src/entities/transaction.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,32 @@
import type { Amount, Psbt, ScriptBuf } from '@metamask/bitcoindevkit';
import type {
Amount,
Psbt,
ScriptBuf,
Transaction,
} from '@metamask/bitcoindevkit';
import { TransactionType } from '@metamask/keyring-api';

import type { BitcoinAccount } from './account';

/**
* Resolves the transaction classification for a Bitcoin transaction.
*
* Bitcoin has no contract calls, so a transaction is either outgoing (`send`,
* including self-sends and consolidations) or incoming (`receive`). Used both
* for the keyring transaction payload and for the `transaction_type` analytics
* dimension, so the two can never disagree.
*
* @param account - The account the transaction belongs to.
* @param tx - The raw Bitcoin transaction.
* @returns The transaction type.
*/
export function mapToTransactionType(
account: BitcoinAccount,
tx: Transaction,
): TransactionType {
const [sent] = account.sentAndReceived(tx);
return sent.to_btc() > 0 ? TransactionType.Send : TransactionType.Receive;
}

/**
* A Bitcoin transaction builder.
Expand Down
15 changes: 14 additions & 1 deletion packages/bitcoin-wallet-snap/src/handlers/CronHandler.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { WalletTx } from '@metamask/bitcoindevkit';
import type { Amount, WalletTx } from '@metamask/bitcoindevkit';
import { TransactionType } from '@metamask/keyring-api';
import { getSelectedAccounts } from '@metamask/keyring-snap-sdk';
import { SynchronizationError } from '@metamask/snap-networks-utils';
import type { SnapsProvider, JsonRpcRequest } from '@metamask/snaps-sdk';
Expand Down Expand Up @@ -51,6 +52,17 @@ describe('CronHandler', () => {
const mockAccounts = [mockAccount1, mockAccount2];
const request = { method: 'synchronizeAccounts' } as JsonRpcRequest;

beforeEach(() => {
// Transactions built from these accounts are classified as receives.
const receivedAmount = mock<Amount>();
jest.spyOn(receivedAmount, 'to_btc').mockReturnValue(0);
for (const account of mockAccounts) {
jest
.mocked(account.sentAndReceived)
.mockReturnValue([receivedAmount, receivedAmount]);
}
});

it('synchronizes all selected accounts and emits batched events', async () => {
const mockResult1: SyncResult = {
account: mockAccount1,
Expand Down Expand Up @@ -306,6 +318,7 @@ describe('CronHandler', () => {
mockAccount1,
txNew,
'cron',
TransactionType.Receive,
);
expect(
mockSnapClient.emitAccountBalancesUpdatedEvent,
Expand Down
7 changes: 6 additions & 1 deletion packages/bitcoin-wallet-snap/src/handlers/CronHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import {
import type { JsonRpcRequest, SnapsProvider } from '@metamask/snaps-sdk';
import { array, assert, is, object, string } from 'superstruct';

import { InexistentMethodError, TrackingSnapEvent } from '../entities';
import {
InexistentMethodError,
mapToTransactionType,
TrackingSnapEvent,
} from '../entities';
import type { Logger, SnapClient, SyncResult } from '../entities';
import type { SendFlowUseCases, AccountUseCases } from '../use-cases';

Expand Down Expand Up @@ -301,6 +305,7 @@ export class CronHandler {
account,
tx,
'cron',
mapToTransactionType(account, tx.tx),
);
}
}
Expand Down
13 changes: 9 additions & 4 deletions packages/bitcoin-wallet-snap/src/handlers/mappings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,15 @@ import type {
KeyringAccount,
Transaction as KeyringTransaction,
} from '@metamask/keyring-api';
import { FeeType, TransactionStatus } from '@metamask/keyring-api';
import {
FeeType,
TransactionStatus,
TransactionType,
} from '@metamask/keyring-api';

import { canAccountTxidBeMalleated, networkToCurrencyUnit } from '../entities';
import type { BitcoinAccount } from '../entities';
import { mapToTransactionType } from '../entities/transaction';
import type { Caip19Asset } from './caip';
import { addressTypeToCaip, networkToCaip19, networkToScope } from './caip';

Expand Down Expand Up @@ -169,11 +174,11 @@ export function mapToTransaction(
const { network } = account;

const [events, timestamp, status] = mapToEvents(chainPosition);
const [sent] = account.sentAndReceived(tx);
const isSend = sent.to_btc() > 0;
const type = mapToTransactionType(account, tx);
const isSend = type === TransactionType.Send;

const transaction: KeyringTransaction = {
type: isSend ? 'send' : 'receive',
type,
id: txid.toString(),
account: account.id,
chain: networkToScope[network],
Expand Down
Loading
Loading