Skip to content

Commit

Permalink
feat: finish addWAllet, get chaindId from caipId
Browse files Browse the repository at this point in the history
  • Loading branch information
vvava committed Dec 12, 2024
1 parent 9720463 commit 4286c96
Show file tree
Hide file tree
Showing 9 changed files with 219 additions and 78 deletions.
24 changes: 12 additions & 12 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,23 @@
},
"dependencies": {
"@avalabs/avalanche-module": "0.0.0-feat-CP-9461-create-hvm-module-20241210153705",
"@avalabs/avalanchejs": "4.1.0-alpha.25",
"@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/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.19",
"@avalabs/glacier-sdk": "3.1.0-alpha.27",
"@avalabs/hw-app-avalanche": "0.14.1",
"@avalabs/types": "3.1.0-alpha.19",
"@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",
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
4 changes: 3 additions & 1 deletion src/background/services/network/NetworkService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,9 @@ 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
? caipToChainId(customNetworkPayload.caipId)
: parseInt(customNetwork.chainId.toString(16), 16);
const chainlist = await this._rawNetworks.promisify();

if (!chainlist) {
Expand Down
77 changes: 57 additions & 20 deletions src/background/services/network/handlers/wallet_addNetwork.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ 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');
Expand All @@ -27,25 +28,25 @@ describe('background/services/network/handlers/wallet_addNetwork.ts', () => {
primaryColor: 'violet',
};

// const mockHvmNetwork = {
// chainName: 'hyperVM-network',
// chainId: 1243345969594372,
// 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',
// };
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;

Expand All @@ -63,6 +64,25 @@ describe('background/services/network/handlers/wallet_addNetwork.ts', () => {
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',
Expand All @@ -77,10 +97,27 @@ describe('background/services/network/handlers/wallet_addNetwork.ts', () => {
.spyOn(mockNetworkService, 'getNetwork')
.mockResolvedValue({ chainId: 43114 } as any);
const result = await handler.handleUnauthenticated(buildRpcCall(request));
console.log('result: ', result);
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,
});
});
});
21 changes: 11 additions & 10 deletions src/background/services/network/handlers/wallet_addNetwork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ import { openApprovalWindow } from '@src/background/runtime/openApprovalWindow';

import { Action } from '../../actions/models';
import { NetworkService } from '../NetworkService';
import { CustomNetworkPayload } from '../models';
import { AddNetworkPayload, CustomNetworkPayload } from '../models';
import { resolve } from '@avalabs/core-utils-sdk';
import { runtime } from 'webextension-polyfill';
import { caipToChainId } from '@src/utils/caipConversion';

type Params = [CustomNetworkPayload];
type Params = [AddNetworkPayload];

@injectable()
export class WalletAddNetworkHandler extends DAppRequestHandler<Params, null> {
Expand All @@ -36,7 +37,6 @@ export class WalletAddNetworkHandler extends DAppRequestHandler<Params, null> {
}

const [network] = request.params;
console.log('request.params network: ', network);

if (!network) {
return {
Expand All @@ -45,9 +45,9 @@ export class WalletAddNetworkHandler extends DAppRequestHandler<Params, null> {
};
}

const isCustomNetworkExist = await this.networkService.getNetwork(
network.chainId
);
const chainId = network.chainId ?? caipToChainId(network.caipId);

const isCustomNetworkExist = await this.networkService.getNetwork(chainId);

if (isCustomNetworkExist) {
return {
Expand All @@ -62,7 +62,10 @@ export class WalletAddNetworkHandler extends DAppRequestHandler<Params, null> {
...request,
scope,
displayData: {
network,
network: {
...network,
chainId,
},
},
};

Expand All @@ -83,12 +86,10 @@ export class WalletAddNetworkHandler extends DAppRequestHandler<Params, null> {
) => {
try {
const { network } = pendingAction.displayData;
console.log('onActionApproved network: ', network);

const [addedNetwork, err] = await resolve(
this.networkService.saveCustomNetwork(network)
);
console.log('addedNetwork: ', addedNetwork);
console.log('err: ', err);

if (err || !addedNetwork) {
throw new Error(String(err));
Expand Down
29 changes: 22 additions & 7 deletions src/background/services/network/models.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { Network as _Network } from '@avalabs/core-chains-sdk';
import {
Network as _Network,
NetworkToken,
NetworkVMType,
} from '@avalabs/core-chains-sdk';
import { EnsureDefined, PartialBy } from '@src/background/models';

export enum NetworkEvents {
Expand Down Expand Up @@ -51,12 +55,10 @@ export type AdvancedNetworkConfig = {
customRpcHeaders?: CustomRpcHeaders;
};

export type CustomNetworkPayload = Omit<
Network & {
chainId: number | string; // Chain ID may come in hex-encoded through wallet_addEthereumChain call.
},
'caipId'
>;
export type CustomNetworkPayload = Network & {
chainId: number | string; // Chain ID may come in hex-encoded through wallet_addEthereumChain call.
caipId?: string;
};

export type AddEthereumChainDisplayData = {
network: EnsureDefined<Network, 'caipId'>;
Expand All @@ -65,4 +67,17 @@ export type AddEthereumChainDisplayData = {
};
};

export interface AddNetworkPayload {
caipId: string;
chainName: string;
rpcUrl: string;
vmName: NetworkVMType;
tokenName: string;
decimals: number;
networkToken: NetworkToken;
logoUri: string;
explorerUrl: string;
chainId?: number;
}

export const PLACEHOLDER_RPC_HEADERS = { '': '' };
4 changes: 4 additions & 0 deletions src/background/services/secrets/SecretsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -787,6 +787,8 @@ export class SecretsService implements OnUnlock {
[NetworkVMType.AVM]: xAddr,
[NetworkVMType.PVM]: pAddr,
[NetworkVMType.CoreEth]: cAddr,
// TODO: getaddressfromhvm
[NetworkVMType.HVM]: getAddressFromXPub(secrets.xpub, index),
};
}

Expand Down Expand Up @@ -821,6 +823,8 @@ export class SecretsService implements OnUnlock {
[NetworkVMType.AVM]: addrX,
[NetworkVMType.PVM]: addrP,
[NetworkVMType.CoreEth]: providerXP.getAddress(pubKeyBuffer, 'C'),
// TODO: getHvmAddressFromPubkey
[NetworkVMType.HVM]: getEvmAddressFromPubKey(pubKeyBuffer),
};
}

Expand Down
15 changes: 10 additions & 5 deletions src/utils/caipConversion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ const AvaxCaipId = {
} as const;

export const getNetworkCaipId = (network: PartialBy<Network, 'caipId'>) => {
if (network.caipId) {
return network.caipId;
}
if (network.vmName === NetworkVMType.EVM) {
return `eip155:${network.chainId}`;
}
Expand All @@ -39,10 +42,9 @@ export const getNetworkCaipId = (network: PartialBy<Network, 'caipId'>) => {
return AvaxCaipId[network.chainId];
}

// TODO: fix
// if (network.vmName === NetworkVMType.HVM) {
// return `hvm:${network.chainId}`;
// }
if (network.vmName === NetworkVMType.HVM) {
return `hvm:${network.chainId}`;
}

throw new Error('Unsupported VM type: ' + network.vmName);
};
Expand All @@ -58,10 +60,13 @@ export const caipToChainId = (identifier: string): number => {
throw new Error('No reference found in identifier: ' + identifier);
}

if (namespace === CaipNamespace.EIP155 || namespace === CaipNamespace.HVM) {
if (namespace === CaipNamespace.EIP155) {
return Number(reference);
}

if (reference.length === 32 && namespace === CaipNamespace.HVM) {
return parseInt(reference.slice(0, 16), 16);
}
if (namespace === CaipNamespace.BIP122) {
const chainId = Object.keys(BitcoinCaipId).find(
(chainIdLookup) => BitcoinCaipId[chainIdLookup] === identifier
Expand Down
Loading

0 comments on commit 4286c96

Please sign in to comment.