Skip to content

Commit

Permalink
Fixed wallet id fetch, fixed tx signature
Browse files Browse the repository at this point in the history
  • Loading branch information
Cryptosaka committed Jun 5, 2024
1 parent 105365d commit 0a2c47b
Show file tree
Hide file tree
Showing 15 changed files with 109 additions and 63 deletions.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,9 @@
"window": {
"height": "450"
}
},
"linux": {
"target": "AppImage"
}
}
}
18 changes: 10 additions & 8 deletions packages/renderer/src/components/PasswordDecrypt.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,16 @@ export default function PasswordDecrypt({onSuccess, onClose}: IPasswordDecrypt)
return (
<div>
<p className="mt-3 text-center">Insert your password to proceed</p>
<Input
type="text"
hidden
value={password}
inputHandler={e => {
setPassword(e.target.value);
}}
/>
<div className="password-input">
<Input
type="text"
hidden
value={password}
inputHandler={e => {
setPassword(e.target.value);
}}
/>
</div>
<div className="v-spacer" />
<Row>
<Col>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ import {signTransaction} from '../../../../tools/utils';
import PasswordDecrypt from '../../../PasswordDecrypt';
import {toast} from 'react-toastify';
import {mnemonicToPrivateKey} from '../../../../../../preload/src/bip';
import {client, createPaymentInputFromPayload, createSignatureInputFromSignature} from '/@/tools';
import {client, createPaymentInputFromPayload, createSignatureInputFromSignature, toNanoMINA} from '/@/tools';
import {ERROR_CODES} from '/@/tools/zkapp';
import ConfirmZkappLedger from './ConfirmZkappLedger';
import TransactionData from './TransactionData';
import {IBalanceContext} from '/@/contexts/balance/BalanceTypes';
import {BalanceContext} from '/@/contexts/balance/BalanceContext';
import * as Big from 'big.js';
import Big from 'big.js';

export default function ConfirmZkappPayment() {
const wallet = useRecoilValue(walletState);
Expand Down Expand Up @@ -57,7 +57,7 @@ export default function ConfirmZkappPayment() {
const address = getAccountAddress();
const balance = getBalance(address[0]);
const available = +(balance?.liquidUnconfirmed || 0);
if (+available > 0 && +Big(+available).sub(fee) >= 0) {
if (+available > 0 && (+Big(available).sub(fee)) >= 0) {
return true;
}
}
Expand All @@ -81,6 +81,8 @@ export default function ConfirmZkappPayment() {
...transactionData,
nonce,
from: address[0],
amount: toNanoMINA(transactionData.amount),
fee: toNanoMINA(transactionData.fee),
});
completePayment(signedTx);
};
Expand Down Expand Up @@ -110,7 +112,7 @@ export default function ConfirmZkappPayment() {
// Define the required balance
const {fee} = transactionData;
// Check if the current balance is sufficient
if (checkBalance(fee)) {
if (checkBalance(toNanoMINA(fee))) {
// If the balance is sufficient, change the state
setShowPassword(true);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const ZkappIframe = () => {
<iframe
id="zkapp-iframe"
loading="lazy"
src="http://localhost:3001/"
src={import.meta.env.VITE_REACT_APP_ZKAPP_STORE}
frameBorder="0"
style={{width: '100%', height: '85vh', borderRadius: '16px'}}
></iframe>
Expand Down
19 changes: 12 additions & 7 deletions packages/renderer/src/components/ZkappIntegration.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {useRecoilValue, useSetRecoilState, useRecoilState} from 'recoil';
import {DEFAULT_FEE, client} from '../tools';
import {DEFAULT_FEE, client, toNanoMINA} from '../tools';
import {NetConfig, sendResponse} from '../tools/mina-zkapp-bridge';
import {
configState,
Expand Down Expand Up @@ -27,7 +27,7 @@ export default function ZkappIntegration() {
const {address: sender} = wallet;
const setZkappState = useSetRecoilState(zkappState);
const config = useRecoilValue(configState);
const [{availableNetworks, selectedNetwork}, setNetworkState] = useRecoilState(networkState);
const [{availableNetworks, selectedNetwork, selectedNode}, setNetworkState] = useRecoilState(networkState);

useEffect(() => {
setListeners();
Expand Down Expand Up @@ -144,9 +144,10 @@ export default function ZkappIntegration() {

const getNetworkConfig = async () => {
console.log('Received get-network-config');
const netConfig: NetConfig = selectedNetwork as NetConfig;
// Mock for Berkeley
// sendResponse('clorio-set-network-config', {chainId: 'berkeley', name: 'Berkeley'});
const netConfig: NetConfig = {
chainId: selectedNode?.label,
name: selectedNetwork?.name,
} as NetConfig;
sendResponse('clorio-set-network-config', netConfig);
};

Expand Down Expand Up @@ -215,7 +216,12 @@ export default function ZkappIntegration() {
setZkappState(prev => {
return {
...prev,
transactionData: {...data, from: sender},
transactionData: {
...data,
from: sender,
fee: data.fee || DEFAULT_FEE,
amount: data.amount,
},
showPaymentConfirmation: true,
isPendingConfirmation: true,
type: 'send-payment',
Expand Down Expand Up @@ -315,7 +321,6 @@ export default function ZkappIntegration() {
rejectIfLedger();
console.log('Received verify-message');
const parsedDocument = {...data, signature: JSON.parse(data.signature)};
console.log('🚀 ~ verifyMessage ~ parsedDocument:', parsedDocument);
const verified = await (await client()).verifyMessage(parsedDocument);
sendResponse('clorio-verified-message', verified);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {GET_ID} from '../../graphql/query';
import type {IWalletIdData} from '../../types/WalletIdData';
import {DEFAULT_QUERY_REFRESH_INTERVAL} from '../../tools';
import {useWallet} from '/@/contexts/WalletContext';
import {useRecoilState, useRecoilValue} from 'recoil';
import {walletState} from '/@/store';

const UserIDUpdater = () => {
const [address, setAddress] = useState<string>('');
Expand All @@ -13,7 +15,8 @@ const UserIDUpdater = () => {
skip: !address,
pollInterval: DEFAULT_QUERY_REFRESH_INTERVAL,
});
const {wallet, updateWallet} = useWallet();
// const {wallet, updateWallet} = useWallet();
const [wallet, updateWallet] = useRecoilState(walletState);

/**
* Read the wallet address from the storage and set it inside the component state
Expand All @@ -34,9 +37,9 @@ const UserIDUpdater = () => {
if (userID?.idByPublicKey) {
updateUser(address, +userID.idByPublicKey.id);
if ((userID && !wallet.id) || +wallet.id === -1) {
updateWallet({...wallet, id: +userID.idByPublicKey.id});
updateWallet(state => ({...state, id: +userID.idByPublicKey.id}));
}
stopPolling();
// stopPolling();
}
}, [userID]);

Expand Down
4 changes: 2 additions & 2 deletions packages/renderer/src/pages/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ function Login({toggleLoader}: IProps) {
*/
const checkCredentials = async () => {
try {
const derivedAccount = await deriveAccount(privateKey);
const derivedAccount = await deriveAccount(privateKey.trim());
if (derivedAccount.publicKey) {
setPublicKey(derivedAccount.publicKey);
await userIdRefetch({publicKey: derivedAccount.publicKey});
Expand Down Expand Up @@ -187,7 +187,7 @@ function Login({toggleLoader}: IProps) {
};

const onSecureStorageSubmit = (key: string) => {
encryptData({key, data: privateKey});
encryptData({key, data: privateKey.trim()});
if (userIdData) {
saveAndStoreSession();
} else {
Expand Down
7 changes: 5 additions & 2 deletions packages/renderer/src/pages/Overview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import type {
} from '../components/transactionsTable/TransactionsTypes';
import type {IHomeNewsQuery} from '/@/types/NewsData';
import {useWallet} from '../contexts/WalletContext';
import {useRecoilValue} from 'recoil';
import {walletState} from '../store';

interface IProps {
sessionData: IWalletData;
Expand All @@ -29,6 +31,7 @@ const Overview = ({sessionData}: IProps) => {
const {balanceData} = useContext<Partial<IBalanceContext>>(BalanceContext);
const balance = balanceData?.balances[sessionData.address];
const {wallet} = useWallet();
const {id} = useRecoilValue(walletState);
const [offset, setOffset] = useState<number>(0);
const [walletId, setWalletId] = useState<number>(+sessionData.id);
const {data: newsData} = useQuery<IHomeNewsQuery>(GET_HOME_NEWS);
Expand All @@ -41,9 +44,9 @@ const Overview = ({sessionData}: IProps) => {
stopPolling: transactionStopPolling,
startPolling: transactionStartPolling,
} = useQuery<ITransactionQueryResult>(GET_TRANSACTIONS, {
variables: {accountId: walletId, offset},
variables: {accountId: +id || walletId, offset},
fetchPolicy: 'network-only',
skip: !wallet.id || wallet.id === -1,
skip: !id,
pollInterval: DEFAULT_QUERY_REFRESH_INTERVAL,
});
const {
Expand Down
4 changes: 2 additions & 2 deletions packages/renderer/src/pages/SplashScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ const SplashScreen = ({toggleLoader}: IProps) => {
variables: {publicKey: derivedAccount.publicKey as string},
});
if (called) {
const id = +data ? data.idByPublicKey.id || -1 : -1;
const id = data?.idByPublicKey.id || -1;
const isUsingMnemonic = privateKey.trim().split(' ').length === 12;
setPassphrase(isUsingMnemonic);
const success = await storeSession(derivedAccount.publicKey, id, false, 0, isUsingMnemonic);
const success = await storeSession(derivedAccount.publicKey, +id, false, 0, isUsingMnemonic);
updateWallet({
address: derivedAccount.publicKey,
id,
Expand Down
52 changes: 36 additions & 16 deletions packages/renderer/src/pages/sendTX/SendTX.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {useState, useEffect, useContext} from 'react';
import {useQuery, useMutation} from '@apollo/client';
import {useQuery, useMutation, useLazyQuery} from '@apollo/client';
import {useNavigate} from 'react-router-dom';
import {toast} from 'react-toastify';
import TransactionForm from '/@/components/forms/transactionForm/TransactionForm';
Expand All @@ -22,9 +22,10 @@ import {
MINIMUM_NONCE,
deriveAccount,
getPassphrase,
toMINA,
} from '/@/tools';
import Spinner from '/@/components/UI/Spinner';
import {BROADCAST_TRANSACTION, GET_FEE, GET_NONCE} from '/@/graphql/query';
import {BROADCAST_TRANSACTION, GET_BALANCE, GET_FEE, GET_NONCE} from '/@/graphql/query';
import type {INonceQueryResult} from './SendTXHelper';
import {
checkBalanceAfterTransaction,
Expand All @@ -44,6 +45,9 @@ import Stepper from '/@/components/UI/stepper/Stepper';
import TransactionAuthentication from '/@/components/transactionAuthentication/TransactionAuthentication';
import {useWallet} from '/@/contexts/WalletContext';
import {signTransaction} from '/@/tools/utils';
import {IBalanceQueryResult} from '/@/components/balance/BalanceTypes';
import {useRecoilState, useRecoilValue} from 'recoil';
import {walletState} from '/@/store';

interface IProps {
sessionData: IWalletData;
Expand All @@ -66,9 +70,10 @@ function SendTX(props: IProps) {
const [storedPassphrase, setStoredPassphrase] = useState('');
const {isLedgerEnabled} = useContext<Partial<ILedgerContext>>(LedgerContext);
const {getBalance, setShouldBalanceUpdate} = useContext<Partial<IBalanceContext>>(BalanceContext);
const {wallet} = useWallet();
// const {wallet} = useWallet();
const wallet = useRecoilValue(walletState);
const senderAddress = wallet.address;
const balance = getBalance && getBalance(senderAddress);
const balance = getBalance && getBalance(wallet.address);
const {
data: nonceData,
refetch: nonceRefetch,
Expand All @@ -79,6 +84,7 @@ function SendTX(props: IProps) {
skip: !senderAddress,
fetchPolicy: 'network-only',
});
const [fetchBalance] = useLazyQuery<IBalanceQueryResult>(GET_BALANCE);
useEffect(() => {
getPassphrase().then(passphrase => {
setStoredPassphrase(passphrase);
Expand Down Expand Up @@ -195,7 +201,7 @@ function SendTX(props: IProps) {
* Check if nonce is available, if not ask the user for a custom nonce.
* After the nonce is set, proceed with transaction data verification and Passphrase/Private key verification
*/
const openConfirmationModal = () => {
const openConfirmationModal = async () => {
if (nonceLoading) {
setWaitingNonce(true);
return;
Expand All @@ -204,10 +210,16 @@ function SendTX(props: IProps) {
if (!nonceData && !customNonce) {
return setShowModal(ModalStates.NONCE);
}
checkBalanceAfterTransaction({balance, transactionData});
checkTransactionFields(transactionData);
setStep(SendTXPageSteps.PRIVATE_KEY);
setShowModal('');
if (getBalance) {
const {data} = await fetchBalance({variables: {publicKey: wallet.address}});
checkBalanceAfterTransaction({
balance: data?.accountByKey?.balance,
transactionData,
});
checkTransactionFields(transactionData);
setStep(SendTXPageSteps.PRIVATE_KEY);
setShowModal('');
}
} catch (e) {
toast.error(e.message);
}
Expand All @@ -222,7 +234,10 @@ function SendTX(props: IProps) {
throw new Error();
}
setShowModal('');
const derivedData = await deriveAccount(passphrase || privateKey, wallet.accountNumber);
const derivedData = await deriveAccount(
passphrase?.trim() || privateKey.trim(),
wallet.accountNumber,
);
setTransactionData({
...transactionData,
senderAddress: derivedData.publicKey || '',
Expand Down Expand Up @@ -311,7 +326,10 @@ function SendTX(props: IProps) {
}
try {
const actualNonce = getNonce();
const derivedData = await deriveAccount(key.privateKey || privateKey, wallet.accountNumber);
const derivedData = await deriveAccount(
key.privateKey.trim() || privateKey.trim(),
wallet.accountNumber,
);
setTransactionData({
...transactionData,
senderAddress: derivedData.publicKey || '',
Expand All @@ -320,11 +338,13 @@ function SendTX(props: IProps) {
privateKey: derivedData?.privateKey,
publicKey: derivedData?.publicKey,
} as IKeypair;
const signedPayment = await signTransaction({
transactionData,
keypair,
sender: derivedData?.publicKey || senderAddress,
actualNonce,
const signedPayment = await signTransaction(keypair.privateKey, {
...transactionData,
from: derivedData?.publicKey || senderAddress,
to: transactionData.receiverAddress,
nonce: actualNonce,
fee: transactionData.fee,
amoun: transactionData.amount,
});

if (signedPayment) {
Expand Down
13 changes: 7 additions & 6 deletions packages/renderer/src/pages/stake/Stake.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ import {IFeeQuery} from '/@/types/Fee';
import {INonceDelegateQueryResult} from './StakeTypes';
import {IKeypair} from '/@/types';
import WaitingLedger from '/@/components/UI/modals/WaitingLedger';
import {useWallet} from '/@/contexts/WalletContext';
import {useRecoilValue} from 'recoil';
import {walletState} from '/@/store';

interface IProps {
sessionData: IWalletData;
Expand All @@ -71,8 +72,8 @@ const Stake = ({sessionData}: IProps) => {
const [sendTransactionFlag, setSendTransactionFlag] = useState<boolean>(false);
const {isLedgerEnabled} = useContext<Partial<ILedgerContext>>(LedgerContext);
const {getBalance, setShouldBalanceUpdate} = useContext<Partial<IBalanceContext>>(BalanceContext);
const {wallet} = useWallet();
const {address} = wallet;
const {address, accountNumber} = useRecoilValue(walletState);

const balance = getBalance && getBalance(address);
const {
data: validatorsData,
Expand Down Expand Up @@ -329,22 +330,22 @@ const Stake = ({sessionData}: IProps) => {
}
checkBalance(selectedFee, balance);
const actualNonce = getNonce();
const derivedAccount = await deriveAccount(passphrase || privateKey, wallet.accountNumber);
const derivedAccount = await deriveAccount(passphrase?.trim() || privateKey.trim(), accountNumber);
const keypair = {
privateKey: derivedAccount.privateKey,
publicKey: derivedAccount.publicKey,
} as IKeypair;
const stakeDelegation = {
to: delegateData.publicKey,
from: address,
from: address || keypair.publicKey,
fee: selectedFee,
nonce: actualNonce,
};
const signedTransaction = (await client()).signStakeDelegation(
stakeDelegation,
keypair.privateKey,
);
(await client()).verifyStakeDelegation(signedTransaction);
const verify = (await client()).verifyStakeDelegation(signedTransaction);
if (signedTransaction) {
const signatureInput = createSignatureInputFromSignature(signedTransaction.signature);
const sendPaymentInput = createDelegationPaymentInputFromPayload(signedTransaction.data);
Expand Down
Loading

0 comments on commit 0a2c47b

Please sign in to comment.