Skip to content

Commit

Permalink
Update get balance for account
Browse files Browse the repository at this point in the history
  • Loading branch information
Thiendekaco committed Feb 29, 2024
1 parent c2b336c commit 871dc6f
Show file tree
Hide file tree
Showing 9 changed files with 148 additions and 70 deletions.
46 changes: 31 additions & 15 deletions packages/demo/src/components/account/AccountList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import { substrateApi } from "../../utils/api/substrateApi";
import {toShort} from "../../utils/style";
import TransactionModal from "../transaction/TransactionModal";
import styled from "styled-components";
import {useNavigate} from "react-router-dom";
import {TRANSACTION_MODAL} from "../../constants/modal";



Expand All @@ -32,11 +34,13 @@ type AccountMapType = {
}



const modalId = TRANSACTION_MODAL;
function Component ({className, substrateProvider, evmProvider}: Props): React.ReactElement {
const [{ wallet},] = useConnectWallet();
const renderEmpty = useCallback(() => <GeneralEmptyList />, []);
const [ accountsMap, setAccountMap ] = useState<AccountMapType[]>([])
const navigate = useNavigate();
const [ accountTransaction, setAccountTransaction ] = useState<Account>();
const [{ chains }] = useSetChain();
const [, customNotification, updateNotify,] = useNotifications();
const { activeModal } = useContext(ModalContext);
Expand Down Expand Up @@ -79,15 +83,19 @@ function Component ({className, substrateProvider, evmProvider}: Props): React.R
);

const onTransactionClicked = useCallback(
(address_: string) => {
(address: string) => {
return async () => {
activeModal(`${address_}`);
const account = wallet?.accounts.find(({address: address_}) => address === address_);
setAccountTransaction(account)
account && activeModal(modalId);
};
}, [wallet])
}, [activeModal, wallet])




useEffect(() => {

const accountMap = wallet?.accounts.reduce((acc, account, index)=>{
acc.push({address: account.address, index, name: account.uns?.name || account.ens?.name || toShort(account.address)})
return acc
Expand Down Expand Up @@ -128,30 +136,38 @@ function Component ({className, substrateProvider, evmProvider}: Props): React.R
</div>
)

const account = wallet?.accounts.find(({address: address_}) => address === address_)
return(
<>
<Web3Block
key={key}
className={'__account-item'}
middleItem={_middleItem}
/>
{account && <TransactionModal senderAccount={account}
substrateProvider={substrateProvider}
evmProvider={evmProvider}/>}
</>

)
}, [wallet?.accounts, onSignClicked, onTransactionClicked, substrateProvider, evmProvider])
}, [onSignClicked, onTransactionClicked])


return (
<SwList
className={CN('__account-list', className)}
list={accountsMap}
renderWhenEmpty={renderEmpty}
renderItem={accountItem}
/>
<>
{
accountsMap.length > 0 &&
<>
<SwList
className={CN('__account-list', className)}
list={accountsMap}
renderWhenEmpty={renderEmpty}
renderItem={accountItem}
/>
{
accountTransaction && <TransactionModal senderAccount={accountTransaction} substrateProvider={substrateProvider} evmProvider={evmProvider} />
}
</>

}
</>

);
}

