Skip to content
This repository has been archived by the owner on Dec 7, 2023. It is now read-only.

Commit

Permalink
Now handling parameters for the snap RPC APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
kpachhai committed Sep 25, 2023
1 parent 3bf2179 commit f28acf4
Show file tree
Hide file tree
Showing 16 changed files with 219 additions and 72 deletions.
2 changes: 2 additions & 0 deletions packages/site/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@metamask/providers": "^9.0.0",
"bignumber.js": "^9.1.2",
"bootstrap": "^5.3.2",
"lodash": "^4.17.21",
"react": "^18.2.0",
"react-bootstrap": "^2.8.0",
"react-dom": "^18.2.0",
Expand All @@ -47,6 +48,7 @@
"@testing-library/user-event": "^13.5.0",
"@types/bootstrap": "^5.2.7",
"@types/jest": "^29.5.0",
"@types/lodash.clonedeep": "^4.5.7",
"@types/react": "^18.0.15",
"@types/react-bootstrap": "^0.32.32",
"@types/react-dom": "^18.0.6",
Expand Down
22 changes: 18 additions & 4 deletions packages/site/src/components/cards/GetAccountInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ import {
} from '../../utils';
import { hederaNetworks } from '../../utils/hedera';
import { Card, SendHelloButton } from '../base';
import ExternalAccount, {
GetExternalAccountRef,
} from '../sections/ExternalAccount';
import { GetExternalAccountRef } from '../sections/ExternalAccount';

