point to take in count

This commit is contained in:
Gala
2023-10-06 22:12:05 +02:00
committed by Lorexia
parent 495f2eb543
commit 7cab3d58a8
6 changed files with 222 additions and 199 deletions
@@ -61,24 +61,20 @@ interface ApiState<RESPONSE> {
*/
interface WalletState {
cosmWasmSigner?: { getAccounts: () => void };
cosmWasmSignerClient?: {
getBalance: (account: string, denom: string) => Coin;
sendTokens: (account: string, recipientAddress: string, amount: [Coin], type: 'auto', memo: string) => void;
};
nymWasmSignerClient?: ApiState<any>;
accountLoading: boolean;
account: string;
clientsAreLoading: boolean;
setConnectWithMnemonic?: (value: string) => void;
connect?: () => void;
connect?: (mnemonic: string) => void;
balance?: Coin;
balanceLoading: boolean;
setRecipientAddress?: (value: string) => void;
setTokensToSend?: (value: string) => void;
sendingTokensLoading: boolean;
log: React.ReactNode[];
doSendTokens?: () => void;
sendTokens?: (recipientAddress: string, tokensToSend: string) => void;
delegations?: any;
unDelegateAll?: () => void;
unDelegateAllLoading?: boolean;
}
export const WalletContext = React.createContext<WalletState>({
@@ -93,28 +89,36 @@ export const WalletContext = React.createContext<WalletState>({
export const useWalletContext = (): React.ContextType<typeof WalletContext> =>
React.useContext<WalletState>(WalletContext);
let cosmWasmSignerClient;
let nymWasmSignerClient;
let account;
export const WalletContextProvider = ({ children }: { children: JSX.Element }) => {
// wallet mnemonic
const [connectWithMnemonic, setConnectWithMnemonic] = React.useState<string>();
const [accountLoading, setAccountLoading] = React.useState<boolean>(false);
const [account, setAccount] = React.useState<string>(null);
const [delegations, setDelegations] = React.useState<any>();
const [clientsAreLoading, setClientsAreLoading] = React.useState<boolean>(false);
const [cosmWasmSignerClient, setCosmWasmSignerClient] = React.useState<any>(null);
const [nymWasmSignerClient, setNymWasmSignerClient] = React.useState<any>(null);
const [balance, setBalance] = React.useState<Coin>(null);
const [balanceLoading, setBalanceLoading] = React.useState<boolean>(false);
const [recipientAddress, setRecipientAddress] = React.useState<string>();
const [tokensToSend, setTokensToSend] = React.useState<string>();
const [sendingTokensLoading, setSendingTokensLoading] = React.useState<boolean>(false);
const [log, setLog] = React.useState<React.ReactNode[]>([]);
const [unDelegateAllLoading, setUnDelegateAllLoading] = React.useState<boolean>(false);
const getSignerAccount = async () => {
const Reset = () => {
setAccountLoading(false);
setClientsAreLoading(false);
setBalance(null);
setBalanceLoading(false);
setSendingTokensLoading(false);
setLog([]);
};
const getSignerAccount = async (mnemonic: string) => {
setAccountLoading(true);
try {
const signer = await signerAccount(connectWithMnemonic);
const signer = await signerAccount(mnemonic);
const accounts = await signer.getAccounts();
if (accounts[0]) {
setAccount(accounts[0].address);
account = accounts[0].address;
}
} catch (error) {
console.error(error);
@@ -122,17 +126,22 @@ export const WalletContextProvider = ({ children }: { children: JSX.Element }) =
setAccountLoading(false);
};
const getClients = async () => {
const getClients = async (mnemonic: string) => {
setClientsAreLoading(true);
try {
setCosmWasmSignerClient(await fetchSignerCosmosWasmClient(connectWithMnemonic));
setNymWasmSignerClient(await fetchSignerClient(connectWithMnemonic));
cosmWasmSignerClient = await fetchSignerCosmosWasmClient(mnemonic);
nymWasmSignerClient = await fetchSignerClient(mnemonic);
} catch (error) {
console.error(error);
}
setClientsAreLoading(false);
};
const connect = React.useCallback(async (mnemonic: string) => {
getSignerAccount(mnemonic);
getClients(mnemonic);
}, []);
const getBalance = React.useCallback(async () => {
setBalanceLoading(true);
try {
@@ -144,40 +153,63 @@ export const WalletContextProvider = ({ children }: { children: JSX.Element }) =
setBalanceLoading(false);
}, [account, cosmWasmSignerClient]);
// Sending tokens
const doSendTokens = React.useCallback(async () => {
const memo = 'test sending tokens';
setSendingTokensLoading(true);
console.log('cosmWasmSignerClient', cosmWasmSignerClient, account, recipientAddress);
const getDelegations = React.useCallback(async () => {
const delegations = await nymWasmSignerClient.getDelegatorDelegations({
delegator: settings.address,
});
console.log('delegations', delegations);
setDelegations(delegations);
}, [nymWasmSignerClient]);
const sendTokens = React.useCallback(
async (recipientAddress: string, tokensToSend: string) => {
const memo = 'test sending tokens';
setSendingTokensLoading(true);
try {
const res = await cosmWasmSignerClient.sendTokens(
account,
recipientAddress,
[{ amount: tokensToSend, denom: 'unym' }],
'auto',
memo,
);
setLog((prev) => [
...prev,
<div key={JSON.stringify(res, null, 2)}>
<code style={{ marginRight: '2rem' }}>{new Date().toLocaleTimeString()}</code>
<pre>{JSON.stringify(res, null, 2)}</pre>
</div>,
]);
} catch (error) {
console.error(error);
}
setSendingTokensLoading(false);
},
[account, cosmWasmSignerClient],
);
const undelegateAll = async () => {
if (!nymWasmSignerClient) {
return;
}
setUnDelegateAllLoading(true);
try {
const res = await cosmWasmSignerClient.sendTokens(
account,
recipientAddress,
[{ amount: tokensToSend, denom: 'unym' }],
'auto',
memo,
);
setLog((prev) => [
...prev,
<div key={JSON.stringify(res, null, 2)}>
<code style={{ marginRight: '2rem' }}>{new Date().toLocaleTimeString()}</code>
<pre>{JSON.stringify(res, null, 2)}</pre>
</div>,
]);
// eslint-disable-next-line no-restricted-syntax
for (const delegation of delegations.delegations) {
// eslint-disable-next-line no-await-in-loop
await nymWasmSignerClient.undelegateFromMixnode({ mixId: delegation.mix_id }, 'auto');
}
} catch (error) {
console.error(error);
}
setSendingTokensLoading(false);
}, [account, cosmWasmSignerClient]);
// End send tokens
setUnDelegateAllLoading(false);
};
React.useEffect(() => {
if (connectWithMnemonic) {
Promise.all([getSignerAccount(), getClients()]);
}
}, [connectWithMnemonic]);
return () => {
Reset();
};
}, []);
React.useEffect(() => {
if (cosmWasmSignerClient) {
@@ -185,36 +217,40 @@ export const WalletContextProvider = ({ children }: { children: JSX.Element }) =
}
}, [cosmWasmSignerClient]);
React.useEffect(() => {
if (nymWasmSignerClient) {
getDelegations();
}
}, [nymWasmSignerClient]);
const state = React.useMemo<WalletState>(
() => ({
accountLoading,
account,
clientsAreLoading,
cosmWasmSignerClient,
nymWasmSignerClient,
setConnectWithMnemonic,
connect,
balance,
balanceLoading,
setRecipientAddress,
setTokensToSend,
sendingTokensLoading,
log,
doSendTokens,
sendTokens,
delegations,
undelegateAll,
unDelegateAllLoading,
}),
[
accountLoading,
account,
clientsAreLoading,
cosmWasmSignerClient,
nymWasmSignerClient,
setConnectWithMnemonic,
connect,
balance,
balanceLoading,
setRecipientAddress,
setTokensToSend,
sendingTokensLoading,
log,
doSendTokens,
sendTokens,
delegations,
undelegateAll,
unDelegateAllLoading,
],
);
+19 -11
View File
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useState, createContext } from 'react';
import React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import { ConnectWallet } from './wallet/connect';
@@ -6,16 +6,24 @@ import { SendTokes } from './wallet/sendTokens';
import { Delegations } from './wallet/delegations';
import { WalletContextProvider } from './context/wallet';
export const Wallet = ({ type }: { type: 'connect' | 'sendTokens' | 'delegations' }) => (
<WalletContextProvider>
export const Wallet = ({ type }: { type: 'connect' | 'sendTokens' | 'delegations' }) => {
return (
<Box padding={3}>
{type === 'connect' && <ConnectWallet />}
{type === 'sendTokens' && <SendTokes />}
{/* {type === 'delegations' && (
<WalletContext.Provider value={WalletContext}>
{type === 'connect' && (
<WalletContextProvider>
<ConnectWallet />
</WalletContextProvider>
)}
{type === 'sendTokens' && (
<WalletContextProvider>
<SendTokes />
</WalletContextProvider>
)}
{type === 'delegations' && (
<WalletContextProvider>
<Delegations />
</WalletContext.Provider>
)} */}
</WalletContextProvider>
)}
{/* {log.length > 0 && (
<Box marginTop={3}>
<Typography variant="h5">Transaction Logs:</Typography>
@@ -23,5 +31,5 @@ export const Wallet = ({ type }: { type: 'connect' | 'sendTokens' | 'delegations
</Box>
)} */}
</Box>
</WalletContextProvider>
);
);
};
@@ -7,8 +7,7 @@ import TextField from '@mui/material/TextField';
import { useWalletContext } from '../context/wallet';
export const ConnectWallet = () => {
const { balance, balanceLoading, accountLoading, setConnectWithMnemonic, account, clientsAreLoading } =
useWalletContext();
const { connect, balance, balanceLoading, accountLoading, account, clientsAreLoading } = useWalletContext();
const [mnemonic, setMnemonic] = useState<string>();
const [connectButtonText, setConnectButtonText] = useState<string>('Connect');
@@ -44,7 +43,7 @@ export const ConnectWallet = () => {
/>
<Button
variant="outlined"
onClick={() => setConnectWithMnemonic(mnemonic)}
onClick={() => connect(mnemonic)}
disabled={!mnemonic || accountLoading || clientsAreLoading || balanceLoading}
>
{connectButtonText}
@@ -1,48 +1,21 @@
import React, { useState } from 'react';
import React, { useEffect, useState } from 'react';
import Button from '@mui/material/Button';
import Paper from '@mui/material/Paper';
import Box from '@mui/material/Box';
import { TableBody, TableCell, TableHead, TableRow, TextField, Typography } from '@mui/material';
import Table from '@mui/material/Table';
import { useWalletContext } from '../context/wallet';
export const Delegations = () => {
const { delegations, unDelegateAllLoading, balanceLoading, accountLoading, account, clientsAreLoading } = useWalletContext();
const [delegationNodeId, setDelegationNodeId] = useState<string>();
const [amountToBeDelegated, setAmountToBeDelegated] = useState<string>();
const [log, setLog] = useState<React.ReactNode[]>([]);
const [delegations, setDelegations] = useState<any>();
const [delegationLoader, setDelegationLoader] = useState<boolean>(false);
const [undeledationLoader, setUndeledationLoader] = useState<boolean>(false);
const [withdrawLoading, setWithdrawLoading] = useState<boolean>(false);
// const [log, setLog] = useState<React.ReactNode[]>([]);
// const [delegations, setDelegations] = useState<any>();
// const [delegationLoader, setDelegationLoader] = useState<boolean>(false);
// const [withdrawLoading, setWithdrawLoading] = useState<boolean>(false);
// const getDelegations = useCallback(async () => {
// const newDelegations = await signerClient.getDelegatorDelegations({
// delegator: settings.address,
// });
// setDelegations(newDelegations);
// }, [signerClient]);
// // Start Undelgate All
// const doUndelegateAll = async () => {
// if (!signerClient) {
// return;
// }
// setUndeledationLoader(true);
// try {
// // eslint-disable-next-line no-restricted-syntax
// for (const delegation of delegations.delegations) {
// // eslint-disable-next-line no-await-in-loop
// await signerClient.undelegateFromMixnode({ mixId: delegation.mix_id }, 'auto');
// }
// } catch (error) {
// console.error(error);
// }
// setUndeledationLoader(false);
// };
// // End Undelgate All
// // Start Delegate
// Start Delegate
// const doDelegate = async ({ mixId, amount }: { mixId: number; amount: number }) => {
// if (!signerClient) {
// return;
@@ -65,9 +38,9 @@ export const Delegations = () => {
// }
// setDelegationLoader(false);
// };
// // End delegate
// End delegate
// // Start Withdraw Rewards
// Start Withdraw Rewards
// const doWithdrawRewards = async () => {
// const delegatorAddress = '';
// const validatorAdress = '';
@@ -87,7 +60,7 @@ export const Delegations = () => {
// }
// setWithdrawLoading(false);
// };
// // End Withdraw Rewards
// End Withdraw Rewards
// useEffect(() => {
// if (signerClient && !delegations) {
@@ -95,88 +68,88 @@ export const Delegations = () => {
// }
// }, [signerClient, getDelegations, delegations]);
// return (
// <Paper style={{ marginTop: '1rem', padding: '1rem' }}>
// <Box padding={3}>
// <Typography variant="h6">Delegations</Typography>
// <Box marginY={3}>
// <Box marginY={3} display="flex" flexDirection="column">
// <Typography marginBottom={3} variant="body1">
// Make a delegation
// </Typography>
// <TextField
// type="text"
// placeholder="Mixnode ID"
// onChange={(e) => setDelegationNodeId(e.target.value)}
// size="small"
// />
// <Box marginTop={3} display="flex" justifyContent="space-between">
// <TextField
// type="text"
// placeholder="Amount"
// onChange={(e) => setAmountToBeDelegated(e.target.value)}
// size="small"
// />
// <Button
// variant="outlined"
// onClick={() =>
// doDelegate({ mixId: parseInt(delegationNodeId, 10), amount: parseInt(amountToBeDelegated, 10) })
// }
// disabled={delegationLoader}
// >
// {delegationLoader ? 'Delegation in process...' : 'Delegate'}
// </Button>
// </Box>
// </Box>
// </Box>
// <Box marginTop={3}>
// <Typography variant="body1">Your delegations</Typography>
// <Box marginBottom={3} display="flex" flexDirection="column">
// {!delegations?.delegations?.length ? (
// <Typography>You do not have delegations</Typography>
// ) : (
// <Box>
// <Table size="small">
// <TableHead>
// <TableRow>
// <TableCell>MixId</TableCell>
// <TableCell>Owner</TableCell>
// <TableCell>Amount</TableCell>
// <TableCell>Cumulative Reward Ratio</TableCell>
// </TableRow>
// </TableHead>
// <TableBody>
// {delegations?.delegations.map((delegation: any) => (
// <TableRow key={delegation.mix_id}>
// <TableCell>{delegation.mix_id}</TableCell>
// <TableCell>{delegation.owner}</TableCell>
// <TableCell>{delegation.amount.amount}</TableCell>
// <TableCell>{delegation.cumulative_reward_ratio}</TableCell>
// </TableRow>
// ))}
// </TableBody>
// </Table>
// </Box>
// )}
// </Box>
// {delegations && (
// <Box marginBottom={3}>
// <Button variant="outlined" onClick={() => doUndelegateAll()} disabled={undeledationLoader}>
// {undeledationLoader ? 'Undelegating...' : 'Undelegate All'}
// </Button>
// </Box>
// )}
// <Box>
// <Button variant="outlined" onClick={() => doWithdrawRewards()} disabled={withdrawLoading}>
// {withdrawLoading ? 'Doing withdraw...' : 'Withdraw rewards'}
// </Button>
// </Box>
// </Box>
// </Box>
// </Paper>
// );
useEffect(() => {
console.log('delegations', delegations);
},[delegations]);
return (
<Box>Hello</Box>
)
<Paper style={{ marginTop: '1rem', padding: '1rem' }}>
<Box padding={3}>
<Typography variant="h6">Delegations</Typography>
<Box marginY={3}>
<Box marginY={3} display="flex" flexDirection="column">
<Typography marginBottom={3} variant="body1">
Make a delegation
</Typography>
<TextField
type="text"
placeholder="Mixnode ID"
onChange={(e) => setDelegationNodeId(e.target.value)}
size="small"
/>
<Box marginTop={3} display="flex" justifyContent="space-between">
<TextField
type="text"
placeholder="Amount"
onChange={(e) => setAmountToBeDelegated(e.target.value)}
size="small"
/>
{/* <Button
variant="outlined"
onClick={() =>
doDelegate({ mixId: parseInt(delegationNodeId, 10), amount: parseInt(amountToBeDelegated, 10) })
}
disabled={delegationLoader}
>
{delegationLoader ? 'Delegation in process...' : 'Delegate'}
</Button> */}
</Box>
</Box>
</Box>
<Box marginTop={3}>
<Typography variant="body1">Your delegations</Typography>
<Box marginBottom={3} display="flex" flexDirection="column">
{!delegations?.delegations?.length ? (
<Typography>You do not have delegations</Typography>
) : (
<Box>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>MixId</TableCell>
<TableCell>Owner</TableCell>
<TableCell>Amount</TableCell>
<TableCell>Cumulative Reward Ratio</TableCell>
</TableRow>
</TableHead>
<TableBody>
{delegations?.delegations.map((delegation: any) => (
<TableRow key={delegation.mix_id}>
<TableCell>{delegation.mix_id}</TableCell>
<TableCell>{delegation.owner}</TableCell>
<TableCell>{delegation.amount.amount}</TableCell>
<TableCell>{delegation.cumulative_reward_ratio}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
)}
</Box>
{delegations && (
<Box marginBottom={3}>
<Button variant="outlined" onClick={() => undelegateAll()} disabled={unDelegateAllLoading}>
{unDelegateAllLoading ? 'Undelegating...' : 'Undelegate All'}
</Button>
</Box>
)}
<Box>
{/* <Button variant="outlined" onClick={() => doWithdrawRewards()} disabled={withdrawLoading}>
{withdrawLoading ? 'Doing withdraw...' : 'Withdraw rewards'}
</Button> */}
</Box>
</Box>
</Box>
</Paper>
);
};
@@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react';
import React from 'react';
import Button from '@mui/material/Button';
import Paper from '@mui/material/Paper';
import Box from '@mui/material/Box';
@@ -7,7 +7,10 @@ import TextField from '@mui/material/TextField';
import { useWalletContext } from '../context/wallet';
export const SendTokes = () => {
const { setRecipientAddress, setTokensToSend, sendingTokensLoading, doSendTokens, log } = useWalletContext();
const { sendingTokensLoading, sendTokens, log } = useWalletContext();
const [recipientAddress, setRecipientAddress] = React.useState<string>();
const [tokensToSend, setTokensToSend] = React.useState<string>();
return (
<Box>
@@ -28,7 +31,11 @@ export const SendTokes = () => {
onChange={(e) => setTokensToSend(e.target.value)}
size="small"
/>
<Button variant="outlined" onClick={() => doSendTokens()} disabled={sendingTokensLoading}>
<Button
variant="outlined"
onClick={() => sendTokens(recipientAddress, tokensToSend)}
disabled={sendingTokensLoading}
>
{sendingTokensLoading ? 'Sending...' : 'Send tokens'}
</Button>
</Box>