Expand Down
4 changes: 2 additions & 2 deletions packages/demo/src/components/layout/WalletHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ function Component ({ visible, className }: Props): React.ReactElement<Props> {
try {
await set({ chainId: network.id, chainNamespace: network.namespace })
}catch (e) {

console.log(e)
}
}
}
Expand Down Expand Up @@ -94,7 +94,7 @@ function Component ({ visible, className }: Props): React.ReactElement<Props> {
modalId={modalId}
onSelectItem={onSwitchNetwork}
/>
<SelectAccount />
{wallet?.accounts && wallet.accounts.length > 0 && <SelectAccount/>}

</div>
</>:
Expand Down
110 changes: 80 additions & 30 deletions packages/demo/src/components/transaction/TransactionModal.tsx
Original file line number Diff line number Diff line change
@@ -1,45 +1,79 @@
import { ThemeProps, TransferParams, FormCallbacks, Theme } from "../../types";
import {TRANSACTION_MODAL} from "../../constants/modal";
import { BaseModal} from "../modal";
import { Button, Form, Icon, Input, ModalContext } from '@subwallet/react-ui';
import { Button, Form, Icon, Input, ModalContext, Number, ActivityIndicator } from '@subwallet/react-ui';
import { useState, useCallback, useMemo, useEffect, useContext } from "react";
import { useConnectWallet, useNotifications, useSetChain } from "@subwallet_connect/react";
import { Rule } from '@subwallet/react-ui/es/form';
import { useWatchTransaction } from "../../hooks";
import styled from 'styled-components';
import styled, {useTheme} from 'styled-components';
import BigN from 'bignumber.js';
import { isAddress, isEthereumAddress } from '@polkadot/util-crypto';
import CN from "classnames";
import AccountBriefInfo from "../account/AccountBriefInfo";
import type { Account } from '@subwallet_connect/core/dist/types';
import { PaperPlaneTilt } from "@phosphor-icons/react";
import { NetworkInfo } from "../../utils/network";
import {EIP1193Provider, SubstrateProvider} from "@subwallet_connect/common";
import { EIP1193Provider, SubstrateProvider } from "@subwallet_connect/common";
import { substrateApi } from "../../utils/api/substrateApi";
import { evmApi } from "../../utils/api/evmApi";
import BN from "bn.js";
import {BN_ZERO} from "@polkadot/util";

export interface Props extends ThemeProps {
senderAccount: Account;
substrateProvider ?: substrateApi,
evmProvider ?: evmApi,
};



export interface TypeFreeBalance {
value: string,
symbol: string,
decimals: number
}
const DEFAULT_ADDRESS = '5GnUABVD7kt1wnmLiSeGcuSd5ESvmVnAjdMRrtvKxUGxuy6N'
const modalId = TRANSACTION_MODAL;
function Component ({ className, senderAccount, evmProvider, substrateProvider }: Props) {
const [{ wallet},] = useConnectWallet();
const [{ chains }] = useSetChain();
const modalId = useMemo(() => `${senderAccount.address}`, [senderAccount.address, wallet])
const [loading, setLoading] = useState(false);
const [, customNotification, updateNotify,] = useNotifications();
const [ availableBalance, setAvailableBalance ] = useState<TypeFreeBalance>()
const [ onReadyFreeBalance, setOnReadyFreeBalance ] = useState(false);
const [ validatePass, setValidatePass ] = useState<{ to: boolean, amount: boolean}>({ to: false, amount: false })
const [ defaultData, persistData ] = useState<TransferParams>({
const defaultData = useMemo((): TransferParams => {
return ({
from: senderAccount.address,
to: '',
value: ''
}
);
const { inactiveModal } = useContext(ModalContext);
})
}, [senderAccount])
const { token } = useTheme() as Theme;
const { inactiveModal, checkActive } = useContext(ModalContext);

const getMaxTransfer = useCallback(async () => {
if(!wallet) return ;
setOnReadyFreeBalance(false);
substrateProvider && await substrateProvider.isReady();

const { namespace: namespace_, id: chainId } = wallet.chains[0]
const chainInfo = chains.find(({id, namespace}) => id === chainId && namespace === namespace_);
const maxTransfer = (await (substrateProvider || evmProvider)?.getMaxTransfer( '0', senderAccount.address, DEFAULT_ADDRESS)) || '0';
const maxTransferBN = new BN(maxTransfer);
setAvailableBalance(
{
symbol: chainInfo?.token || ( wallet.type === 'evm' ? 'ETH' : 'DOT') ,
value: maxTransferBN.gt(BN_ZERO) ? maxTransfer : '0',
decimals: chainInfo?.decimal || ( wallet.type === 'evm' ? 18 : 10)
}
)
setOnReadyFreeBalance(true);

}, [ wallet?.chains[0], substrateProvider, evmProvider, senderAccount.address])

useEffect(() => {
checkActive(modalId) && getMaxTransfer().then(r => {});
}, [checkActive(modalId), wallet?.chains[0].id, senderAccount.address]);



Expand All @@ -50,13 +84,6 @@ function Component ({ className, senderAccount, evmProvider, substrateProvider }
const transferAmount = useWatchTransaction('value', form, defaultData);
const to = useWatchTransaction('to', form, defaultData);

useEffect(() => {
persistData({
from: senderAccount.address,
to: '',
value: ''
})
}, [senderAccount]);

const validateRecipientAddress = useCallback(async (rule: Rule, _recipientAddress: string): Promise<void> => {

Expand Down Expand Up @@ -141,8 +168,14 @@ function Component ({ className, senderAccount, evmProvider, substrateProvider }


const onCloseModal = useCallback(() => {
inactiveModal(modalId)
}, [modalId, inactiveModal])
setAvailableBalance(undefined);
inactiveModal(modalId);
form.resetFields(['to', 'value']);
}, [ inactiveModal, form])

const onValueChange = useCallback(() => {

}, [])



Expand All @@ -164,17 +197,6 @@ function Component ({ className, senderAccount, evmProvider, substrateProvider }
if(wallet?.type === "evm"){
blockHash = await evmProvider?.sendTransaction(senderAccount.address, to, amount ) || ''
}else{
const ws = NetworkInfo[chainInfo.label as string].wsProvider;
if(! ws) {
const {} = customNotification({
type: 'error',
message:
'This network is not provide api',
autoDismiss: 2000
})

return ;
}

const getSigner = async ()=>{
const provider = wallet.provider as SubstrateProvider;
Expand Down Expand Up @@ -245,6 +267,7 @@ function Component ({ className, senderAccount, evmProvider, substrateProvider }
id={modalId}
title={'Transaction'}
closable={true}
maskClosable={false}
onCancel={onCloseModal}
className={CN(className, 'transaction-modal')}
fullSizeOnMobile={true}
Expand All @@ -253,6 +276,7 @@ function Component ({ className, senderAccount, evmProvider, substrateProvider }
<Form
className={'form-container form-space-sm'}
form={form}
onValuesChange={onValueChange}
onFinish={onSubmit}
initialValues={formDefault}
>
Expand Down Expand Up @@ -307,6 +331,23 @@ function Component ({ className, senderAccount, evmProvider, substrateProvider }
suffix={suffixAmountInput}
/>
</Form.Item>

<div className={'__balance-transferable-item'}>
<span className='__label-balance-transferable'>Sender available balance:</span>
{
availableBalance && onReadyFreeBalance?
<Number
decimal={availableBalance.decimals}
decimalColor={token.colorTextTertiary}
intColor={token.colorTextTertiary}
size={14}
suffix={availableBalance.symbol}
unitColor={token.colorTextTertiary}
value={availableBalance.value}
/> :
<ActivityIndicator size={14} />
}
</div>
</Form>
</div>
<div className={'__transaction-footer'}>
Expand Down Expand Up @@ -397,6 +438,15 @@ const TransactionModal = styled(Component)(({ theme: {token} }) => {

'.__amount-transfer-input': {
'-moz-appearance': 'textfield'
},
'.__balance-transferable-item': {
display: 'flex',
flexWrap: 'wrap',
color: token.colorTextTertiary,

'.__label-balance-transferable': {
marginRight: 3
},
}

});
Expand Down
11 changes: 6 additions & 5 deletions packages/demo/src/pages/EvmWalletInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@ interface Props extends ThemeProps{};


function Component ({className}: Props): React.ReactElement {
const [{ wallet, connecting},connect,, updateBalance] = useConnectWallet();
const [{ wallet},,disconnect] = useConnectWallet();
const [{ chains}, setChain] = useSetChain();
const navigate = useNavigate();
const [ evmProvider, setEvmProvider ] = useState<evmApi>();
const [ listendAccountChanged, setListendAccounChanged ] = useState(false);
const customNotification = useNotifications()[1];
const { isWebUI } = useContext(ScreenContext);

Expand All @@ -36,11 +37,11 @@ function Component ({className}: Props): React.ReactElement {
if(!wallet) return;
setEvmProvider(new evmApi(wallet.provider as EIP1193Provider));
wallet.provider.on('accountsChanged', (accounts) => {
if(accounts.length === 0){
navigate("/welcome");
if(!accounts || accounts.length === 0 ){
disconnect({ label: wallet.label, type: wallet.type })
}
})
}, [wallet]);
}, [wallet, navigate]);


const requestPermission = useCallback(async ()=> {
Expand Down Expand Up @@ -79,7 +80,7 @@ function Component ({className}: Props): React.ReactElement {
<div className={'__evm-wallet-info-label'}>
Account List
</div>
<AccountList evmProvider={evmProvider}/>
{wallet?.accounts && wallet.accounts.length > 0 && <AccountList evmProvider={evmProvider}/>}
</div>
<div className={'__evm-wallet-info-box'}>
<div className={'__evm-wallet-info-label'}>Permission</div>
Expand Down
16 changes: 8 additions & 8 deletions packages/demo/src/pages/WalletInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ interface Props extends ThemeProps {};

function Component ({className}: Props): React.ReactElement {
const navigate = useNavigate();
const [ { wallet}] = useConnectWallet();
const [ { wallet},, disconnect] = useConnectWallet();
const [ substrateProvider, setSubstrateProvider ] = useState<substrateApi>();
const [{ chains }] = useSetChain();
const { isWebUI } = useContext(ScreenContext);
Expand All @@ -37,12 +37,12 @@ function Component ({className}: Props): React.ReactElement {
}
}

wallet.provider.on('accountsChanged', (accounts) => {
if(accounts.length === 0){
navigate("/welcome");
}
})
}, [wallet]);
wallet.provider.on('accountsChanged', (accounts) => {
if(!accounts || accounts.length === 0 ){
disconnect({ label: wallet.label, type: wallet.type })
}
})
}, [wallet, navigate]);

return (
<div className={CN('__wallet-info-page', className, {
Expand All @@ -53,7 +53,7 @@ function Component ({className}: Props): React.ReactElement {
<div className={'__wallet-info-label'}>
Account List
</div>
<AccountList substrateProvider={substrateProvider}/>
{wallet?.accounts && wallet.accounts.length > 0 && <AccountList substrateProvider={substrateProvider}/>}
</div>
<div className={'__wallet-info-box'}>
{!! wallet?.metadata &&
Expand Down
4 changes: 2 additions & 2 deletions packages/demo/src/pages/Welcome.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ function Component ({ className }: Props): React.ReactElement {
const [{ wallet }, connect] = useConnectWallet()
const { token } = useTheme() as Theme;
useEffect(() => {
if (wallet?.type === 'substrate') {
if (wallet?.type === 'substrate' && wallet.accounts.length > 0) {
navigate('/wallet-info');
} else if(wallet?.type === 'evm' ){
} else if(wallet?.type === 'evm' && wallet.accounts.length > 0 ){
navigate('/evm-wallet-info');
}
}, [wallet]);
Expand Down
Loading

0 comments on commit 871dc6f

Please sign in to comment.