Skip to content

Commit

Permalink
update massa-web3
Browse files Browse the repository at this point in the history
  • Loading branch information
peterjah committed Dec 3, 2024
1 parent 5f88b16 commit 095c654
Show file tree
Hide file tree
Showing 55 changed files with 1,421 additions and 1,957 deletions.
2 changes: 1 addition & 1 deletion packages/dapp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"@chakra-ui/react": "^2.8.2",
"@emotion/react": "^11.11.4",
"@emotion/styled": "^11.11.0",
"@massalabs/massa-web3": "^4.0.3",
"@massalabs/massa-web3": "^5.0.1-dev",
"@metamask/providers": "^15.0.0",
"framer-motion": "^11.0.8",
"next": "14.1.1",
Expand Down
14 changes: 9 additions & 5 deletions packages/dapp/src/components/NetworkMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,23 @@ import {
Button,
Spinner,
} from '@chakra-ui/react';
import { CHAIN_ID, DefaultProviderUrls } from '@massalabs/massa-web3';

import { invalidateNetwork, useNetwork } from '@/hooks/useNetwork';
import { invalidateOperations } from '@/hooks/useOperations';
import { useSetNetwork } from '@/hooks/useSetNetwork';
import { invalidateTokens } from '@/hooks/useTokens';
import { CHAIN_ID, NetworkName, PublicApiUrl } from '@massalabs/massa-web3';

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

Expand Down
39 changes: 13 additions & 26 deletions packages/dapp/src/components/OperationRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,14 @@

import { CheckCircleIcon, WarningIcon } from '@chakra-ui/icons';
import { AlertIcon, Link, Td, Tr } from '@chakra-ui/react';
import type { IOperationData, ITransactionOpType } from '@massalabs/massa-web3';
import type {
ICallSmartContractOpType,
IExecSmartContractOpType,
IRollBuyOpType,
IRollSellOpType,
} from '@massalabs/massa-web3/dist/esm/interfaces/OperationTypes';
import { rpcTypes } from '@massalabs/massa-web3';
import { useMemo } from 'react';