type Props = {
setCurrentNetwork: React.Dispatch<React.SetStateAction<string>>;
Expand All @@ -30,6 +28,7 @@ const GetAccountInfo: FC<Props> = ({
const [state, dispatch] = useContext(MetaMaskContext);
const [loading, setLoading] = useState(false);
const { showModal } = useModal();
const [accountId, setAccountId] = useState('');

const externalAccountRef = useRef<GetExternalAccountRef>(null);

Expand All @@ -46,6 +45,7 @@ const GetAccountInfo: FC<Props> = ({

const response: any = await getAccountInfo(
network,
accountId,
externalAccountParams,
);

Expand All @@ -68,7 +68,21 @@ const GetAccountInfo: FC<Props> = ({
content={{
title: 'getAccountInfo',
description: 'Get the current account information',
form: <ExternalAccount ref={externalAccountRef} />,
form: (
<>
{/* <ExternalAccount ref={externalAccountRef} /> */}
<label>
Enter an account Id
<input
type="text"
style={{ width: '100%' }}
value={accountId}
placeholder="Account Id(can be empty)"
onChange={(e) => setAccountId(e.target.value)}
/>
</label>
</>
),
button: (
<SendHelloButton
buttonText="Get Account Info"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,32 @@ import useModal from '../../hooks/useModal';
import { Account, SimpleTransfer } from '../../types/snap';
import {
getCurrentMetamaskAccount,
sendHbarToAccountId,
shouldDisplayReconnectButton,
transferCrypto,
} from '../../utils';
import { hederaNetworks } from '../../utils/hedera';
import { Card, SendHelloButton } from '../base';
import ExternalAccount, {
GetExternalAccountRef,
} from '../sections/ExternalAccount';
import { GetExternalAccountRef } from '../sections/ExternalAccount';

type Props = {
setCurrentNetwork: React.Dispatch<React.SetStateAction<string>>;
setMetamaskAddress: React.Dispatch<React.SetStateAction<string>>;
setAccountInfo: React.Dispatch<React.SetStateAction<Account>>;
};

const SendHbarToAccountId: FC<Props> = ({
const TransferCrypto: FC<Props> = ({
setCurrentNetwork,
setMetamaskAddress,
setAccountInfo,
}) => {
const [state, dispatch] = useContext(MetaMaskContext);
const [loading, setLoading] = useState(false);
const { showModal } = useModal();
const [sendToAddress, setSendToAddress] = useState('');

const externalAccountRef = useRef<GetExternalAccountRef>(null);

const handleSendHbarToAccountIdClick = async () => {
const handleTransferCryptoClick = async () => {
setLoading(true);
try {
const network = hederaNetworks.get('testnet') as string;
Expand All @@ -45,17 +44,19 @@ const SendHbarToAccountId: FC<Props> = ({
externalAccountRef.current?.handleGetAccountParams();

// 1 ℏ
// 0.0.633893
// 0x7d871f006d97498ea338268a956af94ab2e65cdd
const transfers: SimpleTransfer[] = [
{
asset: 'HBAR',
to: '0.0.633893',
to: sendToAddress,
amount: 0.01,
} as SimpleTransfer,
];
const memo = '';
// const maxFee: BigNumber = new BigNumber(1); // Note that this value is in tinybars and if you don't pass it, default is 1 HBAR
// const maxFee = 1; // Note that this value is in tinybars and if you don't pass it, default is 1 HBAR

const response: any = await sendHbarToAccountId(
const response: any = await transferCrypto(
network,
transfers,
memo,
Expand All @@ -80,13 +81,29 @@ const SendHbarToAccountId: FC<Props> = ({
return (
<Card
content={{
title: 'sendHbarToAccountId',
description: 'Send HBAR to Account ID',
form: <ExternalAccount ref={externalAccountRef} />,
title: 'sendHbar',
description:
'Send HBAR to another account(can pass in Account Id or EVM address but not both)',
form: (
<>
{/* <ExternalAccount ref={externalAccountRef} /> */}
<label>
Enter an account Id or an EVM address
<input
type="text"
style={{ width: '100%' }}
value={sendToAddress}
placeholder="Account Id or EVM address"
onChange={(e) => setSendToAddress(e.target.value)}
/>
</label>
<br />
</>
),
button: (
<SendHelloButton
buttonText="Send HBAR"
onClick={handleSendHbarToAccountIdClick}
onClick={handleTransferCryptoClick}
disabled={!state.installedSnap}
loading={loading}
/>
Expand All @@ -102,4 +119,4 @@ const SendHbarToAccountId: FC<Props> = ({
);
};

export { SendHbarToAccountId };
export { TransferCrypto };
4 changes: 2 additions & 2 deletions packages/site/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { Card, InstallFlaskButton } from '../components/base';
import { ConnectPulseSnap } from '../components/cards/ConnectPulseSnap';
import { GetAccountInfo } from '../components/cards/GetAccountInfo';
import { ReconnectPulseSnap } from '../components/cards/ReconnectPulseSnap';
import { SendHbarToAccountId } from '../components/cards/SendHbarToAccountId';
import { SendHelloHessage } from '../components/cards/SendHelloMessage';
import { Todo } from '../components/cards/Todo';
import { TransferCrypto } from '../components/cards/TransferCrypto';
import {
CardContainer,
ErrorMessage,
Expand Down Expand Up @@ -107,7 +107,7 @@ const Index = () => {
setAccountInfo={setAccountInfo}
/>

<SendHbarToAccountId
<TransferCrypto
setCurrentNetwork={setCurrentNetwork}
setMetamaskAddress={setMetamaskAddress}
setAccountInfo={setAccountInfo}
Expand Down
9 changes: 5 additions & 4 deletions packages/site/src/utils/snap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ export const sendHello = async (network: string) => {

export const getAccountInfo = async (
network: string,
accountId?: string,
externalAccountparams?: ExternalAccountParams,
) => {
return await window.ethereum.request({
Expand All @@ -110,7 +111,7 @@ export const getAccountInfo = async (
snapId: defaultSnapOrigin,
request: {
method: 'getAccountInfo',
params: { network, ...externalAccountparams },
params: { network, accountId, ...externalAccountparams },
},
},
});
Expand All @@ -137,10 +138,10 @@ export const getAccountBalance = async (
};

/**
* Invoke the "sendHbarToAccountId" method from the snap.
* Invoke the "transferCrypto" method from the snap.
*/

export const sendHbarToAccountId = async (
export const transferCrypto = async (
network: string,
transfers: SimpleTransfer[],
memo?: string,
Expand All @@ -152,7 +153,7 @@ export const sendHbarToAccountId = async (
params: {
snapId: defaultSnapOrigin,
request: {
method: 'sendHbarToAccountId',
method: 'transferCrypto',
params: { network, transfers, memo, maxFee, ...externalAccountparams },
},
},
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/tuum-tech/hedera-pulse.git"
},
"source": {
"shasum": "gJTZMzOaJpk9WUq2jmiaVJ1S75KIF6t0JbcP4LwpHgM=",
"shasum": "4HzdG2v/QPI7U/K81PfXpwj1SYIs6caC/g7U0mOwods=",
"location": {
"npm": {
"filePath": "dist/snap.js",
Expand Down
17 changes: 12 additions & 5 deletions packages/snap/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ import { panel, text } from '@metamask/snaps-ui';
import _ from 'lodash';
import { getAccountBalance } from './rpc/account/getAccountBalance';
import { getAccountInfo } from './rpc/account/getAccountInfo';
import { sendHbarToAccountId } from './rpc/account/sendHbarToAccountId';
import { transferCrypto } from './rpc/account/transferCrypto';
import { setCurrentAccount } from './snap/account';
import { getSnapStateUnchecked } from './snap/state';
import { PulseSnapParams } from './types/state';
import { init } from './utils/init';
import { isValidTransferCryptoParams } from './utils/params';
import {
isValidGetAccountInfoRequest,
isValidTransferCryptoParams,
} from './utils/params';

/**
* Handle incoming JSON-RPC requests, sent through `wallet_invokeSnap`.
Expand Down Expand Up @@ -75,9 +78,13 @@ export const onRpcRequest: OnRpcRequestHandler = async ({
currentAccount: state.currentAccount,
};
case 'getAccountInfo': {
isValidGetAccountInfoRequest(request.params);
return {
currentAccount: state.currentAccount,
accountInfo: await getAccountInfo(pulseSnapParams),
accountInfo: await getAccountInfo(
pulseSnapParams,
request.params.accountId,
),
};
}
case 'getAccountBalance': {
Expand All @@ -86,11 +93,11 @@ export const onRpcRequest: OnRpcRequestHandler = async ({
accountBalance: await getAccountBalance(pulseSnapParams),
};
}
case 'sendHbarToAccountId': {
case 'transferCrypto': {
isValidTransferCryptoParams(request.params);
return {
currentAccount: state.currentAccount,
record: await sendHbarToAccountId(pulseSnapParams, request.params),
record: await transferCrypto(pulseSnapParams, request.params),
};
}
default:
Expand Down
39 changes: 24 additions & 15 deletions packages/snap/src/rpc/account/getAccountInfo.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,54 @@
import _ from 'lodash';
import { HederaAccountInfo } from 'src/services/hedera';
import { createHederaClient } from '../../snap/account';
import { updateSnapState } from '../../snap/state';
import { AccountInfo } from '../../types/account';
import { PulseSnapParams } from '../../types/state';

/**
* Get account info such as address, did, public key, etc.
*
* @param pulseSnapParams - Pulse snap params.
* @param accountId - Hedera Account Id.
* @returns Account Info.
*/
export async function getAccountInfo(
pulseSnapParams: PulseSnapParams,
): Promise<AccountInfo> {
accountId?: string,
): Promise<any> {
const { state } = pulseSnapParams;

const { metamaskAddress, hederaAccountId, network } = state.currentAccount;

let accountInfo = {};

try {
const hederaClient = await createHederaClient(
state.accountState[metamaskAddress].keyStore.privateKey,
hederaAccountId,
network,
);

const response = await hederaClient.getAccountInfo(hederaAccountId);

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
state.accountState[metamaskAddress].accountInfo.balance!.hbars = Number(
response.balance.toString().replace(' ℏ', ''),
);
let response: HederaAccountInfo;
if (accountId && !_.isEmpty(accountId)) {
response = await hederaClient.getAccountInfo(accountId);
} else {
response = await hederaClient.getAccountInfo(hederaAccountId);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
state.accountState[metamaskAddress].accountInfo.balance!.hbars = Number(
response.balance.toString().replace(' ℏ', ''),
);

// Let's massage the info we want rather than spitting out everything
state.accountState[metamaskAddress].accountInfo.extraData = JSON.parse(
JSON.stringify(response),
);
await updateSnapState(snap, state);
// TODO: still need to update state.accountState[metamaskAddress].accountInfo.balance
// Let's massage the info we want rather than spitting out everything
state.accountState[metamaskAddress].accountInfo.extraData = JSON.parse(
JSON.stringify(response),
);
await updateSnapState(snap, state);
}
accountInfo = JSON.parse(JSON.stringify(response));
} catch (error: any) {
console.error(`Error while trying to get account info: ${String(error)}`);
throw new Error(`Error while trying to get account info: ${String(error)}`);
}

return state.accountState[metamaskAddress].accountInfo;
return accountInfo;
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { AccountBalance, TxRecord } from '../../services/hedera';
import {
AccountBalance,
SimpleTransfer,
TxRecord,
} from '../../services/hedera';
import { createHederaClient } from '../../snap/account';
import { TransferCryptoRequestParams } from '../../types/params';
import { PulseSnapParams } from '../../types/state';
Expand All @@ -10,13 +14,17 @@ import { PulseSnapParams } from '../../types/state';
* @param transferCryptoParams - Parameters for transferring crypto.
* @returns Account Info.
*/
export async function sendHbarToAccountId(
export async function transferCrypto(
pulseSnapParams: PulseSnapParams,
transferCryptoParams: TransferCryptoRequestParams,
): Promise<TxRecord> {
const { state } = pulseSnapParams;

const { transfers, memo = null, maxFee = null } = transferCryptoParams;
const {
transfers = [] as SimpleTransfer[],
memo = null,
maxFee = null,
} = transferCryptoParams;

const { metamaskAddress, hederaAccountId, network } = state.currentAccount;

Expand Down Expand Up @@ -45,7 +53,5 @@ export async function sendHbarToAccountId(
throw new Error(`Error while trying to transfer crypto: ${String(error)}`);
}

console.log('record: ', JSON.stringify(record, null, 4));

return record;
}
Loading

0 comments on commit f28acf4

Please sign in to comment.