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

Commit

Permalink
Added snap dialog before sending crypto
Browse files Browse the repository at this point in the history
  • Loading branch information
kpachhai committed Sep 26, 2023
1 parent ed09a0e commit 013526a
Show file tree
Hide file tree
Showing 7 changed files with 93 additions and 50 deletions.
31 changes: 27 additions & 4 deletions packages/site/src/components/cards/TransferCrypto.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ const TransferCrypto: FC<Props> = ({
const [loading, setLoading] = useState(false);
const { showModal } = useModal();
const [sendToAddress, setSendToAddress] = useState('');
const [sendMemo, setSendMemo] = useState('');
const [sendAmount, setSendAmount] = useState(0);

const externalAccountRef = useRef<GetExternalAccountRef>(null);

Expand All @@ -50,16 +52,15 @@ const TransferCrypto: FC<Props> = ({
{
asset: 'HBAR',
to: sendToAddress,
amount: 0.01,
amount: sendAmount,
} as SimpleTransfer,
];
const memo = '';
// const maxFee = 1; // Note that this value is in tinybars and if you don't pass it, default is 1 HBAR
// const maxFee = 1; // Note that if you don't pass this, default is 1 HBAR

const response: any = await transferCrypto(
network,
transfers,
memo,
sendMemo,
undefined,
externalAccountParams,
);
Expand Down Expand Up @@ -98,6 +99,28 @@ const TransferCrypto: FC<Props> = ({
/>
</label>
<br />
<label>
Enter memo to include(needed for exchange addresses)
<input
type="text"
style={{ width: '100%' }}
value={sendMemo}
placeholder="Memo"
onChange={(e) => setSendMemo(e.target.value)}
/>
</label>
<br />
<label>
Enter an amount of HBARs to send(in HBARs)
<input
type="text"
style={{ width: '100%' }}
value={sendAmount}
placeholder="0.01"
onChange={(e) => setSendAmount(parseFloat(e.target.value))}
/>
</label>
<br />
</>
),
button: (
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": "3Z/5TE7OM8ZF3m4WVbq+Byn/sl+KPlBhL7+4vYktYlQ=",
"shasum": "+GQraBauxdm43Ba4RQf0FFrA59AzXZeNalbkYslzVMg=",
"location": {
"npm": {
"filePath": "dist/snap.js",
Expand Down
84 changes: 58 additions & 26 deletions packages/snap/src/rpc/account/transferCrypto.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { divider, heading, panel, text } from '@metamask/snaps-ui';
import _ from 'lodash';
import {
AccountBalance,
SimpleTransfer,
TxRecord,
} from '../../services/hedera';
import { createHederaClient } from '../../snap/account';
import { snapDialog } from '../../snap/dialog';
import { TransferCryptoRequestParams } from '../../types/params';
import { PulseSnapParams } from '../../types/state';
import { PulseSnapParams, SnapDialogParams } from '../../types/state';

/**
* Transfer crypto(hbar or other tokens).
Expand All @@ -18,7 +21,7 @@ export async function transferCrypto(
pulseSnapParams: PulseSnapParams,
transferCryptoParams: TransferCryptoRequestParams,
): Promise<TxRecord> {
const { state } = pulseSnapParams;
const { origin, state } = pulseSnapParams;

const {
transfers = [] as SimpleTransfer[],
Expand All @@ -28,30 +31,59 @@ export async function transferCrypto(

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

let record = {} as TxRecord;
try {
let currentBalance =
state.accountState[metamaskAddress].accountInfo.balance;
if (!currentBalance) {
currentBalance = {} as AccountBalance;
}
const panelToShow = [
text(`Origin: ${origin}`),
divider(),
heading('Transfer Crypto'),
text('Are you sure you want to execute the following transaction(s)?'),
divider(),
text(`Memo: ${memo === null || _.isEmpty(memo) ? 'N/A' : memo}`),
text(`Max Transaction Fee: ${maxFee ?? 1} Hbar`),
];

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

record = await hederaClient.transferCrypto({
currentBalance,
transfers,
memo,
maxFee,
});
} catch (error: any) {
console.error(`Error while trying to transfer crypto: ${String(error)}`);
throw new Error(`Error while trying to transfer crypto: ${String(error)}`);
}
transfers.forEach((transfer, index) => {
panelToShow.push(divider());

const txNumber = (index + 1).toString();
panelToShow.push(text(`Transaction #${txNumber}`));
panelToShow.push(divider());

panelToShow.push(text(`Asset: ${transfer.asset}`));
panelToShow.push(text(`To: ${transfer.to}`));
panelToShow.push(text(`Amount: ${transfer.amount} Hbar`));
});

const dialogParams: SnapDialogParams = {
type: 'confirmation',
content: panel(panelToShow),
};

return record;
if (await snapDialog(dialogParams)) {
try {
let currentBalance =
state.accountState[metamaskAddress].accountInfo.balance;
if (!currentBalance) {
currentBalance = {} as AccountBalance;
}

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

return await hederaClient.transferCrypto({
currentBalance,
transfers,
memo,
maxFee,
});
} catch (error: any) {
console.error(`Error while trying to transfer crypto: ${String(error)}`);
throw new Error(
`Error while trying to transfer crypto: ${String(error)}`,
);
}
}
throw new Error('User rejected the transaction');
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export async function transferCrypto(

let outgoingHbarAmount = 0;
transaction.setTransactionMemo(options.memo ?? '');
transaction.setMaxTransactionFee(options.maxFee ?? new Hbar(1));
transaction.setMaxTransactionFee(new Hbar(options.maxFee) ?? new Hbar(1));

for (const transfer of options.transfers) {
if (transfer.asset === 'HBAR') {
Expand Down
9 changes: 3 additions & 6 deletions packages/snap/src/snap/account.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { SnapsGlobalObject } from '@metamask/snaps-types';

import { divider, heading, text } from '@metamask/snaps-ui';
import _ from 'lodash';
import {
Expand Down Expand Up @@ -73,7 +71,7 @@ export async function setCurrentAccount(
await initAccountState(snap, state, metamaskAddress);
}

await importMetaMaskAccount(origin, snap, state, network, metamaskAddress);
await importMetaMaskAccount(origin, state, network, metamaskAddress);
} catch (error: any) {
console.error(`Error while trying to get the account: ${String(error)}`);
throw new Error(`Error while trying to get the account: ${String(error)}`);
Expand All @@ -84,14 +82,12 @@ export async function setCurrentAccount(
* Veramo Import metamask account.
*
* @param origin - Source.
* @param snap - SnapsGlobalObject.
* @param state - IdentitySnapState.
* @param network - Hedera network.
* @param metamaskAddress - EVM address.
*/
export async function importMetaMaskAccount(
origin: string,
snap: SnapsGlobalObject,
state: PulseSnapState,
network: string,
metamaskAddress: string,
Expand Down Expand Up @@ -194,7 +190,8 @@ export async function importMetaMaskAccount(
divider(),
]),
};
await snapDialog(snap, dialogParamsForHederaAccountId);
await snapDialog(dialogParamsForHederaAccountId);

// TODO: Maybe offer the user an "Activate" option that will charge them "x" amount of ETH
console.error(
`This Hedera account is not yet active. Please activate it by sending some HBAR to this account. Public Key: ${publicKey}, EVM Address: ${address}`,
Expand Down
13 changes: 2 additions & 11 deletions packages/snap/src/snap/dialog.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { SnapsGlobalObject } from '@metamask/snaps-types';
import { divider, heading, panel, Panel, text } from '@metamask/snaps-ui';

import { PulseSnapState, SnapDialogParams } from '../types/state';
Expand All @@ -7,25 +6,19 @@ import { updateSnapState } from './state';
/**
* Function that toggles the disablePopups flag in the config.
*
* @param snap - Snap.
* @param state - PulseSnapState.
*/
export async function updatePopups(
snap: SnapsGlobalObject,
state: PulseSnapState,
) {
export async function updatePopups(state: PulseSnapState) {
state.snapConfig.dApp.disablePopups = !state.snapConfig.dApp.disablePopups;
await updateSnapState(snap, state);
}

/**
* Function that opens snap dialog.
*
* @param snap - Snap.
* @param params - Snap dialog params.
*/
export async function snapDialog(
snap: SnapsGlobalObject,
params: SnapDialogParams,
): Promise<string | boolean | null> {
return (await snap.request({
Expand All @@ -52,13 +45,11 @@ export async function generateCommonPanel(
* Request Hedera Account Id.
*
* @param origin - Source.
* @param snap - SnapGlobalObject.
* @param publicKey - Public key.
* @param address - EVM address.
*/
export async function requestHederaAccountId(
origin: string,
snap: SnapsGlobalObject,
publicKey: string,
address: string,
): Promise<string> {
Expand All @@ -76,5 +67,5 @@ export async function requestHederaAccountId(
]),
placeholder: '0.0.3658062',
};
return (await snapDialog(snap, dialogParamsForHederaAccountId)) as string;
return (await snapDialog(dialogParamsForHederaAccountId)) as string;
}
2 changes: 1 addition & 1 deletion packages/snap/src/utils/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export async function init(
]),
};

await snapDialog(snap, dialogParams);
await snapDialog(dialogParams);
console.log('starting init');
return await initSnapState(snap);
}

0 comments on commit 013526a

Please sign in to comment.