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

Audit #15

Merged
merged 11 commits into from
Oct 31, 2024
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -402,14 +402,14 @@ The MetaMask Snap for Massa supports the following operations:
</thead>
<tbody>
<tr>
<td><code>Provider.getNodeUrls</code></td>
<td><code>Provider.getNodeUrl</code></td>
<td></td>
<td><code>string[]<code></td>
<td><code>string<code></td>
<td></td>
<td>

```ts
['https://node1.example.com', 'https://node2.example.com'];
'https://node1.example.com';
```

</td>
Expand Down
17 changes: 10 additions & 7 deletions packages/dapp/src/components/NetworkMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ 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';
Expand All @@ -16,8 +16,12 @@ import { useSetNetwork } from '@/hooks/useSetNetwork';
import { invalidateTokens } from '@/hooks/useTokens';

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 +32,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 +46,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
6 changes: 3 additions & 3 deletions packages/dapp/src/hooks/useNodeUrls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@ import { defaultSnapOrigin } from '@/config';
* @description Hook that calls the metamask provider to get the node urls for the current active network
* @returns The node urls for the current active network
*/
export const useNodeUrls = () => {
export const useNodeUrl = () => {
const { provider } = useContext(MetaMaskContext);

return useSWR('Provider.getNodeUrls', async () =>
return useSWR('Provider.getNodeUrl', async () =>
provider?.request({
method: 'wallet_invokeSnap',
params: {
snapId: defaultSnapOrigin,
request: {
method: 'Provider.getNodeUrls',
method: 'Provider.getNodeUrl',
},
},
}),
Expand Down
26 changes: 11 additions & 15 deletions packages/snap/src/accounts/clients.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,26 @@
import type { Client, WalletClient } from '@massalabs/massa-web3';
import {
CHAIN_ID,
ClientFactory,
DefaultProviderUrls,
} from '@massalabs/massa-web3';
import { ClientFactory, 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 +32,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 setActiveRPC(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);
}
9 changes: 9 additions & 0 deletions packages/snap/src/handlers/buy-rolls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { panel, text } from '@metamask/snaps-sdk';

import { getClientWallet } from '../accounts/clients';
import type { Handler } from './handler';
import { addAccountOperation } from '../operations';
import { getHDAccount } from '../accounts/hd-deriver';

export type BuyRollsParams = {
fee: string;
Expand Down Expand Up @@ -35,6 +37,11 @@ export const buyRolls: Handler<BuyRollsParams, BuyRollsResponse> = async (
) => {
const rollsData = coerceParams(params);
const wallet: WalletClient | undefined = await getClientWallet();
const account = await getHDAccount();

if (!account) {
throw new Error('Account not found or client not logged in');
}

const confirm = await snap.request({
method: 'snap_dialog',
Expand All @@ -58,5 +65,7 @@ export const buyRolls: Handler<BuyRollsParams, BuyRollsResponse> = async (

const operationId = await wallet.buyRolls(rollsData);

await addAccountOperation(account.address!, operationId[0]!);

return { operationId: operationId[0]! };
};
2 changes: 1 addition & 1 deletion packages/snap/src/handlers/get-balance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export const getBalance: Handler<GetBalanceParams, GetBalanceResponse> = async (
const balance = await wallet.getAccountBalance(address);

return {
finalBalance: balance?.candidate?.toString() || '0',
finalBalance: balance?.final?.toString() || '0',
candidateBalance: balance?.candidate?.toString() || '0',
};
};
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 { getActiveRPC } from '../active-chain';
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,
};
};
15 changes: 15 additions & 0 deletions packages/snap/src/handlers/get-node-url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { getActiveRPC } from '../active-chain';
import type { Handler } from './handler';

// url list
export type GetNodeUrlsResponse = string;

/**
* @description Get the node urls for the current network
* @returns The node urls for the current network
*/
export const getNodeUrl: Handler<void, GetNodeUrlsResponse> = async () => {
const url = await getActiveRPC();

return url;
};
21 changes: 0 additions & 21 deletions packages/snap/src/handlers/get-node-urls.ts

This file was deleted.

3 changes: 1 addition & 2 deletions packages/snap/src/handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export * from './transfer';
export * from './get-balance';
export * from './get-network';
export * from './set-network';
export * from './get-node-urls';
export * from './get-node-url';
export * from './sell-rolls';
export * from './buy-rolls';
export * from './show-account-credentials';
Expand All @@ -13,4 +13,3 @@ export * from './delete-token';
export * from './get-tokens';
export * from './get-operations';
export * from './clear-operations';
export * from './list-account';
25 changes: 0 additions & 25 deletions packages/snap/src/handlers/list-account.ts

This file was deleted.

9 changes: 9 additions & 0 deletions packages/snap/src/handlers/sell-rolls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { panel, text } from '@metamask/snaps-sdk';

import { getClientWallet } from '../accounts/clients';
import type { Handler } from './handler';
import { addAccountOperation } from '../operations';
import { getHDAccount } from '../accounts/hd-deriver';

export type SellRollsParams = {
fee: string;
Expand Down Expand Up @@ -41,11 +43,16 @@ export const sellRolls: Handler<SellRollsParams, SellRollsResponse> = async (
) => {
const rollsData = coerceParams(params);
const wallet = await getClientWallet();
const account = await getHDAccount();

if (!wallet) {
throw new Error('Not logged in to metamask. Please log in and try again.');
}

if (!account) {
throw new Error('Account not found or client not logged in');
}

const confirm = await snap.request({
method: 'snap_dialog',
params: {
Expand All @@ -64,5 +71,7 @@ export const sellRolls: Handler<SellRollsParams, SellRollsResponse> = async (

const operationId = await wallet.sellRolls(rollsData);

await addAccountOperation(account.address!, operationId[0]!);

return { operationId: operationId[0]! };
};
Loading
Loading