Modal conversion, functional non-TxComponent (#2548)

* Modal conversion, functional non-TxComponent

* Fix duration calc
This commit is contained in:
Jaco Greeff 2020-04-11 09:05:00 +02:00 committed by GitHub
parent 48a3d49a0c
commit 52c04fc29d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 230 additions and 366 deletions

View File

@ -2,108 +2,76 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiProps } from '@polkadot/react-api/types';
import { I18nProps } from '@polkadot/react-components/types';
import React, { useState } from 'react';
import { Icon, InputAddress, Modal, TxButton } from '@polkadot/react-components';
import React from 'react';
import { Icon, InputAddress, Modal, TxButton, TxComponent } from '@polkadot/react-components';
import { withApi, withMulti } from '@polkadot/react-api/hoc';
import { useTranslation } from '../../translate';
import InputValidationController from './InputValidationController';
import translate from '../../translate';
import InputValidationController from '../Account/InputValidationController';
interface Props extends ApiProps, I18nProps {
interface Props {
defaultControllerId: string;
isValidating?: boolean;
onClose: () => void;
stashId: string;
}
interface State {
controllerError: string | null;
controllerId: string | null;
function SetControllerAccount ({ defaultControllerId, isValidating, onClose, stashId }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [, setControllerError] = useState<string | null>(null);
const [controllerId, setControllerId] = useState<string | null>(null);
return (
<Modal
className='staking--SetControllerAccount'
header={t('Change controller account')}
size='small'
>
<Modal.Content className='ui--signer-Signer-Content'>
{isValidating && (
<article className='warning'>
<div className='warning'>
<Icon name='warning sign' />
{t('Warning - Changing the controller while validating will modify the associated session account. It is advised to stop validating before changing the controller account.')}
</div>
</article>
)}
<InputAddress
className='medium'
isDisabled
label={t('stash account')}
value={stashId}
/>
<InputAddress
className='medium'
defaultValue={defaultControllerId}
help={t('The controller is the account that will be used to control any nominating or validating actions. Should not match another stash or controller.')}
label={t('controller account')}
onChange={setControllerId}
type='account'
value={controllerId}
/>
<InputValidationController
accountId={stashId}
controllerId={controllerId}
defaultController={defaultControllerId}
onError={setControllerError}
/>
</Modal.Content>
<Modal.Actions onCancel={onClose}>
<TxButton
accountId={stashId}
icon='sign-in'
isDisabled={!controllerId}
isPrimary
label={t('Set controller')}
onStart={onClose}
params={[controllerId]}
tx='staking.setController'
withSpinner={false}
/>
</Modal.Actions>
</Modal>
);
}
class SetControllerAccount extends TxComponent<Props, State> {
constructor (props: Props) {
super(props);
this.state = {
controllerError: null,
controllerId: null
};
}
public render (): React.ReactNode {
const { defaultControllerId, isValidating, onClose, stashId, t } = this.props;
const { controllerId } = this.state;
const canSubmit = !!controllerId;
return (
<Modal
className='staking--SetControllerAccount'
header={t('Change controller account')}
size='small'
>
<Modal.Content className='ui--signer-Signer-Content'>
{isValidating && (
<article className='warning'>
<div className='warning'>
<Icon name='warning sign' />
{t('Warning - Changing the controller while validating will modify the associated session account. It is advised to stop validating before changing the controller account.')}
</div>
</article>
)}
<InputAddress
className='medium'
isDisabled
label={t('stash account')}
value={stashId}
/>
<InputAddress
className='medium'
defaultValue={defaultControllerId}
help={t('The controller is the account that will be used to control any nominating or validating actions. Should not match another stash or controller.')}
label={t('controller account')}
onChange={this.onChangeController}
type='account'
value={controllerId}
/>
<InputValidationController
accountId={stashId}
controllerId={controllerId}
defaultController={defaultControllerId}
onError={this.onControllerError}
/>
</Modal.Content>
<Modal.Actions onCancel={onClose}>
<TxButton
accountId={stashId}
icon='sign-in'
isDisabled={!canSubmit}
isPrimary
label={t('Set controller')}
onStart={onClose}
params={[controllerId]}
tx='staking.setController'
withSpinner
/>
</Modal.Actions>
</Modal>
);
}
private onChangeController = (controllerId: string | null): void => {
this.setState({ controllerId });
}
private onControllerError = (controllerError: string | null): void => {
this.setState({ controllerError });
}
}
export default withMulti(
SetControllerAccount,
translate,
withApi
);
export default React.memo(SetControllerAccount);

View File

@ -2,68 +2,28 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { I18nProps } from '@polkadot/react-components/types';
import React, { useState } from 'react';
import { Dropdown, InputAddress, Modal, TxButton } from '@polkadot/react-components';
import React from 'react';
import { Dropdown, InputAddress, Modal, TxButton, TxComponent } from '@polkadot/react-components';
import { withMulti } from '@polkadot/react-api/hoc';
import translate from '../../translate';
import { useTranslation } from '../../translate';
import { rewardDestinationOptions } from '../constants';
interface Props extends I18nProps {
interface Props {
defaultDestination?: number;
controllerId: string;
onClose: () => void;
}
interface State {
destination: number;
}
function SetRewardDestination ({ controllerId, defaultDestination, onClose }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [destination, setDestination] = useState(0);
class SetRewardDestination extends TxComponent<Props, State> {
constructor (props: Props) {
super(props);
this.state = {
destination: 0
};
}
public render (): React.ReactNode {
const { controllerId, onClose, t } = this.props;
const { destination } = this.state;
const canSubmit = !!controllerId;
return (
<Modal
className='staking--Bonding'
header={t('Bonding Preferences')}
size='small'
>
{this.renderContent()}
<Modal.Actions onCancel={onClose}>
<TxButton
accountId={controllerId}
icon='sign-in'
isDisabled={!canSubmit}
isPrimary
label={t('Set reward destination')}
onStart={onClose}
params={[destination]}
tx={'staking.setPayee'}
withSpinner
/>
</Modal.Actions>
</Modal>
);
}
private renderContent (): React.ReactNode {
const { controllerId, defaultDestination, t } = this.props;
const { destination } = this.state;
return (
return (
<Modal
className='staking--Bonding'
header={t('Bonding Preferences')}
size='small'
>
<Modal.Content className='ui--signer-Signer-Content'>
<InputAddress
className='medium'
@ -77,20 +37,26 @@ class SetRewardDestination extends TxComponent<Props, State> {
defaultValue={defaultDestination}
help={t('The destination account for any payments as either a nominator or validator')}
label={t('payment destination')}
onChange={this.onChangeDestination}
onChange={setDestination}
options={rewardDestinationOptions}
value={destination}
/>
</Modal.Content>
);
}
private onChangeDestination = (destination: number): void => {
this.setState({ destination });
}
<Modal.Actions onCancel={onClose}>
<TxButton
accountId={controllerId}
icon='sign-in'
isDisabled={!controllerId}
isPrimary
label={t('Set reward destination')}
onStart={onClose}
params={[destination]}
tx={'staking.setPayee'}
withSpinner={false}
/>
</Modal.Actions>
</Modal>
);
}
export default withMulti(
SetRewardDestination,
translate
);
export default React.memo(SetRewardDestination);

View File

@ -2,93 +2,39 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
/* eslint-disable @typescript-eslint/camelcase */
import { AccountId, StakingLedger } from '@polkadot/types/interfaces';
import { I18nProps } from '@polkadot/react-components/types';
import { ApiProps } from '@polkadot/react-api/types';
import BN from 'bn.js';
import React from 'react';
import React, { useState } from 'react';
import { Trans } from 'react-i18next';
import styled from 'styled-components';
import { Option } from '@polkadot/types';
import { AddressInfo, InputAddress, InputBalance, Modal, TxButton, TxComponent } from '@polkadot/react-components';
import { withCalls, withApi, withMulti } from '@polkadot/react-api/hoc';
import { AddressInfo, InputAddress, InputBalance, Modal, TxButton } from '@polkadot/react-components';
import { BlockToTime } from '@polkadot/react-query';
import { formatNumber } from '@polkadot/util';
import translate from '../../translate';
import { useTranslation } from '../../translate';
import useUnbondDuration from '../useUnbondDuration';
interface Props extends I18nProps, ApiProps {
interface Props {
className?: string;
controllerId?: AccountId | null;
isOpen: boolean;
onClose: () => void;
stakingLedger?: StakingLedger;
stashId: string;
staking_ledger?: Option<StakingLedger>;
}
interface State {
maxBalance?: BN;
maxUnbond?: BN;
}
function Unbond ({ className, controllerId, onClose, stakingLedger, stashId }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const duration = useUnbondDuration();
const [maxBalance] = useState<BN | null>(stakingLedger?.active.unwrap() || null);
const [maxUnbond, setMaxUnbond] = useState<BN | null>(null);
const BalanceWrapper = styled.div`
& > div {
justify-content: flex-end;
& .column {
flex: 0;
}
}
`;
class Unbond extends TxComponent<Props, State> {
public state: State = {};
public componentDidUpdate (prevProps: Props): void {
const { staking_ledger } = this.props;
if (staking_ledger !== prevProps.staking_ledger) {
this.setMaxBalance();
}
}
public render (): React.ReactNode {
const { controllerId, isOpen, onClose, t } = this.props;
const { maxUnbond } = this.state;
const canSubmit = !!maxUnbond && maxUnbond.gtn(0);
if (!isOpen) {
return null;
}
return (
<Modal
className='staking--Unbond'
header={t('Unbond funds')}
size='small'
>
{this.renderContent()}
<Modal.Actions onCancel={onClose}>
<TxButton
accountId={controllerId}
icon='sign-out'
isDisabled={!canSubmit}
isPrimary
label={t('Unbond')}
onStart={onClose}
params={[maxUnbond]}
tx='staking.unbond'
withSpinner={false}
/>
</Modal.Actions>
</Modal>
);
}
private renderContent (): React.ReactNode {
const { controllerId, stashId, t } = this.props;
const { maxBalance } = this.state;
return (
return (
<Modal
className={`staking--Unbond ${className}`}
header={t('Unbond funds')}
size='small'
>
<Modal.Content className='ui--signer-Signer-Content'>
<InputAddress
className='medium'
@ -96,63 +42,56 @@ class Unbond extends TxComponent<Props, State> {
isDisabled
label={t('controller account')}
/>
<BalanceWrapper>
<div className='staking--Unbond--max'>
<AddressInfo
accountId={stashId}
withBalance={{
bonded: true
}}
/>
</BalanceWrapper>
</div>
<InputBalance
autoFocus
className='medium'
help={t('The amount of funds to unbond, this is adjusted using the bonded funds on the stash account.')}
label={t('unbond amount')}
maxValue={maxBalance}
onChange={this.onChangeValue}
onEnter={this.sendTx}
onChange={setMaxUnbond}
withMax
/>
{duration?.gtn(0) && (
<article className='warning'>
<Trans key='unlockDuration'>Once unbonded, funds will only be available for withdrawal in <BlockToTime blocks={duration} /> ({formatNumber(duration)} blocks)</Trans>
</article>
)}
</Modal.Content>
);
}
private nextState (newState: Partial<State>): void {
this.setState((prevState: State): State => {
const { maxUnbond = prevState.maxUnbond, maxBalance = prevState.maxBalance } = newState;
return {
maxBalance,
maxUnbond
};
});
}
private setMaxBalance = (): void => {
const { staking_ledger } = this.props;
if (!staking_ledger || staking_ledger.isNone) {
return;
}
const { active } = staking_ledger.unwrap();
this.nextState({
maxBalance: active.unwrap()
});
}
private onChangeValue = (maxUnbond?: BN): void => {
this.nextState({ maxUnbond });
}
<Modal.Actions onCancel={onClose}>
<TxButton
accountId={controllerId}
icon='sign-out'
isDisabled={!maxUnbond?.gtn(0)}
isPrimary
label={t('Unbond')}
onStart={onClose}
params={[maxUnbond]}
tx='staking.unbond'
withSpinner={false}
/>
</Modal.Actions>
</Modal>
);
}
export default withMulti(
Unbond,
translate,
withApi,
withCalls<Props>(
['query.staking.ledger', { paramName: 'controllerId' }]
)
);
export default React.memo(styled(Unbond)`
article.warning > div {
display: inline-block;
}
.staking--Unbond--max > div {
justify-content: flex-end;
& .column {
flex: 0;
}
}
`);

View File

@ -2,82 +2,41 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiProps } from '@polkadot/react-api/types';
import { I18nProps } from '@polkadot/react-components/types';
import BN from 'bn.js';
import React from 'react';
import { withApi, withMulti } from '@polkadot/react-api/hoc';
import { InputAddress, InputNumber, Modal, TxButton, TxComponent } from '@polkadot/react-components';
import React, { useCallback, useState } from 'react';
import { InputAddress, InputNumber, Modal, TxButton } from '@polkadot/react-components';
import translate from '../../translate';
import { useTranslation } from '../../translate';
interface Props extends ApiProps, I18nProps {
interface Props {
controllerId: string;
isOpen: boolean;
onClose: () => void;
stashId: string;
}
interface State {
commission: BN;
}
const COMM_MUL = new BN(10000000);
const MAX_COMM = new BN(100);
const ZERO = new BN(0);
class Validate extends TxComponent<Props, State> {
public state: State = {
commission: new BN(0)
};
function Validate ({ controllerId, onClose, stashId }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [prefs, setPrefs] = useState({ commission: ZERO });
public render (): React.ReactNode {
const { isOpen, t } = this.props;
const _setCommission = useCallback(
(commission?: BN) => setPrefs({ commission: (commission || ZERO).mul(COMM_MUL) }),
[]
);
if (!isOpen) {
return null;
}
return (
<Modal
className='staking--Staking'
header={t('Set validator preferences')}
size='small'
>
{this.renderContent()}
{this.renderButtons()}
</Modal>
);
}
private renderButtons (): React.ReactNode {
const { controllerId, onClose, t } = this.props;
const { commission } = this.state;
return (
<Modal.Actions onCancel={onClose}>
<TxButton
accountId={controllerId}
icon='check circle outline'
isPrimary
label={t('Validate')}
onStart={onClose}
params={[{ commission }]}
tx='staking.validate'
withSpinner
/>
</Modal.Actions>
);
}
private renderContent (): React.ReactNode {
const { controllerId, stashId, t } = this.props;
return (
return (
<Modal
className='staking--Staking'
header={t('Set validator preferences')}
size='small'
>
<Modal.Content className='ui--signer-Signer-Content'>
<InputAddress
className='medium'
defaultValue={stashId.toString()}
defaultValue={stashId}
isDisabled
label={t('stash account')}
/>
@ -93,20 +52,23 @@ class Validate extends TxComponent<Props, State> {
isZeroable
label={t('reward commission percentage')}
maxValue={MAX_COMM}
onChange={this.onChangeCommission}
onEnter={this.sendTx}
onChange={_setCommission}
/>
</Modal.Content>
);
}
private onChangeCommission = (commission?: BN): void => {
commission && this.setState({ commission: commission.mul(COMM_MUL) });
}
<Modal.Actions onCancel={onClose}>
<TxButton
accountId={controllerId}
icon='check circle outline'
isPrimary
label={t('Validate')}
onStart={onClose}
params={[prefs]}
tx='staking.validate'
withSpinner={false}
/>
</Modal.Actions>
</Modal>
);
}
export default withMulti(
Validate,
translate,
withApi
);
export default React.memo(Validate);

View File

@ -97,7 +97,7 @@ function Account ({ allStashes, className, isInElection, isOwnStash, next, onUpd
const validateInfo = useCall<ValidatorInfo>(api.query.staking.validators, [stashId]);
const balancesAll = useCall<DeriveBalancesAll>(api.derive.balances.all as any, [stashId]);
const stakingAccount = useCall<DeriveStakingAccount>(api.derive.staking.account as any, [stashId]);
const [{ controllerId, destination, destinationId, hexSessionIdNext, hexSessionIdQueue, isLoading, isOwnController, isStashNominating, isStashValidating, nominees, sessionIds, validatorPrefs }, setStakeState] = useState<StakeState>({ controllerId: null, destinationId: 0, hexSessionIdNext: null, hexSessionIdQueue: null, isLoading: true, isOwnController: false, isStashNominating: false, isStashValidating: false, sessionIds: [] });
const [{ controllerId, destination, destinationId, hexSessionIdNext, hexSessionIdQueue, isLoading, isOwnController, isStashNominating, isStashValidating, nominees, sessionIds, stakingLedger }, setStakeState] = useState<StakeState>({ controllerId: null, destinationId: 0, hexSessionIdNext: null, hexSessionIdQueue: null, isLoading: true, isOwnController: false, isStashNominating: false, isStashValidating: false, sessionIds: [] });
const [activeNoms, setActiveNoms] = useState<string[]>([]);
const inactiveNoms = useInactives(stashId, nominees);
const [isBondExtraOpen, toggleBondExtra] = useToggle();
@ -146,19 +146,21 @@ function Account ({ allStashes, className, isInElection, isOwnStash, next, onUpd
validators={validators}
/>
)}
<Unbond
controllerId={controllerId}
isOpen={isUnbondOpen}
onClose={toggleUnbond}
stashId={stashId}
/>
<Validate
controllerId={controllerId}
isOpen={isValidateOpen}
onClose={toggleValidate}
stashId={stashId}
validatorPrefs={validatorPrefs}
/>
{isUnbondOpen && (
<Unbond
controllerId={controllerId}
onClose={toggleUnbond}
stakingLedger={stakingLedger}
stashId={stashId}
/>
)}
{isValidateOpen && controllerId && (
<Validate
controllerId={controllerId}
onClose={toggleValidate}
stashId={stashId}
/>
)}
{isBondExtraOpen && (
<BondExtra
onClose={toggleBondExtra}
@ -168,7 +170,7 @@ function Account ({ allStashes, className, isInElection, isOwnStash, next, onUpd
{isInjectOpen && (
<InjectKeys onClose={toggleInject} />
)}
{isSetControllerOpen && (
{isSetControllerOpen && controllerId && (
<SetControllerAccount
defaultControllerId={controllerId}
isValidating={isStashValidating}

View File

@ -0,0 +1,21 @@
// Copyright 2017-2020 @polkadot/app-staking authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import { useEffect, useState } from 'react';
import { useApi, useCall } from '@polkadot/react-hooks';
export default function useUnbondDuration (): BN | undefined {
const { api } = useApi();
const eraLength = useCall<BN>(api.derive.session?.eraLength as any, []);
const [duration, setDuration] = useState<BN | undefined>();
useEffect((): void => {
eraLength && setDuration(
eraLength.mul(api.consts.staking?.bondingDuration)
);
}, [api, eraLength]);
return duration;
}

View File

@ -83,7 +83,7 @@ export default React.memo(styled(LinkExternal)`
> div {
display: block;
whitespace: nowrap;
white-space: nowrap;
> span+span {
margin-left: 0.3rem;

View File

@ -74,8 +74,14 @@ function StakingUnbonding ({ className, stakingInfo }: Props): React.ReactElemen
}
export default React.memo(styled(StakingUnbonding)`
white-space: nowrap;
i.icon {
margin-left: 0.25rem;
margin-right: 0;
}
.ui--FormatBalance {
display: inline-block;
}
`);