Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: CP-9461 wallet_addNetwork #108

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
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
32 changes: 16 additions & 16 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,25 +23,25 @@
"sentry": "node sentryscript.js"
},
"dependencies": {
"@avalabs/avalanche-module": "0.11.12",
"@avalabs/avalanchejs": "4.1.0-alpha.25",
"@avalabs/bitcoin-module": "0.11.12",
"@avalabs/avalanche-module": "0.0.0-feat-CP-9461-create-hvm-module-20241210153705",
"@avalabs/avalanchejs": "4.1.2-alpha.1",
"@avalabs/bitcoin-module": "0.0.0-feat-CP-9461-create-hvm-module-20241210153705",
"@avalabs/bridge-unified": "4.0.0",
"@avalabs/core-bridge-sdk": "3.1.0-alpha.19",
"@avalabs/core-chains-sdk": "3.1.0-alpha.19",
"@avalabs/core-coingecko-sdk": "3.1.0-alpha.19",
"@avalabs/core-covalent-sdk": "3.1.0-alpha.19",
"@avalabs/core-etherscan-sdk": "3.1.0-alpha.19",
"@avalabs/core-bridge-sdk": "3.1.0-alpha.27",
"@avalabs/core-chains-sdk": "3.1.0-alpha.27",
"@avalabs/core-coingecko-sdk": "3.1.0-alpha.27",
"@avalabs/core-covalent-sdk": "3.1.0-alpha.27",
"@avalabs/core-etherscan-sdk": "3.1.0-alpha.27",
"@avalabs/core-k2-components": "4.18.0-alpha.50",
"@avalabs/core-snowtrace-sdk": "3.1.0-alpha.19",
"@avalabs/core-token-prices-sdk": "3.1.0-alpha.19",
"@avalabs/core-utils-sdk": "3.1.0-alpha.19",
"@avalabs/core-wallets-sdk": "3.1.0-alpha.19",
"@avalabs/evm-module": "0.11.12",
"@avalabs/glacier-sdk": "3.1.0-alpha.19",
"@avalabs/core-snowtrace-sdk": "3.1.0-alpha.27",
"@avalabs/core-token-prices-sdk": "3.1.0-alpha.27",
"@avalabs/core-utils-sdk": "3.1.0-alpha.27",
"@avalabs/core-wallets-sdk": "3.1.0-alpha.27",
"@avalabs/evm-module": "0.0.0-feat-CP-9461-create-hvm-module-20241210153705",
"@avalabs/glacier-sdk": "3.1.0-alpha.27",
"@avalabs/hw-app-avalanche": "0.14.1",
"@avalabs/types": "3.1.0-alpha.19",
"@avalabs/vm-module-types": "0.11.12",
"@avalabs/types": "3.1.0-alpha.27",
"@avalabs/vm-module-types": "0.0.0-feat-CP-9461-create-hvm-module-20241210153705",
"@blockaid/client": "0.10.0",
"@coinbase/cbpay-js": "1.6.0",
"@cubist-labs/cubesigner-sdk": "0.3.28",
Expand Down
3 changes: 2 additions & 1 deletion src/background/connections/dAppConnection/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export enum DAppProviderRequest {
AVALANCHE_SIGN_MESSAGE = 'avalanche_signMessage',
BITCOIN_SEND_TRANSACTION = 'bitcoin_sendTransaction',
WALLET_RENAME = 'avalanche_renameWallet',
WALLET_ADD_NETWORK = 'wallet_addNetwork',
}

export enum Web3Event {
Expand Down Expand Up @@ -100,7 +101,7 @@ export interface JsonRpcSuccess<T = unknown> {
result: Maybe<T | symbol>;
}
export interface JsonRpcFailure {
error: EthereumProviderError<unknown> | SerializedEthereumRpcError;
error: EthereumProviderError<unknown> | SerializedEthereumRpcError | Error;
}
export declare type JsonRpcResponse<T = unknown> =
| JsonRpcSuccess<T>
Expand Down
2 changes: 2 additions & 0 deletions src/background/connections/dAppConnection/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { AvalancheSignTransactionHandler } from '@src/background/services/wallet
import { AvalancheSignMessageHandler } from '@src/background/services/messages/handlers/avalanche_signMessage';
import { AvalancheRenameAccountHandler } from '@src/background/services/accounts/handlers/avalanche_renameAccount';
import { AvalancheRenameWalletHandler } from '@src/background/services/secrets/handlers/avalanche_renameWallet';
import { WalletAddNetworkHandler } from '@src/background/services/network/handlers/wallet_addNetwork';

/**
* TODO: GENERATE THIS FILE AS PART OF THE BUILD PROCESS
Expand Down Expand Up @@ -72,6 +73,7 @@ import { AvalancheRenameWalletHandler } from '@src/background/services/secrets/h
{ token: 'DAppRequestHandler', useToken: ConnectRequestHandler },
{ token: 'DAppRequestHandler', useToken: AvalancheGetProviderState },
{ token: 'DAppRequestHandler', useToken: AvalancheRenameWalletHandler },
{ token: 'DAppRequestHandler', useToken: WalletAddNetworkHandler },
{
token: 'DAppRequestHandler',
useToken: AvalancheSendDomainMetadataHandler,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import {
import { RpcMethod } from '@avalabs/vm-module-types';
import getTargetNetworkForTx from '@src/background/services/wallet/handlers/eth_sendTransaction/utils/getTargetNetworkForTx';

const isNetworkNeeded = (method: string) => {
return !method.startsWith('wallet_');
};

export function ActiveNetworkMiddleware(
networkService: NetworkService
): Middleware<
Expand All @@ -27,6 +31,11 @@ export function ActiveNetworkMiddleware(
return;
}

if (!isNetworkNeeded(method)) {
next();
return;
}

const isEthSendTx = method === RpcMethod.ETH_SEND_TRANSACTION;
const hasParams = Array.isArray(params) && typeof params[0] === 'object';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export function DAppRequestHandlerMiddleware(
context.request.params.request.method
)
);
console.log('module: ', module);

if (!context.network) {
promise = Promise.reject(ethErrors.provider.disconnected());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ export const UNRESTRICTED_METHODS = Object.freeze([
DAppProviderRequest.AVALANCHE_SIGN_TRANSACTION,
DAppProviderRequest.AVALANCHE_SIGN_MESSAGE,
DAppProviderRequest.AVALANCHE_GET_ACCOUNT_PUB_KEY,
DAppProviderRequest.WALLET_ADD_NETWORK,
'hvm_signTransaction',
]);

const CORE_METHODS = Object.freeze([
Expand Down
18 changes: 13 additions & 5 deletions src/background/providers/ChainAgnosticProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import {
import { PartialBy } from '../models';
import { ethErrors, serializeError } from 'eth-rpc-errors';
import AbstractConnection from '../utils/messaging/AbstractConnection';
import { chainIdToCaip } from '../../utils/caipConversion';
import {
CaipNamespace,
chainIdToCaip,
getNameSpaceFromScope,
} from '../../utils/caipConversion';
import { ChainId } from '@avalabs/core-chains-sdk';
import RequestRatelimiter from './utils/RequestRatelimiter';
import {
Expand Down Expand Up @@ -64,15 +68,19 @@ export class ChainAgnosticProvider extends EventEmitter {
if (!data) {
throw ethErrors.rpc.invalidRequest();
}

const namespace = getNameSpaceFromScope(chainId);
const scope =
namespace === CaipNamespace.HVM
? chainId
: chainIdToCaip(
chainId ? parseInt(chainId) : ChainId.AVALANCHE_MAINNET_ID
);
const result = this.#contentScriptConnection
.request({
method: 'provider_request',
jsonrpc: '2.0',
params: {
scope: chainIdToCaip(
chainId ? parseInt(chainId) : ChainId.AVALANCHE_MAINNET_ID
),
scope,
sessionId,
request: {
params: [],
Expand Down
2 changes: 2 additions & 0 deletions src/background/services/accounts/AccountsService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,7 @@ describe('background/services/accounts/AccountsService', () => {
[NetworkVMType.AVM]: avmAddress,
[NetworkVMType.PVM]: pvmAddress,
[NetworkVMType.CoreEth]: coreEthAddress,
[NetworkVMType.HVM]: otherEvmAddress,
});

await accountsService.onUnlock();
Expand Down Expand Up @@ -403,6 +404,7 @@ describe('background/services/accounts/AccountsService', () => {
[NetworkVMType.AVM]: avmAddress,
[NetworkVMType.PVM]: pvmAddress,
[NetworkVMType.CoreEth]: coreEthAddress,
[NetworkVMType.HVM]: otherEvmAddress,
});
jest
.mocked(secretsService.getImportedAddresses)
Expand Down
6 changes: 5 additions & 1 deletion src/background/services/network/NetworkService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,11 @@ export class NetworkService implements OnLock, OnStorageReady {

async saveCustomNetwork(customNetworkPayload: CustomNetworkPayload) {
const customNetwork = decorateWithCaipId(customNetworkPayload);
const chainId = parseInt(customNetwork.chainId.toString(16), 16);
const chainId =
customNetworkPayload.caipId && !customNetwork.chainId
? caipToChainId(customNetworkPayload.caipId)
: parseInt(customNetwork.chainId.toString(16), 16);

const chainlist = await this._rawNetworks.promisify();

if (!chainlist) {
Expand Down
123 changes: 123 additions & 0 deletions src/background/services/network/handlers/wallet_addNetwork.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { Network, NetworkVMType } from '@avalabs/core-chains-sdk';
import { NetworkService } from '../NetworkService';
import { WalletAddNetworkHandler } from './wallet_addNetwork';
import { openApprovalWindow } from '@src/background/runtime/openApprovalWindow';
import { DAppProviderRequest } from '@src/background/connections/dAppConnection/models';
import { buildRpcCall } from '@src/tests/test-utils';
import { DEFERRED_RESPONSE } from '@src/background/connections/middlewares/models';

jest.mock('../NetworkService');
jest.mock('@src/background/runtime/openApprovalWindow');
describe('background/services/network/handlers/wallet_addNetwork.ts', () => {
const mockActiveNetwork: Network = {
chainName: 'Avalanche (C-Chain)',
chainId: 43114,
vmName: NetworkVMType.EVM,
subnetExplorerUriId: 'c-chain',
rpcUrl: 'https://api.avax.network/ext/bc/C/rpc',
explorerUrl: 'https://explorer.url',
networkToken: {
name: 'Avalanche',
symbol: 'AVAX',
decimals: 18,
description: '',
logoUri: 'token-logo.png',
},
logoUri: 'chain-logo.png',
tokens: [],
primaryColor: 'violet',
};

const mockHvmNetwork = {
chainName: 'hyperVM-network',
caipId: 'hvm:11414092629610059909939753419964',
rpcUrl: 'http://localhost',
networkToken: {
symbol: 'HVM',
decimals: 18,
description: '',
name: 'HyperToken',
logoUri: '',
},
logoUri: '',
tokenName: 'HyperToken',
decimals: 18,
vmName: NetworkVMType.HVM,
additionalProperty1: '1',
additionalProperty2: '2',
additionalProperty3: '3',
};
let mockNetworkService: NetworkService;
let handler: WalletAddNetworkHandler;

beforeEach(() => {
jest.resetAllMocks();
mockNetworkService = new NetworkService({} as any, {} as any);
jest.spyOn(mockNetworkService, 'setNetwork');
mockNetworkService.allNetworks = {
promisify: () =>
Promise.resolve({
[mockActiveNetwork.chainId]: { ...mockActiveNetwork },
[43113]: { ...mockActiveNetwork, id: 43113 },
}),
} as any;
handler = new WalletAddNetworkHandler(mockNetworkService);
(openApprovalWindow as jest.Mock).mockReturnValue({ id: 123 });
});
it('should throw an error because there is no site info', async () => {
const request = {
id: '1234',
method: DAppProviderRequest.WALLET_ADD_NETWORK,
params: [mockActiveNetwork],
site: {
domain: '',
tabId: 1,
},
};
jest
.spyOn(mockNetworkService, 'getNetwork')
.mockResolvedValue({ chainId: 43114 } as any);
const result = await handler.handleUnauthenticated(buildRpcCall(request));
expect(result).toEqual({
...request,
error: new Error('Missing dApp domain information'),
});
});
it('should return null when the network has benn already added', async () => {
const request = {
id: '1234',
method: DAppProviderRequest.WALLET_ADD_NETWORK,
params: [mockActiveNetwork],
site: {
domain: 'core.app',
tabId: 1,
},
};
jest
.spyOn(mockNetworkService, 'getNetwork')
.mockResolvedValue({ chainId: 43114 } as any);
const result = await handler.handleUnauthenticated(buildRpcCall(request));
expect(result).toEqual({
...request,
result: null,
});
});

it('should add the network properly', async () => {
const request = {
id: '1234',
method: DAppProviderRequest.WALLET_ADD_NETWORK,
params: [mockHvmNetwork],
site: {
domain: 'hvm.app',
tabId: 1,
},
};
jest.spyOn(mockNetworkService, 'getNetwork').mockResolvedValue(undefined);
const result = await handler.handleUnauthenticated(buildRpcCall(request));
expect(result).toEqual({
...request,
result: DEFERRED_RESPONSE,
});
});
});
Loading
Loading