Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
Nick-1979 committed Dec 3, 2023
1 parent 1992cd4 commit 6cb750a
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 74 deletions.
4 changes: 3 additions & 1 deletion packages/snap/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down Expand Up @@ -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",
Expand Down
4 changes: 2 additions & 2 deletions packages/snap/snap.manifest.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
{
"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": {
"type": "git",
"url": "https://github.com/polkagate/polkamask.git"
},
"source": {
"shasum": "q7MPyRH/1nZ9bqvITwWOJ5nGAMTfih0mLvkmIo5AOOE=",
"shasum": "K1P3QUEz9UZeHmnPLTYZmSzEoy00HeuZdjGIUa7vn3Q=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
39 changes: 24 additions & 15 deletions packages/snap/src/rpc/getAddress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)]),
]);
};

Expand All @@ -35,18 +36,26 @@ export const getAddress = async (chainName?: string): Promise<string> => {

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;
};
}
46 changes: 24 additions & 22 deletions packages/snap/src/rpc/showConfirmTx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<u128> | undefined,
_decimals: number | undefined,
Expand All @@ -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}`;

Expand All @@ -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),
Expand All @@ -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(),
Expand All @@ -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),
Expand All @@ -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),
Expand All @@ -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 {
Expand Down Expand Up @@ -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)),
]),
]);
}
Expand Down
38 changes: 8 additions & 30 deletions packages/snap/src/util/getBalance.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -13,38 +14,15 @@ export async function getBalances(
address: string,
): Promise<Balance> {
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;
}
5 changes: 1 addition & 4 deletions packages/snap/src/util/getFormatted.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

0 comments on commit 6cb750a

Please sign in to comment.