Skip to content

Commit

Permalink
SAY-01 : Custom Networks Won’t Function Correctly
Browse files Browse the repository at this point in the history
rework client creation with url instead of chainId
  • Loading branch information
modship committed Oct 31, 2024
1 parent 6a8b5b0 commit 7f4259e
Show file tree
Hide file tree
Showing 19 changed files with 147 additions and 86 deletions.
18 changes: 11 additions & 7 deletions packages/dapp/src/components/NetworkMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,22 @@ import {
Button,
Spinner,
} from '@chakra-ui/react';
import { CHAIN_ID } from '@massalabs/massa-web3';
import { CHAIN_ID, DefaultProviderUrls } from '@massalabs/massa-web3';
import { useMemo } from 'react';

import { invalidateNetwork, useNetwork } from '@/hooks/useNetwork';
import { invalidateOperations } from '@/hooks/useOperations';
import { useSetNetwork } from '@/hooks/useSetNetwork';
import { invalidateTokens } from '@/hooks/useTokens';
import { url } from 'inspector';

Check warning on line 17 in packages/dapp/src/components/NetworkMenu.tsx

View workflow job for this annotation

GitHub Actions / Perform checks

'url' is defined but never used

const networkList = [
{ id: CHAIN_ID.MainNet, name: 'Mainnet' },
{ id: CHAIN_ID.BuildNet, name: 'Buildnet' },
{ id: CHAIN_ID.MainNet, name: 'Mainnet', url: DefaultProviderUrls.MAINNET },
{
id: CHAIN_ID.BuildNet,
name: 'Buildnet',
url: DefaultProviderUrls.BUILDNET,
},
];

export const NetworkMenu = () => {
Expand All @@ -28,9 +33,8 @@ export const NetworkMenu = () => {
if (activeNetwork === undefined) {
return;
}
return networkList.find(
(network) => network.id === BigInt(activeNetwork.network),
)?.name;
return networkList.find((network) => network.url === activeNetwork.network)
?.name;
}, [activeNetwork]);

