From 6cb750a446c15c6b97bd4788f9b44135571ecde9 Mon Sep 17 00:00:00 2001 From: Kami Date: Mon, 4 Dec 2023 03:07:15 +0330 Subject: [PATCH] refactor --- packages/snap/package.json | 4 ++- packages/snap/snap.manifest.json | 4 +-- packages/snap/src/rpc/getAddress.ts | 39 +++++++++++++--------- packages/snap/src/rpc/showConfirmTx.ts | 46 ++++++++++++++------------ packages/snap/src/util/getBalance.ts | 38 +++++---------------- packages/snap/src/util/getFormatted.ts | 5 +-- 6 files changed, 62 insertions(+), 74 deletions(-) diff --git a/packages/snap/package.json b/packages/snap/package.json index 1b2f658..ef32cc8 100644 --- a/packages/snap/package.json +++ b/packages/snap/package.json @@ -1,6 +1,6 @@ { "name": "@polkagate/snap", - "version": "0.1.5", + "version": "0.1.6", "description": "PolkaMask: a MetaMask Snap to interact with Polkadot ecosystem, a platform for cross-chain communication and scalability. Use your MetaMask wallet to access Polkadot dApps and tokens. No extra extension or app needed.", "repository": { "type": "git", @@ -28,7 +28,9 @@ "dependencies": { "@metamask/key-tree": "latest", "@metamask/snaps-sdk": "latest", + "@polkadot/api": "^10.11.1", "@polkadot/keyring": "latest", + "@polkadot/networks": "latest", "@polkadot/types": "latest", "@polkadot/util": "latest", "@polkadot/util-crypto": "latest", diff --git a/packages/snap/snap.manifest.json b/packages/snap/snap.manifest.json index fa7d38d..9ab0d67 100644 --- a/packages/snap/snap.manifest.json +++ b/packages/snap/snap.manifest.json @@ -1,5 +1,5 @@ { - "version": "0.1.5", + "version": "0.1.6", "description": "PolkaMask: a MetaMask Snap to interact with Polkadot, a platform for cross-chain communication and scalability. Use your MetaMask wallet to access Polkadot dApps and tokens. No extra extension or app needed.", "proposedName": "PolkaMask", "repository": { @@ -7,7 +7,7 @@ "url": "https://github.com/polkagate/polkamask.git" }, "source": { - "shasum": "q7MPyRH/1nZ9bqvITwWOJ5nGAMTfih0mLvkmIo5AOOE=", + "shasum": "K1P3QUEz9UZeHmnPLTYZmSzEoy00HeuZdjGIUa7vn3Q=", "location": { "npm": { "filePath": "dist/bundle.js", diff --git a/packages/snap/src/rpc/getAddress.ts b/packages/snap/src/rpc/getAddress.ts index 80eaa2a..b045f61 100644 --- a/packages/snap/src/rpc/getAddress.ts +++ b/packages/snap/src/rpc/getAddress.ts @@ -6,23 +6,24 @@ import { getBalances } from '../util/getBalance'; import { getGenesisHash } from '../chains'; import { getFormatted } from '../util/getFormatted'; -const AccountDemo = (address: string) => { +const AccountDemo = (address: string, balance: Balance) => { const polkadotGenesishash = getGenesisHash('polkadot'); const addressOnPolkadot = getFormatted(polkadotGenesishash, address); - + const kusamaGenesishash = getGenesisHash('kusama'); const addressOnPKusama = getFormatted(kusamaGenesishash, address); - - const acalaGenesishash = getGenesisHash('acala'); - const addressOnAcala = getFormatted(acalaGenesishash, address); return panel([ heading('Your Account on Different Chains'), divider(), - panel([text('Any chain/Westend'), copyable(address), divider()]), + panel([ + text('Any chain / Westend'), + copyable(address), + text(`balance: ${balance.toHuman()}`), + divider(), + ]), panel([text('Polkadot'), copyable(addressOnPolkadot), divider()]), - panel([text('Kusama'), copyable(addressOnPKusama), divider()]), - panel([text('Acala'), copyable(addressOnAcala), divider()]), + panel([text('Kusama'), copyable(addressOnPKusama)]), ]); }; @@ -35,18 +36,26 @@ export const getAddress = async (chainName?: string): Promise => { const { address } = account; - const genesisHash = getGenesisHash('westend'); - // const balance = await getBalances(genesisHash, address); - // console.log('balance:', balance) + showAddress(address); + + return address; +}; + +/** + * To show address(es) in some main chains format to users for a short while + * + * @param address - the any chain address + */ +async function showAddress(address: string) { + const genesisHash = getGenesisHash('westend'); // For testing purposes + const balance = await getBalances(genesisHash, address); /** to show the address to user */ snap.request({ method: 'snap_dialog', params: { type: 'alert', - content: AccountDemo(address), + content: AccountDemo(address, balance), }, }); - - return address; -}; +} diff --git a/packages/snap/src/rpc/showConfirmTx.ts b/packages/snap/src/rpc/showConfirmTx.ts index e303825..eb746c6 100644 --- a/packages/snap/src/rpc/showConfirmTx.ts +++ b/packages/snap/src/rpc/showConfirmTx.ts @@ -41,6 +41,12 @@ export function fixFloatingPoint( return integerDigits + fractionalDigits; } +function formatCamelCase(input: string) { + return input + .replace(/([a-z])([A-Z])/g, '$1 $2') // Add space between camelCase + .replace(/\b(\w)/, (char) => char.toUpperCase()); // Capitalize the first letter +} + export function amountToHuman( _amount: string | number | BN | bigint | Compact | undefined, _decimals: number | undefined, @@ -66,10 +72,8 @@ const confirmation = ( ) => { const headingText = `Transaction Approval Request from ${origin}`; - const extrinsicCall = api.createType('Call', payload.method); - const { method, section } = api.registry.findMetaCall( - extrinsicCall.callIndex, - ); + const { args, callIndex } = api.createType('Call', payload.method); + const { method, section } = api.registry.findMetaCall(callIndex); const action = `${section}_${method}`; @@ -80,20 +84,20 @@ const confirmation = ( const token = api.registry.chainTokens[0]; let amount; - const isNoArgsMethod = extrinsicCall.args?.length === 0 && 'noArgsMethods'; + const isNoArgsMethod = args?.length === 0 && 'noArgsMethods'; switch (isNoArgsMethod || action) { case 'balances_transfer': case 'balances_transferKeepAlive': case 'balances_transferAll': - const to = `${extrinsicCall.args[0]}`; - amount = String(extrinsicCall.args[1]); + const to = `${args[0]}`; + amount = String(args[1]); return panel([ heading(headingText), divider(), panel([ - text(`Method: ${method}`), + text(`Method: ${formatCamelCase(method)}`), divider(), text(`To:`), copyable(to), @@ -104,14 +108,14 @@ const confirmation = ( ]), ]); case 'staking_bond': - amount = `${extrinsicCall.args[0]}`; - const payee = String(extrinsicCall.args[1]); + amount = `${args[0]}`; + const payee = String(args[1]); return panel([ heading(headingText), divider(), panel([ - text(`Method: ${method}`), + text(`Method: ${formatCamelCase(method)}`), divider(), text(`Amount: ${amountToHuman(amount, decimal)} ${token}`), divider(), @@ -125,15 +129,13 @@ const confirmation = ( panel([ text(`Method: ${method}`), divider(), - text(`Validators: ${extrinsicCall.args[0]}`), + text(`Validators: ${args[0]}`), ]), ]); case 'nominationPools_unbond': case 'staking_unbond': case 'staking_bondExtra': - amount = `${ - extrinsicCall.args[action === 'nominationPools_unbond' ? 1 : 0] - }`; + amount = `${args[action === 'nominationPools_unbond' ? 1 : 0]}`; return panel([ heading(headingText), @@ -151,12 +153,12 @@ const confirmation = ( panel([ text(`Method: ${method}`), divider(), - text(`Payee: ${extrinsicCall.args[0]}`), + text(`Payee: ${args[0]}`), ]), ]); case 'nominationPools_join': - amount = `${extrinsicCall.args[0]}`; - const poolId = String(extrinsicCall.args[1]); + amount = `${args[0]}`; + const poolId = String(args[1]); return panel([ heading(headingText), @@ -170,7 +172,7 @@ const confirmation = ( ]), ]); case 'nominationPools_bondExtra': - let extra = String(extrinsicCall.args[0]); + let extra = String(args[0]); if (extra === 'Rewards') { extra = 'Rewards'; } else { @@ -198,11 +200,11 @@ const confirmation = ( heading(headingText), divider(), panel([ - text(`Method: ${section}_${method}`), + text(`Method: ${action}`), divider(), - text(`Call details:`), + text(`Args:`), divider(), - text(JSON.stringify(extrinsicCall)), + text(JSON.stringify(args, null, 2)), ]), ]); } diff --git a/packages/snap/src/util/getBalance.ts b/packages/snap/src/util/getBalance.ts index 03b279c..f55d9cf 100644 --- a/packages/snap/src/util/getBalance.ts +++ b/packages/snap/src/util/getBalance.ts @@ -1,4 +1,5 @@ import { Balance } from '@polkadot/types/interfaces'; +import type { AccountData } from '@polkadot/types/interfaces/balances/types'; import { getApi } from './getApi'; import { getFormatted } from './getFormatted'; @@ -13,38 +14,15 @@ export async function getBalances( address: string, ): Promise { const api = await getApi(genesisHash); - console.log('getBalances api:', api); const formatted = getFormatted(genesisHash, address); - console.log('formatted:', formatted); - const balances = await api.derive.balances.all(formatted); - // const balances = await fetchBalance(formatted, 'https://westend-rpc.polkadot.io'); + const balances = (await api.query.system.account(formatted)) as unknown as { + data: AccountData; + }; console.log('balances:', balances); - return balances.availableBalance; -} - -/** - * - */ -async function fetchBalance(formatted: string, endpoint: string) { - return new Promise((resolve) => - fetch(endpoint, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - jsonrpc: '2.0', - method: 'system.account', - params: [formatted], - id: 1, - }), - }) - .then((response) => response.json()) - .then((data) => { - console.log('data.result.data.free:', data.result.data.free); - resolve(data.result.data.free); - }), - ); + return api.createType( + 'Balance', + balances.data.free.sub(balances.data.frozen), + ) as Balance; } diff --git a/packages/snap/src/util/getFormatted.ts b/packages/snap/src/util/getFormatted.ts index de76c6d..0ae8040 100644 --- a/packages/snap/src/util/getFormatted.ts +++ b/packages/snap/src/util/getFormatted.ts @@ -9,11 +9,8 @@ import { getChain } from '../chains'; * @returns - the formatted address */ export function getFormatted(genesisHash: string, address: string): string { - console.log('getFormatted genesisHash:', genesisHash) - const { prefix } = getChain(genesisHash as string); - console.log('getFormatted prefix:', prefix) - const publicKey = decodeAddress(address); + return encodeAddress(publicKey, prefix); }