Convert transfer to functional (#1735)

* Convert transfer to functional

* Cleanup extra amount addition

* Cleanup unused
This commit is contained in:
Jaco Greeff 2019-10-21 12:40:49 +02:00 committed by GitHub
parent 9b2d24bd8a
commit a1bd658ee0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 126 additions and 197 deletions

View File

@ -4,218 +4,157 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { SubmittableExtrinsic } from '@polkadot/api/promise/types';
import { Index } from '@polkadot/types/interfaces';
import { ApiProps } from '@polkadot/react-api/types';
import { DerivedFees } from '@polkadot/api-derive/types';
import { I18nProps } from '@polkadot/react-components/types';
import BN from 'bn.js';
import React from 'react';
import React, { useContext, useEffect, useState } from 'react';
import styled from 'styled-components';
import { Button, InputAddress, InputBalance, Modal, TxButton } from '@polkadot/react-components';
import { Available } from '@polkadot/react-query';
import Checks, { calcTxLength } from '@polkadot/react-signer/Checks';
import { withApi, withCalls, withMulti } from '@polkadot/react-api';
import { ZERO_FEES } from '@polkadot/react-signer/Checks/constants';
import { bnMax } from '@polkadot/util';
import Checks from '@polkadot/react-signer/Checks';
import { ApiContext } from '@polkadot/react-api';
import translate from '../translate';
interface Props extends ApiProps, I18nProps {
interface Props extends I18nProps {
balances_fees?: DerivedFees;
className?: string;
onClose: () => void;
recipientId?: string;
senderId?: string;
system_accountNonce?: BN;
}
interface State {
amount: BN;
extrinsic: SubmittableExtrinsic | null;
hasAvailable: boolean;
maxBalance?: BN;
recipientId?: string | null;
senderId?: string | null;
}
const ZERO = new BN(0);
class Transfer extends React.PureComponent<Props, State> {
public state: State;
// TODO Re-enable when we have proper fee calculation (incl. weights)
// async function calcMax (api: ApiPromise, balances_fees: DerivedFees | undefined, senderId: string, recipientId: string): Promise<BN> {
// let maxBalance = new BN(1);
public constructor (props: Props) {
super(props);
// if (!balances_fees) {
// return maxBalance;
// }
this.state = {
amount: ZERO,
extrinsic: null,
hasAvailable: true,
maxBalance: ZERO,
recipientId: props.recipientId || null,
senderId: props.senderId || null
};
}
// const { transferFee, transactionBaseFee, transactionByteFee, creationFee } = balances_fees;
public componentDidUpdate (prevProps: Props, prevState: State): void {
const { balances_fees } = this.props;
const { extrinsic, recipientId, senderId } = this.state;
const hasLengthChanged = ((extrinsic && extrinsic.encodedLength) || 0) !== ((prevState.extrinsic && prevState.extrinsic.encodedLength) || 0);
// const [senderNonce, senderBalances, recipientBalances] = await Promise.all([
// api.query.system.accountNonce<Index>(senderId),
// api.derive.balances.all(senderId),
// api.derive.balances.all(recipientId)
// ]);
if ((recipientId && prevState.recipientId !== recipientId) ||
(balances_fees !== prevProps.balances_fees) || (prevState.senderId !== senderId) ||
hasLengthChanged
) {
this.setMaxBalance().catch((error: Error): void => console.error(error));
// let prevMax = new BN(0);
// // something goes screwy here when we move this out of the component :(
// let extrinsic: any;
// while (!prevMax.eq(maxBalance)) {
// prevMax = maxBalance;
// extrinsic = api.tx.balances.transfer(senderNonce, prevMax);
// const txLength = calcTxLength(extrinsic, senderNonce);
// const fees = transactionBaseFee
// .add(transactionByteFee.mul(txLength))
// .add(transferFee)
// .add(recipientBalances.availableBalance.isZero() ? creationFee : ZERO);
// maxBalance = bnMax(senderBalances.availableBalance.sub(fees), ZERO);
// }
// return maxBalance;
// }
function Transfer ({ className, onClose, recipientId: propRecipientId, senderId: propSenderId, t }: Props): React.ReactElement<Props> {
const { api } = useContext(ApiContext);
const [amount, setAmount] = useState<BN | undefined>(new BN(0));
const [extrinsic, setExtrinsic] = useState<SubmittableExtrinsic | null>(null);
const [hasAvailable, setHasAvailable] = useState(true);
const [maxBalance] = useState(new BN(0));
const [recipientId, setRecipientId] = useState<string | null>(propRecipientId || null);
const [senderId, setSenderId] = useState<string | null>(propSenderId || null);
useEffect((): void => {
if (senderId && recipientId) {
setExtrinsic(api.tx.balances.transfer(recipientId, amount || ZERO));
// We currently have not enabled the max functionality - we don't take care of weights
// calcMax(api, balances_fees, senderId, recipientId)
// .then(([maxBalance]): void => setMaxBalance(maxBalance))
// .catch((error: Error): void => console.error(error));
}
}
}, [amount, recipientId, senderId]);
public render (): React.ReactNode {
const { className, onClose, recipientId: propRecipientId, senderId: propSenderId, t } = this.props;
const { extrinsic, hasAvailable, maxBalance, recipientId, senderId } = this.state;
const available = <span className='label'>{t('available ')}</span>;
const available = <span className='label'>{t('available ')}</span>;
return (
<Modal
className='app--accounts-Modal'
dimmer='inverted'
open
>
<Modal.Header>{t('Send funds')}</Modal.Header>
<Modal.Content>
<div className={className}>
<InputAddress
defaultValue={propSenderId}
help={t('The account you will send funds from.')}
isDisabled={!!propSenderId}
label={t('send from account')}
labelExtra={<Available label={available} params={senderId} />}
onChange={this.onChangeFrom}
type='account'
/>
<InputAddress
defaultValue={propRecipientId}
help={t('Select a contact or paste the address you want to send funds to.')}
isDisabled={!!propRecipientId}
label={t('send to address')}
labelExtra={<Available label={available} params={recipientId} />}
onChange={this.onChangeTo}
type='allPlus'
/>
<InputBalance
help={t('Type the amount you want to transfer. Note that you can select the unit on the right e.g sending 1 milli is equivalent to sending 0.001.')}
isError={!hasAvailable}
label={t('amount')}
maxValue={maxBalance}
onChange={this.onChangeAmount}
withMax
/>
<Checks
accountId={senderId}
extrinsic={extrinsic}
isSendable
onChange={this.onChangeFees}
/>
</div>
</Modal.Content>
<Modal.Actions>
<Button.Group>
<Button
icon='cancel'
isNegative
label={t('Cancel')}
onClick={onClose}
/>
<Button.Or />
<TxButton
accountId={senderId}
extrinsic={extrinsic}
icon='send'
isDisabled={!hasAvailable}
isPrimary
label={t('Make Transfer')}
onStart={onClose}
withSpinner={false}
/>
</Button.Group>
</Modal.Actions>
</Modal>
);
}
private nextState (newState: Partial<State>): void {
this.setState((prevState: State): State => {
const { api } = this.props;
const { amount = prevState.amount, recipientId = prevState.recipientId, hasAvailable = prevState.hasAvailable, maxBalance = prevState.maxBalance, senderId = prevState.senderId } = newState;
const extrinsic = recipientId && senderId
? api.tx.balances.transfer(recipientId, amount)
: null;
return {
amount,
extrinsic,
hasAvailable,
maxBalance,
recipientId,
senderId
};
});
}
private onChangeAmount = (amount: BN = new BN(0)): void => {
this.nextState({ amount });
}
private onChangeFrom = (senderId: string | null): void => {
this.nextState({ senderId });
}
private onChangeTo = (recipientId: string | null): void => {
this.nextState({ recipientId });
}
private onChangeFees = (hasAvailable: boolean): void => {
this.setState({ hasAvailable });
}
private setMaxBalance = async (): Promise<void> => {
const { api, balances_fees = ZERO_FEES } = this.props;
const { senderId, recipientId } = this.state;
if (!senderId || !recipientId) {
return;
}
const { transferFee, transactionBaseFee, transactionByteFee, creationFee } = balances_fees;
const accountNonce = await api.query.system.accountNonce<Index>(senderId);
const senderBalance = (await api.derive.balances.all(senderId)).availableBalance;
const recipientBalance = (await api.derive.balances.all(recipientId)).availableBalance;
let prevMax = new BN(0);
let maxBalance = new BN(1);
let extrinsic;
while (!prevMax.eq(maxBalance)) {
prevMax = maxBalance;
extrinsic = api.tx.balances.transfer(recipientId, prevMax);
const txLength = calcTxLength(extrinsic, accountNonce);
const fees = transactionBaseFee
.add(transactionByteFee.mul(txLength))
.add(transferFee)
.add(recipientBalance.isZero() ? creationFee : ZERO);
maxBalance = bnMax(senderBalance.sub(fees), ZERO);
}
this.nextState({
extrinsic,
maxBalance
});
}
return (
<Modal
className='app--accounts-Modal'
dimmer='inverted'
open
>
<Modal.Header>{t('Send funds')}</Modal.Header>
<Modal.Content>
<div className={className}>
<InputAddress
defaultValue={propSenderId}
help={t('The account you will send funds from.')}
isDisabled={!!propSenderId}
label={t('send from account')}
labelExtra={<Available label={available} params={senderId} />}
onChange={setSenderId}
type='account'
/>
<InputAddress
defaultValue={propRecipientId}
help={t('Select a contact or paste the address you want to send funds to.')}
isDisabled={!!propRecipientId}
label={t('send to address')}
labelExtra={<Available label={available} params={recipientId} />}
onChange={setRecipientId}
type='allPlus'
/>
<InputBalance
help={t('Type the amount you want to transfer. Note that you can select the unit on the right e.g sending 1 milli is equivalent to sending 0.001.')}
isError={!hasAvailable}
label={t('amount')}
maxValue={maxBalance}
onChange={setAmount}
withMax
/>
<Checks
accountId={senderId}
extrinsic={extrinsic}
isSendable
onChange={setHasAvailable}
/>
</div>
</Modal.Content>
<Modal.Actions>
<Button.Group>
<Button
icon='cancel'
isNegative
label={t('Cancel')}
onClick={onClose}
/>
<Button.Or />
<TxButton
accountId={senderId}
extrinsic={extrinsic}
icon='send'
isDisabled={!hasAvailable}
isPrimary
label={t('Make Transfer')}
onStart={onClose}
withSpinner={false}
/>
</Button.Group>
</Modal.Actions>
</Modal>
);
}
export default withMulti(
export default translate(
styled(Transfer)`
article.padded {
box-shadow: none;
@ -235,10 +174,5 @@ export default withMulti(
label.with-help {
flex-basis: 10rem;
}
`,
translate,
withApi,
withCalls<Props>(
'derive.balances.fees'
)
`
);

View File

@ -46,7 +46,7 @@ export function Transfer ({ amount, balances_all = ZERO_BALANCE, fees, onChange,
extraFees = extraFees.add(fees.creationFee);
}
const extraAmount = amount instanceof Compact ? amount.toBn() : new BN(amount);
const extraAmount = amount instanceof Compact ? amount.unwrap() : new BN(amount);
const isCreation = balances_all.votingBalance.isZero() && fees.creationFee.gtn(0);
const isNoEffect = extraAmount.add(balances_all.votingBalance).lt(fees.existentialDeposit);
const extraWarn = isCreation || isNoEffect;

View File

@ -114,11 +114,6 @@ export function FeeDisplay ({ accountId, balances_all = ZERO_BALANCE, balances_f
onChange && onChange(hasAvailable);
setExtra({
extraAmount,
extraFees,
extraWarn
});
setState({
allFees,
allTotal,
@ -130,7 +125,7 @@ export function FeeDisplay ({ accountId, balances_all = ZERO_BALANCE, balances_f
isReserved,
overLimit
});
}, [accountId, balances_all, extrinsic, balances_fees, system_accountNonce, tip]);
}, [accountId, balances_all, balances_fees, extra, extrinsic, system_accountNonce, tip]);
if (!accountId) {
return null;