return (
Expand All @@ -43,7 +47,7 @@ export const NetworkMenu = () => {
<MenuItem
key={network.id}
onClick={async () => {
await setNetwork({ network: network.id.toString() });
await setNetwork({ network: network.url });
invalidateNetwork();
invalidateTokens();
invalidateOperations();
Expand Down
6 changes: 4 additions & 2 deletions packages/dapp/src/hooks/useMassaClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ export const useMassaClient = () => {
const createClient = useCallback(
async (net: NetworkResponse) => {
const newClient = await ClientFactory.createDefaultClient(
BigInt(net?.network) === CHAIN_ID.MainNet
net?.network === DefaultProviderUrls.MAINNET
? DefaultProviderUrls.MAINNET
: DefaultProviderUrls.BUILDNET,
BigInt(net?.network),
net?.network === DefaultProviderUrls.MAINNET
? CHAIN_ID.MainNet
: CHAIN_ID.BuildNet,
);
setClient(newClient);
},
Expand Down
21 changes: 11 additions & 10 deletions packages/snap/src/accounts/clients.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,29 @@ import {
CHAIN_ID,

Check warning on line 3 in packages/snap/src/accounts/clients.ts

View workflow job for this annotation

GitHub Actions / Perform checks

'CHAIN_ID' is defined but never used
ClientFactory,
DefaultProviderUrls,

Check warning on line 5 in packages/snap/src/accounts/clients.ts

View workflow job for this annotation

GitHub Actions / Perform checks

'DefaultProviderUrls' is defined but never used
ProviderType,
} from '@massalabs/massa-web3';

import { getActiveChainId } from '../active-chain';
import { getActiveChainId, getActiveRPC } from '../active-chain';
import { getHDAccount } from './hd-deriver';

/**
*
* @param address
* @param chainId
*/
export async function getClient(chainId?: bigint): Promise<Client | undefined> {
export async function getClient(url?: string): Promise<Client | undefined> {
const account = await getHDAccount();
const chain = chainId ?? (await getActiveChainId());
const rpc = url ?? (await getActiveRPC());
const chain_id = await getActiveChainId();

if (!account) {
return undefined;
}
return await ClientFactory.createDefaultClient(
chain === CHAIN_ID.MainNet
? DefaultProviderUrls.MAINNET
: DefaultProviderUrls.BUILDNET,
chain,

return await ClientFactory.createCustomClient(
[{ url: rpc, type: ProviderType.PUBLIC }],
chain_id,
true,
account,
);
Expand All @@ -36,9 +37,9 @@ export async function getClient(chainId?: bigint): Promise<Client | undefined> {
* @param chainId
*/
export async function getClientWallet(
chainId?: bigint,
url?: string,
): Promise<WalletClient | undefined> {
const client = await getClient(chainId);
const client = await getClient(url);
if (!client) {
return undefined;
}
Expand Down
25 changes: 24 additions & 1 deletion packages/snap/src/active-chain.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CHAIN_ID } from '@massalabs/massa-web3';
import { CHAIN_ID, DefaultProviderUrls } from '@massalabs/massa-web3';

import { StateManager } from './state-manager';

Expand All @@ -23,3 +23,26 @@ export async function getActiveChainId(): Promise<bigint> {
export async function setActiveChainId(chainId: bigint) {
await StateManager.setState('activeChainId', chainId.toString());
}

/**
* @description Get the current network url
* @returns Promise of the url as a string
*/
export async function getActiveRPC(): Promise<string> {
const rpc = await StateManager.getState('activeRPC');

if (!rpc) {
await StateManager.setState('activeRPC', DefaultProviderUrls.MAINNET);
return DefaultProviderUrls.MAINNET;
}

return rpc;
}

/**
* @description Set the current network using a rpc URL
* @param chainId - Chain id as a bigint
*/
export async function setActiveRPC(url: string) {
await StateManager.setState('activeRPC', url);
}
10 changes: 5 additions & 5 deletions packages/snap/src/handlers/get-network.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { getActiveChainId } from '../active-chain';
import { getActiveChainId, getActiveRPC } from '../active-chain';

Check warning on line 1 in packages/snap/src/handlers/get-network.ts

View workflow job for this annotation

GitHub Actions / Perform checks

'getActiveChainId' is defined but never used
import type { Handler } from './handler';

export type GetNetworkResponse = {
network: string; // chainId
};

/**
* @description Get the current network chain id
* @returns The network chain id as a string
* @description Get the current network url
* @returns The network url as a string
*/
export const getNetwork: Handler<void, GetNetworkResponse> = async () => {
const chainId = await getActiveChainId();
const url = await getActiveRPC();
return {
network: chainId.toString(),
network: url,
};
};
7 changes: 3 additions & 4 deletions packages/snap/src/handlers/get-node-url.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CHAIN_ID, DefaultProviderUrls } from '@massalabs/massa-web3';

Check warning on line 1 in packages/snap/src/handlers/get-node-url.ts

View workflow job for this annotation

GitHub Actions / Perform checks

'CHAIN_ID' is defined but never used

Check warning on line 1 in packages/snap/src/handlers/get-node-url.ts

View workflow job for this annotation

GitHub Actions / Perform checks

'DefaultProviderUrls' is defined but never used

import { getActiveChainId } from '../active-chain';
import { getActiveChainId, getActiveRPC } from '../active-chain';
import type { Handler } from './handler';

// url list
Expand All @@ -12,8 +12,7 @@ export type GetNodeUrlsResponse = string;
*/
export const getNodeUrl: Handler<void, GetNodeUrlsResponse> = async () => {
const chain = await getActiveChainId();

Check warning on line 14 in packages/snap/src/handlers/get-node-url.ts

View workflow job for this annotation

GitHub Actions / Perform checks

'chain' is assigned a value but never used
const url = await getActiveRPC();

return chain == CHAIN_ID.MainNet
? (DefaultProviderUrls.MAINNET as string)
: (DefaultProviderUrls.BUILDNET as string);
return url;
};
31 changes: 25 additions & 6 deletions packages/snap/src/handlers/set-network.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { setActiveChainId } from '../active-chain';
import {
IClientConfig,
ProviderType,
PublicApiClient,
} from '@massalabs/massa-web3';
import { setActiveChainId, setActiveRPC } from '../active-chain';
import type { Handler } from './handler';

export type SetNetworkParams = {
network: string;
};

export type SetNetworkResponse = {
network: string; // chainId
network: string; // url
};

/**
Expand All @@ -22,15 +27,29 @@ const coerceParams = (params: SetNetworkParams): bigint => {
};

/**
* @description Set the current network using a chain id
* @description Set the current network using a rpc url
* @param params - The network parameters
* @returns The network chain id
* @returns The network rpc url
*/
export const setNetwork: Handler<SetNetworkParams, SetNetworkResponse> = async (
params,
) => {
const network = coerceParams(params);
if (!params.network || typeof params.network !== 'string') {
throw new Error('Invalid params: network must be a string');
}

const network = params.network;

const config: IClientConfig = {
providers: [{ url: network, type: ProviderType.PUBLIC }],
};

const publicApi = new PublicApiClient(config);
const node_status = await publicApi.getNodeStatus();

await setActiveRPC(network);
await setActiveChainId(node_status.chain_id);

await setActiveChainId(network);
console.log('Network set to:', network);
return { network: network.toString() };
};
3 changes: 2 additions & 1 deletion packages/snap/src/handlers/sign-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { getClientWallet } from '../accounts/clients';
import { getHDAccount } from '../accounts/hd-deriver';
import { getNetwork } from './get-network';

Check warning on line 5 in packages/snap/src/handlers/sign-message.ts

View workflow job for this annotation

GitHub Actions / Perform checks

'getNetwork' is defined but never used
import type { Handler } from './handler';
import { getActiveChainId } from '../active-chain';

export type SignMessageParams = {
data: number[];
Expand Down Expand Up @@ -53,7 +54,7 @@ export const signMessage: Handler<
throw new Error(`Account not found: ${signingAddress}`);
}

const { network: chainId } = await getNetwork();
const chainId = await getActiveChainId();
const confirm = await snap.request({
method: 'snap_dialog',
params: {
Expand Down
8 changes: 4 additions & 4 deletions packages/snap/src/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export type AccountsOperations = Record<string, string[]>;
/**
* @description Get operations for the given account address
* @param address - Account address as a string prefixed with 'AU'
* @returns Array of operation ids as as string array prefixed with 'OP'
* @returns Array of operation ids as as string array prefixed with 'O'
*/
export async function getAccountOperations(address: string): Promise<string[]> {
if (!address || !address.startsWith('AU')) {
Expand All @@ -29,7 +29,7 @@ export async function getAccountOperations(address: string): Promise<string[]> {
* @description Add operation to account with the given operation id for the given account address
* Does nothing if the operation is already added
* @param address - Account address as a string prefixed with 'AU'
* @param operation - Operation id as a string prefixed with 'OP'
* @param operation - Operation id as a string prefixed with 'O'
*/
export async function addAccountOperation(address: string, operation: string) {
if (!address || !address.startsWith('AU')) {
Expand All @@ -38,9 +38,9 @@ export async function addAccountOperation(address: string, operation: string) {
);
}

if (!operation || !operation.startsWith('OP')) {
if (!operation || !operation.startsWith('O')) {
throw new Error(
'Invalid params: operation must be a string and start with OP',
'Invalid params: operation must be a string and start with O',
);
}

Expand Down
13 changes: 7 additions & 6 deletions packages/snap/test/buy-rolls.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import { installSnap } from '@metamask/snaps-jest';
import { panel, text } from '@metamask/snaps-sdk';

import { setNetwork } from './utils/setNetwork';
import { DefaultProviderUrls } from '@massalabs/massa-web3';

describe('onRpcRequest', () => {
describe('buy-rolls', () => {
it('should return an operation id', async () => {
const { request } = await installSnap();
const origin = 'Jest';

await setNetwork(request, 77658366n); // BuildNet
await setNetwork(request, DefaultProviderUrls.BUILDNET); // BuildNet

const response = request({
method: 'account.buyRolls',
Expand Down Expand Up @@ -42,7 +43,7 @@ describe('onRpcRequest', () => {
const { request } = await installSnap();
const origin = 'Jest';

await setNetwork(request, 77658366n); // BuildNet
await setNetwork(request, DefaultProviderUrls.BUILDNET); // BuildNet

const response = request({
method: 'account.buyRolls',
Expand Down Expand Up @@ -75,7 +76,7 @@ describe('onRpcRequest', () => {
const { request } = await installSnap();
const origin = 'Jest';

await setNetwork(request, 77658366n); // BuildNet
await setNetwork(request, DefaultProviderUrls.BUILDNET); // BuildNet

const response = request({
method: 'account.buyRolls',
Expand All @@ -97,7 +98,7 @@ describe('onRpcRequest', () => {
const { request } = await installSnap();
const origin = 'Jest';

await setNetwork(request, 77658366n); // BuildNet
await setNetwork(request, DefaultProviderUrls.BUILDNET); // BuildNet

const response = request({
method: 'account.buyRolls',
Expand All @@ -119,7 +120,7 @@ describe('onRpcRequest', () => {
const { request } = await installSnap();
const origin = 'Jest';

await setNetwork(request, 77658366n); // BuildNet
await setNetwork(request, DefaultProviderUrls.BUILDNET); // BuildNet

const response = request({
method: 'account.buyRolls',
Expand All @@ -140,7 +141,7 @@ describe('onRpcRequest', () => {
const { request } = await installSnap();
const origin = 'Jest';

await setNetwork(request, 77658366n); // BuildNet
await setNetwork(request, DefaultProviderUrls.BUILDNET); // BuildNet

const response = request({
method: 'account.buyRolls',
Expand Down
Loading

0 comments on commit 7f4259e

Please sign in to comment.