Skip to content

Commit

Permalink
fix: update transaction controllers to use selected account (#4244)
Browse files Browse the repository at this point in the history
This pr updates the transaction controller to use account id from the
InternalAccount instead of an address

Related to MetaMask/accounts-planning#381

- **BREAKING**: `getSelectedAddress` is replaced with
`getSelectedAccount` in the `TransactionController`
- **BREAKING**: `getCurrentAccount` returns an `InternalAccount` instead
of a `string` in the `IncomingTransactionHelper`

- [x] I've updated the test suite for new or updated code as appropriate
- [x] I've updated documentation (JSDoc, Markdown, etc.) for new or
updated code as appropriate
- [x] I've highlighted breaking changes using the "BREAKING" category
above as appropriate

Fixes MetaMask/accounts-planning#381

---------

Co-authored-by: Charly Chevalier <charly.chevalier@consensys.net>
  • Loading branch information
2 people authored and legobeat committed Jun 11, 2024
1 parent e619ce2 commit 7a1989b
Show file tree
Hide file tree
Showing 9 changed files with 245 additions and 66 deletions.
3 changes: 3 additions & 0 deletions packages/transaction-controller/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,11 @@
},
"devDependencies": {
"@babel/runtime": "^7.23.9",
"@metamask/accounts-controller": "^16.0.0",
"@metamask/auto-changelog": "^3.4.4",
"@metamask/eth-json-rpc-provider": "^3.0.2",
"@metamask/ethjs-provider-http": "^0.3.0",
"@metamask/keyring-api": "^6.4.0",
"@types/bn.js": "^5.1.5",
"@types/jest": "^27.4.1",
"@types/node": "^16.18.54",
Expand All @@ -84,6 +86,7 @@
},
"peerDependencies": {
"@babel/runtime": "^7.23.9",
"@metamask/accounts-controller": "^16.0.0",
"@metamask/approval-controller": "^6.0.2",
"@metamask/gas-fee-controller": "^16.0.0",
"@metamask/network-controller": "^18.1.3"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import {
import type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';
import EthQuery from '@metamask/eth-query';
import HttpProvider from '@metamask/ethjs-provider-http';
import type { InternalAccount } from '@metamask/keyring-api';
import { EthAccountType } from '@metamask/keyring-api';
import type {
BlockTracker,
NetworkController,
Expand Down Expand Up @@ -439,6 +441,20 @@ const MOCK_CUSTOM_NETWORK: MockNetwork = {
};

const ACCOUNT_MOCK = '0x6bf137f335ea1b8f193b8f6ea92561a60d23a207';
const INTERNAL_ACCOUNT_MOCK = {
id: '58def058-d35f-49a1-a7ab-e2580565f6f5',
address: ACCOUNT_MOCK,
type: EthAccountType.Eoa,
options: {},
methods: [],
metadata: {
name: 'Account 1',
keyring: { type: 'HD Key Tree' },
importTime: 1631619180000,
lastSelected: 1631619180000,
},
};

const ACCOUNT_2_MOCK = '0x08f137f335ea1b8f193b8f6ea92561a60d23a211';
const NONCE_MOCK = 12;
const ACTION_ID_MOCK = '123456';
Expand Down Expand Up @@ -551,12 +567,14 @@ describe('TransactionController', () => {
* messenger.
* @param args.messengerOptions.addTransactionApprovalRequest - Options to mock
* the `ApprovalController:addRequest` action call for transactions.
* @param args.selectedAccount - The selected account to use with the controller.
* @returns The new TransactionController instance.
*/
function setupController({
options: givenOptions = {},
network = MOCK_NETWORK,
messengerOptions = {},
selectedAccount = INTERNAL_ACCOUNT_MOCK,
}: {
options?: Partial<ConstructorParameters<typeof TransactionController>[0]>;
network?: MockNetwork;
Expand All @@ -565,6 +583,7 @@ describe('TransactionController', () => {
typeof mockAddTransactionApprovalRequest
>[1];
};
selectedAccount?: InternalAccount;
} = {}) {
const unrestrictedMessenger: UnrestrictedControllerMessenger =
new ControllerMessenger();
Expand All @@ -587,7 +606,6 @@ describe('TransactionController', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getNetworkClientRegistry: () => ({} as any),
getPermittedAccounts: async () => [ACCOUNT_MOCK],
getSelectedAddress: () => ACCOUNT_MOCK,
isMultichainEnabled: false,
hooks: {},
onNetworkStateChange: network.subscribe,
Expand All @@ -605,10 +623,17 @@ describe('TransactionController', () => {
'ApprovalController:addRequest',
'NetworkController:getNetworkClientById',
'NetworkController:findNetworkClientIdByChainId',
'AccountsController:getSelectedAccount',
],
allowedEvents: [],
});

const mockGetSelectedAccount = jest.fn().mockReturnValue(selectedAccount);
unrestrictedMessenger.registerActionHandler(
'AccountsController:getSelectedAccount',
mockGetSelectedAccount,
);

const controller = new TransactionController({
...otherOptions,
messenger: restrictedMessenger,
Expand All @@ -618,6 +643,7 @@ describe('TransactionController', () => {
controller,
messenger: unrestrictedMessenger,
mockTransactionApprovalRequest,
mockGetSelectedAccount,
};
}

Expand Down
18 changes: 9 additions & 9 deletions packages/transaction-controller/src/TransactionController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Hardfork, Common, type ChainConfig } from '@ethereumjs/common';
import type { TypedTransaction } from '@ethereumjs/tx';
import { TransactionFactory } from '@ethereumjs/tx';
import { bufferToHex } from '@ethereumjs/util';
import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';
import type {
AcceptResultCallbacks,
AddApprovalRequest,
Expand Down Expand Up @@ -297,7 +298,6 @@ export type TransactionControllerOptions = {
getNetworkState: () => NetworkState;
getPermittedAccounts: (origin?: string) => Promise<string[]>;
getSavedGasFees?: (chainId: Hex) => SavedGasFees | undefined;
getSelectedAddress: () => string;
incomingTransactions?: IncomingTransactionOptions;
isMultichainEnabled: boolean;
isSimulationEnabled?: () => boolean;
Expand Down Expand Up @@ -344,7 +344,8 @@ const controllerName = 'TransactionController';
export type AllowedActions =
| AddApprovalRequest
| NetworkControllerFindNetworkClientIdByChainIdAction
| NetworkControllerGetNetworkClientByIdAction;
| NetworkControllerGetNetworkClientByIdAction
| AccountsControllerGetSelectedAccountAction;

/**
* The external events available to the {@link TransactionController}.
Expand Down Expand Up @@ -614,8 +615,6 @@ export class TransactionController extends BaseController<

private readonly getPermittedAccounts: (origin?: string) => Promise<string[]>;

private readonly getSelectedAddress: () => string;

private readonly getExternalPendingTransactions: (
address: string,
chainId?: string,
Expand Down Expand Up @@ -733,7 +732,6 @@ export class TransactionController extends BaseController<
* @param options.getNetworkState - Gets the state of the network controller.
* @param options.getPermittedAccounts - Get accounts that a given origin has permissions for.
* @param options.getSavedGasFees - Gets the saved gas fee config.
* @param options.getSelectedAddress - Gets the address of the currently selected account.
* @param options.incomingTransactions - Configuration options for incoming transaction support.
* @param options.isMultichainEnabled - Enable multichain support.
* @param options.isSimulationEnabled - Whether new transactions will be automatically simulated.
Expand Down Expand Up @@ -761,7 +759,6 @@ export class TransactionController extends BaseController<
getNetworkState,
getPermittedAccounts,
getSavedGasFees,
getSelectedAddress,
incomingTransactions = {},
isMultichainEnabled = false,
isSimulationEnabled,
Expand Down Expand Up @@ -802,7 +799,6 @@ export class TransactionController extends BaseController<
this.getGasFeeEstimates =
getGasFeeEstimates || (() => Promise.resolve({} as GasFeeState));
this.getPermittedAccounts = getPermittedAccounts;
this.getSelectedAddress = getSelectedAddress;
this.getExternalPendingTransactions =
getExternalPendingTransactions ?? (() => []);
this.securityProviderRequest = securityProviderRequest;
Expand Down Expand Up @@ -1035,7 +1031,7 @@ export class TransactionController extends BaseController<
if (origin) {
await validateTransactionOrigin(
await this.getPermittedAccounts(origin),
this.getSelectedAddress(),
this.#getSelectedAccount().address,
txParams.from,
origin,
);
Expand Down Expand Up @@ -3430,7 +3426,7 @@ export class TransactionController extends BaseController<
}): IncomingTransactionHelper {
const incomingTransactionHelper = new IncomingTransactionHelper({
blockTracker,
getCurrentAccount: this.getSelectedAddress,
getCurrentAccount: () => this.#getSelectedAccount(),
getLastFetchedBlockNumbers: () => this.state.lastFetchedBlockNumbers,
getChainId: chainId ? () => chainId : this.getChainId.bind(this),
isEnabled: this.#incomingTransactionOptions.isEnabled,
Expand Down Expand Up @@ -3843,4 +3839,8 @@ export class TransactionController extends BaseController<
).configuration.type === NetworkClientType.Custom
);
}

#getSelectedAccount() {
return this.messagingSystem.call('AccountsController:getSelectedAccount');
}
}
Loading

0 comments on commit 7a1989b

Please sign in to comment.