export const OperationRow = ({ operation }: { operation: IOperationData }) => {
export const OperationRow = ({
operation,
}: {
operation: rpcTypes.OperationInfo;
}) => {
const getStatusIcon = useMemo(() => {
if (operation.op_exec_status === true) {
return <CheckCircleIcon color={'green'} />;
Expand All @@ -22,28 +20,17 @@ export const OperationRow = ({ operation }: { operation: IOperationData }) => {
}, [operation]);

const getOperationType = useMemo(() => {
if (
(operation.operation.content.op as ITransactionOpType).Transaction !==
undefined
) {
const { op } = operation.operation.content;

if (!!op.Transaction) {
return 'Transaction';
} else if (
(operation.operation.content.op as ICallSmartContractOpType).CallSC !==
undefined
) {
} else if (!!op.CallSC) {
return 'Smart Contract Call';
} else if (
(operation.operation.content.op as IExecSmartContractOpType).ExecuteSC !==
undefined
) {
} else if (!!op.ExecutSC) {
return 'Smart Contract Execution';
} else if (
(operation.operation.content.op as IRollBuyOpType).RollBuy !== undefined
) {
} else if (!!op.RollBuy) {
return 'Roll Buy';
} else if (
(operation.operation.content.op as IRollSellOpType).RollSell !== undefined
) {
} else if (!!op.RollSell) {
return 'Roll Sell';
}
return 'Unknown';
Expand Down
18 changes: 6 additions & 12 deletions packages/dapp/src/components/SendTransactionModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ import {
ModalHeader,
ModalOverlay,
} from '@chakra-ui/react';
import { fromMAS } from '@massalabs/massa-web3';
import { useMemo, useRef, useState } from 'react';

import { invalidateOperations } from '@/hooks/useOperations';
import { useTransfer } from '@/hooks/useTransfer';
import { Mas } from '@massalabs/massa-web3';

export const TxModal = ({
isOpen,
Expand All @@ -29,22 +29,16 @@ export const TxModal = ({

const [recipientAddress, setReceiver] = useState<string>('');
const [amount, setAmount] = useState<string>('0');
const [fee, setFee] = useState<string>('0');
const [fee, setFee] = useState<string>('');
const transfer = useTransfer();

const isFormValid = useMemo(() => {
if (recipientAddress === '' || amount === '' || fee === '') {
if (recipientAddress === '' || amount === '') {
// TODO: Show error message
return false;
}
try {
BigInt(amount);
BigInt(fee);
} catch (error) {
return false;
}
return true;
}, [recipientAddress, amount, fee]);
}, [recipientAddress, amount]);

return (
<Modal
Expand Down Expand Up @@ -101,8 +95,8 @@ export const TxModal = ({
onClick={async () => {
await transfer({
recipientAddress,
amount: fromMAS(amount).toString(),
fee: fromMAS(fee).toString(),
amount: Mas.fromString(amount).toString(),
fee: fee !== '' ? Mas.fromString(fee).toString() : undefined,
});
invalidateOperations();
onClose(false);
Expand Down
11 changes: 6 additions & 5 deletions packages/dapp/src/components/TokenRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { DeleteIcon } from '@chakra-ui/icons';
import { IconButton, Td, Tr } from '@chakra-ui/react';
import { Args, bytesToStr, bytesToU256 } from '@massalabs/massa-web3';
import { Args, bytesToStr, U256 } from '@massalabs/massa-web3';
import { useEffect, useState, useCallback } from 'react';

import { useActiveAccount } from '@/hooks/useActiveAccount';
Expand Down Expand Up @@ -34,7 +34,7 @@ export const TokenRow = ({ token }: { token: string }) => {
console.warn(`No response from readSC ${readData.functionName}`);
return;
}
const decimals = new Args(res.data).nextU8();
const decimals = new Args(Uint8Array.from(res.data!)).nextU8();

readData.functionName = 'symbol';
res = await readSC(readData);
Expand All @@ -45,15 +45,16 @@ export const TokenRow = ({ token }: { token: string }) => {
const symbol = bytesToStr(Uint8Array.from(res.data!));
setTokenName(symbol);

const serAddr = new Args().addString(account.address).serialize();
readData.args = serAddr;
readData.args = Array.from(
new Args().addString(account.address).serialize(),
);
readData.functionName = 'balanceOf';
res = await readSC(readData);
if (!res) {
console.warn(`No response from readSC ${readData.functionName}`);
return;
}
const rBalance = bytesToU256(Uint8Array.from(res.data!));
const rBalance = U256.fromBytes(Uint8Array.from(res.data!));
const balanceNormalized =
Number(rBalance / BigInt(10 ** (Number(decimals) - 3))) / 10 ** 3;

Expand Down
5 changes: 2 additions & 3 deletions packages/dapp/src/components/TokenTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { TokenRow } from './TokenRow';
import { useAccountBalance } from '@/hooks/useAccountBalance';
import { useActiveAccount } from '@/hooks/useActiveAccount';
import { useTokens } from '@/hooks/useTokens';
import { Mas } from '@massalabs/massa-web3';

export type AccountToken = { name: string; address: string; decimals: number };

Expand Down Expand Up @@ -60,9 +61,7 @@ export const TokenTab = () => {
if (isLoadingAccountBalance || !accountBalance) {
return <Spinner />;
}
return (
Number(BigInt(accountBalance.finalBalance) / BigInt(10 ** 6)) / 10 ** 3
);
return Mas.toString(BigInt(accountBalance.finalBalance));
}, [accountBalance, isLoadingAccountBalance]);

return (
Expand Down
11 changes: 3 additions & 8 deletions packages/dapp/src/hooks/useMassaClient.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,19 @@
import type { Client } from '@massalabs/massa-web3';
import { ClientFactory } from '@massalabs/massa-web3';
import { useCallback, useEffect, useState } from 'react';

import type { NetworkInfos } from './useNetwork';
import { useNetwork } from './useNetwork';
import { JsonRPCClient } from '@massalabs/massa-web3';

/**
* @description Hook that creates a massa client from 'massa-web3' using the current network (updates when the network changes)
* @returns The massa client
*/
export const useMassaClient = () => {
const { data: network } = useNetwork();
const [client, setClient] = useState<Client>();
const [client, setClient] = useState<JsonRPCClient>();
const createClient = useCallback(
async (net: NetworkInfos) => {
const newClient = await ClientFactory.createDefaultClient(
net.rpcUrl as any,
BigInt(net.chainId),
);
setClient(newClient);
setClient(new JsonRPCClient(net.rpcUrl));
},
[setClient],
);
Expand Down
8 changes: 5 additions & 3 deletions packages/dapp/src/hooks/useOperationsData.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import type { IOperationData } from '@massalabs/massa-web3';
import { useCallback, useEffect, useState } from 'react';

import { useMassaClient } from './useMassaClient';
import { rpcTypes } from '@massalabs/massa-web3';

/**
* @description Hook that calls the massa client to get the operations data
* @param operationIds - The operation ids to get the data from
* @returns The operations data (@see `IOperationData` for more information)
*/
export const useOperationsData = (operationIds: string[]) => {
const [operationsData, setOperationsData] = useState<IOperationData[]>([]);
const [operationsData, setOperationsData] = useState<
rpcTypes.OperationInfo[]
>([]);
const client = useMassaClient();

const setOperationsInfos = useCallback(async () => {
if (!client) {
return;
}
try {
const res = await client.publicApi().getOperations(operationIds);
const res = await client.getOperations(operationIds);
setOperationsData(res);
} catch (error) {
console.error(error);
Expand Down
2 changes: 1 addition & 1 deletion packages/dapp/src/hooks/useTransfer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { defaultSnapOrigin } from '@/config';
export type TransferParams = {
recipientAddress: string;
amount: string;
fee: string;
fee?: string;
};

export type TransferResponse = {
Expand Down
6 changes: 4 additions & 2 deletions packages/snap/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,11 @@
"test": "jest"
},
"dependencies": {
"@massalabs/massa-web3": "^4.0.3",
"@massalabs/massa-web3": "^5.0.1-dev",
"@metamask/key-tree": "^9.0.0",
"@metamask/snaps-sdk": "^6.10.0",
"buffer": "^6.0.3"
"buffer": "^6.0.3",
"varint": "^6.0.0"
},
"devDependencies": {
"@jest/globals": "^29.5.0",
Expand All @@ -44,6 +45,7 @@
"@types/jest": "^29.5.12",
"@types/react": "18.2.14",
"@types/react-dom": "18.2.4",
"@types/varint": "^6.0.3",
"@typescript-eslint/eslint-plugin": "^5.42.1",
"@typescript-eslint/parser": "^5.42.1",
"eslint": "^8.45.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/massalabs/metamask-massa.git"
},
"source": {
"shasum": "Yj5vc0Btmwc469HpD7oRnhRAXLXh+XGnxX4mWP421fU=",
"shasum": "KHYaXuehXQ9AmSorULWLkNqB1RlycfosKAiS3+f2Upg=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
29 changes: 0 additions & 29 deletions packages/snap/src/accounts/clients.ts

This file was deleted.

37 changes: 11 additions & 26 deletions packages/snap/src/accounts/hd-deriver.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,15 @@
import type { IAccount } from '@massalabs/massa-web3';
import {
utils,
KEYS_VERSION_NUMBER,
SECRET_KEY_PREFIX,
WalletClient,
} from '@massalabs/massa-web3';
import { Account, PrivateKey } from '@massalabs/massa-web3';
import type { JsonSLIP10Node } from '@metamask/key-tree';
import varint from 'varint';

/**
*
*/
export async function getHDAccount(): Promise<IAccount> {
const KEYS_VERSION_NUMBER = 0;

export async function getHDAccount(): Promise<Account> {
const secretKey = await retrieveSecretKey();
return WalletClient.getAccountFromSecretKey(secretKey);
return Account.fromPrivateKey(secretKey);
}

/**
*
*/
async function retrieveSecretKey(): Promise<string> {
async function retrieveSecretKey(): Promise<PrivateKey> {
const account = await retrieveSlip10Path();

if (!account?.privateKey) {
Expand All @@ -27,18 +18,12 @@ async function retrieveSecretKey(): Promise<string> {

const bytes = new TextEncoder().encode(account.privateKey.slice(0, 32));

const version = Uint8Array.from(
utils.crypto.varintEncode(KEYS_VERSION_NUMBER),
);
const encoded = utils.crypto.base58Encode(
Uint8Array.from([...version, ...bytes]),
);
return SECRET_KEY_PREFIX + encoded;
// add version number to the key bytes
const versionBytes = varint.encode(KEYS_VERSION_NUMBER);
const keyBytes = new Uint8Array([...versionBytes, ...bytes]);
return PrivateKey.fromBytes(keyBytes);
}

/**
*
*/
async function retrieveSlip10Path(): Promise<JsonSLIP10Node> {
const entropy = await snap.request({
method: 'snap_getBip32Entropy',
Expand Down
10 changes: 10 additions & 0 deletions packages/snap/src/accounts/provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Provider, Web3Provider } from '@massalabs/massa-web3';

import { getHDAccount } from './hd-deriver';
import { getActiveNetwork } from '../active-chain';

export async function getProvider(): Promise<Provider> {
const account = await getHDAccount();
const networkInfos = await getActiveNetwork();
return Web3Provider.fromRPCUrl(networkInfos.rpcUrl, account);
}
Loading

0 comments on commit 095c654

Please sign in to comment.