New stake steps (#2754)

* New stake steps

* Controller jiggle

* 2 step validation

* Fatal errors on validation

* Cleanups

* Fix auto-select before rewards
This commit is contained in:
Jaco Greeff 2020-05-15 17:05:27 +02:00 committed by GitHub
parent def23cf695
commit 401c147020
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 959 additions and 460 deletions

View File

@ -15,7 +15,7 @@ interface Props {
accountId: string | null;
controllerId: string | null;
defaultController?: string;
onError: (error: string | null) => void;
onError: (error: string | null, isFatal: boolean) => void;
}
function ValidateController ({ accountId, controllerId, defaultController, onError }: Props): React.ReactElement<Props> | null {
@ -33,24 +33,26 @@ function ValidateController ({ accountId, controllerId, defaultController, onErr
? value.unwrap().stash.toString()
: null
});
const [error, setError] = useState<string | null>(null);
const [{ error, isFatal }, setError] = useState<{ error: string | null; isFatal: boolean }>({ error: null, isFatal: false });
useEffect((): void => {
// don't show an error if the selected controller is the default
// this applies when changing controller
if (defaultController !== controllerId) {
let newError: string | null = null;
let isFatal = true;
if (controllerId === accountId) {
newError = t('Distinct stash and controller accounts are recommended to ensure fund security. You will be allowed to make the transaction, but take care to not tie up all funds, only use a portion of the available funds during this period.');
} else if (bondedId) {
if (bondedId) {
newError = t('A controller account should not map to another stash. This selected controller is a stash, controlled by {{bondedId}}', { replace: { bondedId } });
} else if (stashId) {
newError = t('A controller account should not be set to manages multiple stashes. The selected controller is already controlling {{stashId}}', { replace: { stashId } });
} else if (controllerId === accountId) {
newError = t('Distinct stash and controller accounts are recommended to ensure fund security. You will be allowed to make the transaction, but take care to not tie up all funds, only use a portion of the available funds during this period.');
isFatal = false;
}
onError(newError);
setError((error) => error !== newError ? newError : error);
onError(newError, isFatal);
setError((state) => state.error !== newError ? { error: newError, isFatal } : state);
}
}, [accountId, bondedId, controllerId, defaultController, onError, stashId, t]);
@ -59,7 +61,7 @@ function ValidateController ({ accountId, controllerId, defaultController, onErr
}
return (
<article className='warning'>
<article className={isFatal ? 'error' : 'warning'}>
<div><Icon name='warning sign' />{error}</div>
</article>
);

View File

@ -2,238 +2,59 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { SubmittableExtrinsic } from '@polkadot/api/types';
import { SortedTargets } from '../../types';
import React, { useCallback, useState } from 'react';
import styled from 'styled-components';
import { AddressMini, InputAddressMulti, InputAddress, Modal, Static, Toggle, TxButton } from '@polkadot/react-components';
import { useFavorites } from '@polkadot/react-hooks';
import React, { useState } from 'react';
import { Modal, TxButton } from '@polkadot/react-components';
import { MAX_NOMINATIONS, MAX_PAYOUTS, STORE_FAVS_BASE } from '../../constants';
import { useTranslation } from '../../translate';
import NominatePartial from '../partials/Nominate';
interface Props {
className?: string;
controllerId: string;
next?: string[];
nominating?: string[];
onClose: () => void;
stashId: string;
targets: SortedTargets;
validators: string[];
validators?: string[];
}
interface Selected {
isAutoSelect: boolean;
selected: string[];
}
function autoPick (targets: SortedTargets): string[] {
return (targets.validators || []).reduce((result: string[], { key, numNominators }): string[] => {
if (result.length < MAX_NOMINATIONS) {
if (numNominators && (numNominators < MAX_PAYOUTS)) {
result.push(key);
}
}
return result;
}, []);
}
function initialPick (targets: SortedTargets): Selected {
const selected = targets.validators?.length
? autoPick(targets)
: [];
return {
isAutoSelect: selected.length !== 0,
selected
};
}
function Nominate ({ className, controllerId, next, nominating, onClose, stashId, targets, validators }: Props): React.ReactElement<Props> | null {
function Nominate ({ controllerId, next, nominating, onClose, stashId, targets, validators }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const [favorites] = useFavorites(STORE_FAVS_BASE);
const [{ isAutoSelect, selected }, setSelected] = useState<Selected>(initialPick(targets));
const [available] = useState<string[]>((): string[] => {
const shortlist = [
// ensure that the favorite is included in the list of stashes
...favorites.filter((acc) => (validators || []).includes(acc) || (next || []).includes(acc)),
// make sure the nominee is not in our favorites already
...(nominating || []).filter((acc) => !favorites.includes(acc))
];
return shortlist
.concat(...(validators || []).filter((acc) => !shortlist.includes(acc)))
.concat(...(next || []).filter((acc) => !shortlist.includes(acc)));
});
const _setSelected = useCallback(
(selected: string[]) => setSelected(({ isAutoSelect }: Selected) => ({
isAutoSelect,
selected
})),
[]
);
const _toggleAutoSelect = useCallback(
(isAutoSelect: boolean) => setSelected(() => ({
isAutoSelect,
selected: isAutoSelect
? autoPick(targets)
: []
})),
[targets]
);
const [tx, setTx] = useState<SubmittableExtrinsic<'promise'> | null>(null);
return (
<Modal
className={`staking--Nominating ${className}`}
header={t('Nominate Validators')}
size='large'
>
<Modal.Content className='ui--signer-Signer-Content'>
<Modal.Columns>
<Modal.Column>
<InputAddress
defaultValue={stashId}
isDisabled
label={t('stash account')}
/>
<InputAddress
defaultValue={controllerId}
isDisabled
label={t('controller account')}
/>
</Modal.Column>
<Modal.Column>
<p>{t('The stash that is to be affected. The transaction will be sent from the associated controller account.')}</p>
</Modal.Column>
</Modal.Columns>
<Modal.Columns>
<Modal.Column>
{isAutoSelect
? (
<>
<Static
label={t('auto-selected targets for nomination')}
value={
selected.map((validatorId) => (
<AddressMini
key={validatorId}
value={validatorId}
/>
))
}
/>
<article className='warning'>{t('The auto-selection is done on the current profitability of the validators taking your favorites into account. It is adjusted based on the commission and current range of backing for the validator. The calculation may and will change over time, so it is rather a selection based on the current state of the network, not a predictor of future profitability.')}</article>
</>
)
: (
<InputAddressMulti
available={available}
availableLabel={t('candidate accounts')}
defaultValue={nominating}
help={t('Filter available candidates based on name, address or short account index.')}
maxCount={MAX_NOMINATIONS}
onChange={_setSelected}
valueLabel={t('nominated accounts')}
/>
)
}
<Toggle
className='auto--toggle'
isDisabled={!targets.validators?.length}
label={
isAutoSelect
? t('Use an automatic selection of the currently most profitable validators')
: t('Select targets manually (no auto-selection based on current profitability)')
}
onChange={_toggleAutoSelect}
value={isAutoSelect}
/>
</Modal.Column>
<Modal.Column>
<p>{t('Nominators can be selected automatically based on the current on-chain conditions or supplied manually as selected from the list of all currently available validators. In both cases, your favorites appear for the selection.')}</p>
<p>{t('Once transmitted the new selection will only take effect in 2 eras since the selection criteria for the next era was done at the end of the previous era. Until then, the nominations will show as inactive.')}</p>
</Modal.Column>
</Modal.Columns>
<Modal.Content>
<NominatePartial
controllerId={controllerId}
next={next}
nominating={nominating}
onChange={setTx}
stashId={stashId}
targets={targets}
validators={validators}
withSenders
/>
</Modal.Content>
<Modal.Actions onCancel={onClose}>
<TxButton
accountId={controllerId}
extrinsic={tx}
icon='hand paper outline'
isDisabled={!selected?.length}
isDisabled={!tx}
isPrimary
label={t('Nominate')}
onStart={onClose}
params={[selected]}
tx='staking.nominate'
/>
</Modal.Actions>
</Modal>
);
}
export default React.memo(styled(Nominate)`
article.warning {
margin-top: 0;
}
.auto--toggle {
margin: 0.5rem 0 0;
text-align: right;
width: 100%;
}
.ui--Static .ui--AddressMini.padded {
padding-top: 0.5rem;
}
.shortlist {
display: flex;
flex-wrap: wrap;
justify-content: center;
.candidate {
border: 1px solid #eee;
border-radius: 0.25rem;
margin: 0.25rem;
padding-bottom: 0.25rem;
padding-right: 0.5rem;
position: relative;
&::after {
content: '';
position: absolute;
top: 0;
right: 0;
border-color: transparent;
border-style: solid;
border-radius: 0.25em;
border-width: 0.25em;
}
&.isAye {
background: #fff;
border-color: #ccc;
}
&.member::after {
border-color: green;
}
&.runnerup::after {
border-color: steelblue;
}
.ui--AddressMini-icon {
z-index: 1;
}
.candidate-right {
text-align: right;
}
}
}
`);
export default React.memo(Nominate);

View File

@ -2,10 +2,13 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { SessionInfo } from '../partials/types';
import React, { useState } from 'react';
import { Input, InputAddress, Modal, TxButton } from '@polkadot/react-components';
import { Modal, TxButton } from '@polkadot/react-components';
import { useTranslation } from '../../translate';
import SessionKeyPartital from '../partials/SessionKey';
interface Props {
controllerId: string;
@ -13,63 +16,32 @@ interface Props {
stashId: string;
}
const EMPTY_PROOF = new Uint8Array();
function SetSessionKey ({ controllerId, onClose, stashId }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const [keys, setKeys] = useState<string | null>(null);
const [{ sessionTx }, setTx] = useState<SessionInfo>({});
return (
<Modal
className='staking--SetSessionAccount'
header={t('Set Session Key')}
size='large'
>
<Modal.Content className='ui--signer-Signer-Content'>
<Modal.Columns>
<Modal.Column>
<InputAddress
defaultValue={stashId}
isDisabled
label={t('stash account')}
/>
<InputAddress
className='medium'
defaultValue={controllerId}
isDisabled
label={t('controller account')}
/>
</Modal.Column>
<Modal.Column>
<p>{t('The stash and controller pair. This transaction, setting the session keys, will be sent from the controller.')}</p>
</Modal.Column>
</Modal.Columns>
<Modal.Columns>
<Modal.Column>
<Input
autoFocus
help={t('Changing the key only takes effect at the start of the next session. The input here is generates from the author_rotateKeys command')}
isError={!keys}
label={t('Keys from rotateKeys')}
onChange={setKeys}
placeholder='0x...'
/>
</Modal.Column>
<Modal.Column>
<p>{t('The hex output from author_rotateKeys, as executed on the validator node. The keys will show as pending until applied at the start of a new session.')}</p>
</Modal.Column>
</Modal.Columns>
<Modal.Content>
<SessionKeyPartital
controllerId={controllerId}
onChange={setTx}
stashId={stashId}
withSenders
/>
</Modal.Content>
<Modal.Actions onCancel={onClose}>
<TxButton
accountId={controllerId}
extrinsic={sessionTx}
icon='sign-in'
isDisabled={!keys}
isDisabled={!sessionTx}
isPrimary
label={t('Set Session Key')}
onStart={onClose}
params={[keys, EMPTY_PROOF]}
tx='session.setKeys'
/>
</Modal.Actions>
</Modal>

View File

@ -2,11 +2,13 @@
// 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 React, { useCallback, useState } from 'react';
import { InputAddress, InputNumber, Modal, TxButton } from '@polkadot/react-components';
import { ValidateInfo } from '../partials/types';
import React, { useState } from 'react';
import { Modal, TxButton } from '@polkadot/react-components';
import { useTranslation } from '../../translate';
import ValidatePartial from '../partials/Validate';
interface Props {
controllerId: string;
@ -14,67 +16,32 @@ interface Props {
stashId: string;
}
const COMM_MUL = new BN(10000000);
const MAX_COMM = new BN(100);
const ZERO = new BN(0);
function Validate ({ controllerId, onClose, stashId }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [prefs, setPrefs] = useState({ commission: ZERO });
const _setCommission = useCallback(
(commission?: BN) => setPrefs({ commission: (commission || ZERO).mul(COMM_MUL) }),
[]
);
const [{ validateTx }, setTx] = useState<ValidateInfo>({});
return (
<Modal
className='staking--Staking'
header={t('Set validator preferences')}
size='large'
>
<Modal.Content className='ui--signer-Signer-Content'>
<Modal.Columns>
<Modal.Column>
<InputAddress
defaultValue={stashId}
isDisabled
label={t('stash account')}
/>
<InputAddress
defaultValue={controllerId}
isDisabled
label={t('controller account')}
/>
</Modal.Column>
<Modal.Column>
<p>{t('The stash and controller pair. This transaction, managing preferences, will be sent from the controller.')}</p>
</Modal.Column>
</Modal.Columns>
<Modal.Columns>
<Modal.Column>
<InputNumber
help={t('The percentage reward (0-100) that should be applied for the validator')}
isZeroable
label={t('reward commission percentage')}
maxValue={MAX_COMM}
onChange={_setCommission}
/>
</Modal.Column>
<Modal.Column>
<p>{t('The commission is deducted from all rewards before the remainder is split with nominators.')}</p>
</Modal.Column>
</Modal.Columns>
<ValidatePartial
controllerId={controllerId}
onChange={setTx}
stashId={stashId}
withSenders
/>
</Modal.Content>
<Modal.Actions onCancel={onClose}>
<TxButton
accountId={controllerId}
extrinsic={validateTx}
icon='check circle outline'
isDisabled={!validateTx}
isPrimary
label={t('Validate')}
onStart={onClose}
params={[prefs]}
tx='staking.validate'
/>
</Modal.Actions>
</Modal>

View File

@ -65,7 +65,6 @@ function Account ({ className, info: { controllerId, destination, destinationId,
{isNominateOpen && controllerId && (
<Nominate
controllerId={controllerId}
isOpen={isNominateOpen}
next={next}
nominating={nominating}
onClose={toggleNominate}

View File

@ -0,0 +1,129 @@
// 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 { BondInfo, NominateInfo } from './partials/types';
import { SortedTargets } from '../types';
import React, { useCallback, useState } from 'react';
import { Button, Modal, TxButton } from '@polkadot/react-components';
import { useToggle } from '@polkadot/react-hooks';
import { useTranslation } from '../translate';
import BondPartial from './partials/Bond';
import NominatePartial from './partials/Nominate';
interface Props {
isInElection?: boolean;
next?: string[];
targets?: SortedTargets;
validators?: string[];
}
const EMPTY_NOMS: string[] = [];
const NUM_STEPS = 2;
function NewNominator ({ isInElection, next, targets, validators }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [isVisible, toggleVisible] = useToggle();
const [{ bondOwnTx, bondTx, controllerId, controllerTx, stashId }, setBondInfo] = useState<BondInfo>({});
const [{ nominateTx }, setNominateInfo] = useState<NominateInfo>({});
const [step, setStep] = useState(1);
const _nextStep = useCallback(
() => setStep((step) => step + 1),
[]
);
const _prevStep = useCallback(
() => setStep((step) => step - 1),
[]
);
const _toggle = useCallback(
(): void => {
setBondInfo({});
setNominateInfo({});
setStep(1);
toggleVisible();
},
[toggleVisible]
);
return (
<>
<Button
icon='add'
isDisabled={isInElection}
key='new-nominator'
label={t('Nominator')}
onClick={_toggle}
/>
{isVisible && (
<Modal
header={t('Setup Nominator {{step}}/{{NUM_STEPS}}', {
replace: {
NUM_STEPS,
step
}
})}
size='large'
>
<Modal.Content>
{step === 1 && (
<BondPartial onChange={setBondInfo} />
)}
{controllerId && stashId && step === 2 && (
<NominatePartial
controllerId={controllerId}
next={next}
nominating={EMPTY_NOMS}
onChange={setNominateInfo}
stashId={stashId}
targets={targets}
validators={validators}
/>
)}
</Modal.Content>
<Modal.Actions onCancel={_toggle}>
<Button
icon='step backward'
isDisabled={step === 1}
label={t('prev')}
onClick={_prevStep}
/>
{step === NUM_STEPS
? (
<TxButton
accountId={stashId}
icon='sign-in'
isDisabled={!bondTx || !nominateTx || !stashId || !controllerId}
isPrimary
label={t('Bond & Nominate')}
onStart={_toggle}
params={[
stashId === controllerId
? [bondTx, nominateTx]
: [bondOwnTx, nominateTx, controllerTx]
]}
tx='utility.batch'
/>
)
: (
<Button
icon='step forward'
isDisabled={!bondTx}
isPrimary
label={t('next')}
onClick={_nextStep}
/>
)
}
</Modal.Actions>
</Modal>
)}
</>
);
}
export default React.memo(NewNominator);

View File

@ -1,159 +0,0 @@
// 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 { SubmittableExtrinsic } from '@polkadot/api/types';
import BN from 'bn.js';
import React, { useEffect, useState } from 'react';
import { Button, Dropdown, InputAddress, InputBalance, Modal, TxButton, Static } from '@polkadot/react-components';
import { useApi, useToggle } from '@polkadot/react-hooks';
import { Available, BlockToTime } from '@polkadot/react-query';
import { useTranslation } from '../translate';
import InputValidateAmount from './Account/InputValidateAmount';
import InputValidationController from './Account/InputValidationController';
import { rewardDestinationOptions } from './constants';
import useUnbondDuration from './useUnbondDuration';
interface Props {
className?: string;
isInElection?: boolean;
}
function NewStake ({ className, isInElection }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const [isVisible, toggleVisible] = useToggle();
const [amount, setAmount] = useState<BN | undefined>();
const [amountError, setAmountError] = useState<string | null>(null);
const [, setControllerError] = useState<string | null>(null);
const [controllerId, setControllerId] = useState<string | null>(null);
const [destination, setDestination] = useState(0);
const [extrinsic, setExtrinsic] = useState<SubmittableExtrinsic<'promise'> | null>(null);
const [stashId, setStashId] = useState<string | null>(null);
const bondedBlocks = useUnbondDuration();
useEffect((): void => {
setExtrinsic(
() => (amount && controllerId)
? api.tx.staking.bond(controllerId, amount, destination)
: null
);
}, [api, amount, controllerId, destination]);
const hasValue = !!amount?.gtn(0);
const canSubmit = hasValue && !!controllerId;
return (
<div className={className}>
<Button.Group>
<Button
icon='add'
isDisabled={isInElection}
key='new-stake'
label={t('New stake')}
onClick={toggleVisible}
/>
</Button.Group>
{isVisible && (
<Modal
className='staking--Bonding'
header={t('Bonding Preferences')}
size='large'
>
<Modal.Content className='ui--signer-Signer-Content'>
<Modal.Columns>
<Modal.Column>
<InputAddress
label={t('stash account')}
onChange={setStashId}
type='account'
value={stashId}
/>
<InputAddress
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}
onError={setControllerError}
/>
</Modal.Column>
<Modal.Column>
<p>{t('Think of the stash as your cold wallet and the controller as your hot wallet. Funding operations are controlled by the stash, any other non-funding actions by the controller itself.')}</p>
<p>{t('To ensure optimal fund security using the same stash/controller is strongly discouraged, but not forbidden.')}</p>
</Modal.Column>
</Modal.Columns>
<Modal.Columns>
<Modal.Column>
<InputBalance
autoFocus
help={t('The total amount of the stash balance that will be at stake in any forthcoming rounds (should be less than the total amount available)')}
isError={!hasValue || !!amountError}
label={t('value bonded')}
labelExtra={
<Available
label={<span className='label'>{t('available')}</span>}
params={stashId}
/>
}
onChange={setAmount}
/>
{bondedBlocks?.gtn(0) && (
<Static
help={t('The bonding duration for any staked funds. Needs to be unlocked and withdrawn to become available.')}
label={t('on-chain bonding duration')}
>
<BlockToTime blocks={bondedBlocks} />
</Static>
)}
<InputValidateAmount
accountId={stashId}
onError={setAmountError}
value={amount}
/>
</Modal.Column>
<Modal.Column>
<p>{t('The amount placed at-stake should be no more that 95% of your available amount to protect against slashing events.')}</p>
<p>{t('Once bonded, it wil need to be unlocked/withdrawn and will be locked for at least the bonding duration.')}</p>
</Modal.Column>
</Modal.Columns>
<Modal.Columns>
<Modal.Column>
<Dropdown
defaultValue={0}
help={t('The destination account for any payments as either a nominator or validator')}
label={t('payment destination')}
onChange={setDestination}
options={rewardDestinationOptions}
value={destination}
/>
</Modal.Column>
<Modal.Column>
<p>{t('Rewards (once paid) can be deposited to either the stash or controller, with different effects.')}</p>
</Modal.Column>
</Modal.Columns>
</Modal.Content>
<Modal.Actions onCancel={toggleVisible}>
<TxButton
accountId={stashId}
extrinsic={extrinsic}
icon='sign-in'
isDisabled={!canSubmit}
isPrimary
label={t('Bond')}
onStart={toggleVisible}
/>
</Modal.Actions>
</Modal>
)}
</div>
);
}
export default React.memo(NewStake);

View File

@ -0,0 +1,60 @@
// 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 { BondInfo } from './partials/types';
import React, { useCallback, useState } from 'react';
import { Button, Modal, TxButton } from '@polkadot/react-components';
import { useToggle } from '@polkadot/react-hooks';
import { useTranslation } from '../translate';
import BondPartial from './partials/Bond';
function NewStash (): React.ReactElement {
const { t } = useTranslation();
const [isVisible, toggleVisible] = useToggle();
const [{ bondTx, stashId }, setBondInfo] = useState<BondInfo>({});
const _toggle = useCallback(
(): void => {
setBondInfo({});
toggleVisible();
},
[toggleVisible]
);
return (
<>
<Button
icon='add'
key='new-stash'
label={t('Stash')}
onClick={_toggle}
/>
{isVisible && (
<Modal
header={t('Bonding Preferences')}
size='large'
>
<Modal.Content>
<BondPartial onChange={setBondInfo} />
</Modal.Content>
<Modal.Actions onCancel={_toggle}>
<TxButton
accountId={stashId}
extrinsic={bondTx}
icon='sign-in'
isDisabled={!bondTx || !stashId}
isPrimary
label={t('Bond')}
onStart={_toggle}
/>
</Modal.Actions>
</Modal>
)}
</>
);
}
export default React.memo(NewStash);

View File

@ -0,0 +1,130 @@
// 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 { BondInfo, SessionInfo, ValidateInfo } from './partials/types';
import React, { useCallback, useState } from 'react';
import { Button, Modal, TxButton } from '@polkadot/react-components';
import { useToggle } from '@polkadot/react-hooks';
import { useTranslation } from '../translate';
import BondPartial from './partials/Bond';
import SessionKeyPartial from './partials/SessionKey';
import ValidatePartial from './partials/Validate';
interface Props {
isInElection?: boolean;
}
const NUM_STEPS = 2;
function NewValidator ({ isInElection }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [isVisible, toggleVisible] = useToggle();
const [{ bondOwnTx, bondTx, controllerId, controllerTx, stashId }, setBondInfo] = useState<BondInfo>({});
const [{ sessionTx }, setSessionInfo] = useState<SessionInfo>({});
const [{ validateTx }, setValidateInfo] = useState<ValidateInfo>({});
const [step, setStep] = useState(1);
const _nextStep = useCallback(
() => setStep((step) => step + 1),
[]
);
const _prevStep = useCallback(
() => setStep((step) => step - 1),
[]
);
const _toggle = useCallback(
(): void => {
setBondInfo({});
setSessionInfo({});
setValidateInfo({});
setStep(1);
toggleVisible();
},
[toggleVisible]
);
return (
<>
<Button
icon='add'
isDisabled={isInElection}
key='new-validator'
label={t('Validator')}
onClick={_toggle}
/>
{isVisible && (
<Modal
header={t('Setup Validator {{step}}/{{NUM_STEPS}}', {
replace: {
NUM_STEPS,
step
}
})}
size='large'
>
<Modal.Content>
{step === 1 && (
<BondPartial onChange={setBondInfo} />
)}
{controllerId && stashId && step === 2 && (
<>
<SessionKeyPartial
controllerId={controllerId}
onChange={setSessionInfo}
stashId={stashId}
/>
<ValidatePartial
controllerId={controllerId}
onChange={setValidateInfo}
stashId={stashId}
/>
</>
)}
</Modal.Content>
<Modal.Actions onCancel={_toggle}>
<Button
icon='step backward'
isDisabled={step === 1}
label={t('prev')}
onClick={_prevStep}
/>
{step === NUM_STEPS
? (
<TxButton
accountId={stashId}
icon='sign-in'
isDisabled={!bondTx || !sessionTx || !validateTx}
isPrimary
label={t('Bond & Validate')}
onStart={_toggle}
params={[
controllerId === stashId
? [bondTx, sessionTx, validateTx]
: [bondOwnTx, sessionTx, validateTx, controllerTx]
]}
tx='utility.batch'
/>
)
: (
<Button
icon='step forward'
isDisabled={!bondTx}
isPrimary
label={t('next')}
onClick={_nextStep}
/>
)}
</Modal.Actions>
</Modal>
)}
</>
);
}
export default React.memo(NewValidator);

View File

@ -8,7 +8,7 @@ import { SortedTargets } from '../types';
import BN from 'bn.js';
import React, { useEffect, useMemo, useState } from 'react';
import { Table } from '@polkadot/react-components';
import { Button, Table } from '@polkadot/react-components';
import { useCall, useApi } from '@polkadot/react-hooks';
import { FormatBalance } from '@polkadot/react-query';
import { Option } from '@polkadot/types';
@ -16,7 +16,9 @@ import { Option } from '@polkadot/types';
import ElectionBanner from '../ElectionBanner';
import { useTranslation } from '../translate';
import Account from './Account';
import NewStake from './NewStake';
import NewNominator from './NewNominator';
import NewStash from './NewStash';
import NewValidator from './NewValidator';
interface Props {
className?: string;
@ -73,7 +75,16 @@ function Actions ({ className, isInElection, next, ownStashes, targets, validato
return (
<div className={className}>
<NewStake />
<Button.Group>
<NewNominator
isInElection={isInElection}
next={next}
targets={targets}
validators={validators}
/>
<NewValidator isInElection={isInElection} />
<NewStash />
</Button.Group>
<ElectionBanner isInElection={isInElection} />
<Table
empty={foundStashes && t('No funds staked yet. Bond funds to validate or nominate a validator')}

View File

@ -0,0 +1,142 @@
// 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 { BondInfo } from './types';
import BN from 'bn.js';
import React, { useCallback, useEffect, useState } from 'react';
import { Dropdown, InputAddress, InputBalance, Modal, Static } from '@polkadot/react-components';
import { Available, BlockToTime } from '@polkadot/react-query';
import { useApi } from '@polkadot/react-hooks';
import { useTranslation } from '../../translate';
import InputValidateAmount from '../Account/InputValidateAmount';
import InputValidationController from '../Account/InputValidationController';
import { rewardDestinationOptions } from '../constants';
import useUnbondDuration from '../useUnbondDuration';
interface Props {
className?: string;
onChange: (info: BondInfo) => void;
}
function Bond ({ className, onChange }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const [amount, setAmount] = useState<BN | undefined>();
const [amountError, setAmountError] = useState<string | null>(null);
const [controllerError, setControllerError] = useState<boolean>(false);
const [controllerId, setControllerId] = useState<string | null>(null);
const [destination, setDestination] = useState(0);
const [stashId, setStashId] = useState<string | null>(null);
const bondedBlocks = useUnbondDuration();
const _setError = useCallback(
// eslint-disable-next-line handle-callback-err
(error: string | null, isFatal: boolean) => setControllerError(isFatal),
[]
);
useEffect((): void => {
onChange(
(amount && amount.gtn(0) && !controllerError && controllerId && stashId)
? {
bondOwnTx: api.tx.staking.bond(stashId, amount, destination),
bondTx: api.tx.staking.bond(controllerId, amount, destination),
controllerId,
controllerTx: api.tx.staking.setController(controllerId),
stashId
}
: {
bondTx: null,
controllerId: null,
stashId: null
}
);
}, [api, amount, controllerError, controllerId, destination, stashId, onChange]);
const hasValue = !!amount?.gtn(0);
return (
<div className={className}>
<Modal.Columns>
<Modal.Column>
<InputAddress
label={t('stash account')}
onChange={setStashId}
type='account'
value={stashId}
/>
<InputAddress
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}
onError={_setError}
/>
</Modal.Column>
<Modal.Column>
<p>{t('Think of the stash as your cold wallet and the controller as your hot wallet. Funding operations are controlled by the stash, any other non-funding actions by the controller itself.')}</p>
<p>{t('To ensure optimal fund security using the same stash/controller is strongly discouraged, but not forbidden.')}</p>
</Modal.Column>
</Modal.Columns>
<Modal.Columns>
<Modal.Column>
<InputBalance
autoFocus
help={t('The total amount of the stash balance that will be at stake in any forthcoming rounds (should be less than the total amount available)')}
isError={!hasValue || !!amountError}
label={t('value bonded')}
labelExtra={
<Available
label={<span className='label'>{t('available')}</span>}
params={stashId}
/>
}
onChange={setAmount}
/>
{bondedBlocks?.gtn(0) && (
<Static
help={t('The bonding duration for any staked funds. Needs to be unlocked and withdrawn to become available.')}
label={t('on-chain bonding duration')}
>
<BlockToTime blocks={bondedBlocks} />
</Static>
)}
<InputValidateAmount
accountId={stashId}
onError={setAmountError}
value={amount}
/>
</Modal.Column>
<Modal.Column>
<p>{t('The amount placed at-stake should be no more that 95% of your available amount to protect against slashing events.')}</p>
<p>{t('Once bonded, it wil need to be unlocked/withdrawn and will be locked for at least the bonding duration.')}</p>
</Modal.Column>
</Modal.Columns>
<Modal.Columns>
<Modal.Column>
<Dropdown
defaultValue={0}
help={t('The destination account for any payments as either a nominator or validator')}
label={t('payment destination')}
onChange={setDestination}
options={rewardDestinationOptions}
value={destination}
/>
</Modal.Column>
<Modal.Column>
<p>{t('Rewards (once paid) can be deposited to either the stash or controller, with different effects.')}</p>
</Modal.Column>
</Modal.Columns>
</div>
);
}
export default React.memo(Bond);

View File

@ -0,0 +1,245 @@
// 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 { NominateInfo } from './types';
import { SortedTargets } from '../../types';
import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
import { AddressMini, InputAddress, InputAddressMulti, Modal, Static, Toggle } from '@polkadot/react-components';
import { useApi, useFavorites } from '@polkadot/react-hooks';
import { MAX_NOMINATIONS, MAX_PAYOUTS, STORE_FAVS_BASE } from '../../constants';
import { useTranslation } from '../../translate';
interface Props {
className?: string;
controllerId: string;
next?: string[];
nominating?: string[];
onChange: (info: NominateInfo) => void;
stashId: string;
targets: SortedTargets;
validators: string[];
withSenders?: boolean;
}
interface Selected {
isAutoSelect: boolean;
selected: string[];
}
function autoPick (targets: SortedTargets): string[] {
return (targets.validators || []).reduce((result: string[], { key, numNominators }): string[] => {
if (result.length < MAX_NOMINATIONS) {
if (numNominators && (numNominators < MAX_PAYOUTS)) {
result.push(key);
}
}
return result;
}, []);
}
function initialPick (targets: SortedTargets): Selected {
const selected = targets.validators?.length
? autoPick(targets)
: [];
return {
isAutoSelect: selected.length !== 0,
selected
};
}
function Nominate ({ className, controllerId, next, nominating, onChange, stashId, targets, validators, withSenders }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const [favorites] = useFavorites(STORE_FAVS_BASE);
const [{ isAutoSelect, selected }, setSelected] = useState<Selected>(initialPick(targets));
const [available] = useState<string[]>((): string[] => {
const shortlist = [
// ensure that the favorite is included in the list of stashes
...favorites.filter((acc) => (validators || []).includes(acc) || (next || []).includes(acc)),
// make sure the nominee is not in our favorites already
...(nominating || []).filter((acc) => !favorites.includes(acc))
];
return shortlist
.concat(...(validators || []).filter((acc) => !shortlist.includes(acc)))
.concat(...(next || []).filter((acc) => !shortlist.includes(acc)));
});
const [autoSelected, setAutoSelected] = useState<string[]>([]);
const _setSelected = useCallback(
(selected: string[]) => setSelected(({ isAutoSelect }: Selected) => ({
isAutoSelect,
selected
})),
[]
);
const _toggleAutoSelect = useCallback(
(isAutoSelect: boolean) => setSelected(() => ({
isAutoSelect,
selected: isAutoSelect
? autoSelected
: []
})),
[autoSelected]
);
useEffect((): void => {
setAutoSelected(
targets.validators?.length
? autoPick(targets)
: []
);
}, [targets]);
useEffect((): void => {
onChange({
nominateTx: selected && selected.length
? api.tx.staking.nominate(selected)
: null
});
}, [api, onChange, selected]);
return (
<div className={className}>
{withSenders && (
<Modal.Columns>
<Modal.Column>
<InputAddress
defaultValue={stashId}
isDisabled
label={t('stash account')}
/>
<InputAddress
defaultValue={controllerId}
isDisabled
label={t('controller account')}
/>
</Modal.Column>
<Modal.Column>
<p>{t('The stash that is to be affected. The transaction will be sent from the associated controller account.')}</p>
</Modal.Column>
</Modal.Columns>
)}
<Modal.Columns>
<Modal.Column>
{isAutoSelect
? (
<>
<Static
label={t('auto-selected targets for nomination')}
value={
selected.map((validatorId) => (
<AddressMini
key={validatorId}
value={validatorId}
/>
))
}
/>
<article className='warning'>{t('The auto-selection is done on the current profitability of the validators taking your favorites into account. It is adjusted based on the commission and current range of backing for the validator. The calculation may and will change over time, so it is rather a selection based on the current state of the network, not a predictor of future profitability.')}</article>
</>
)
: (
<InputAddressMulti
available={available}
availableLabel={t('candidate accounts')}
defaultValue={nominating}
help={t('Filter available candidates based on name, address or short account index.')}
maxCount={MAX_NOMINATIONS}
onChange={_setSelected}
valueLabel={t('nominated accounts')}
/>
)
}
{autoSelected.length !== 0 && (
<Toggle
className='auto--toggle'
isDisabled={!targets.validators?.length}
label={
isAutoSelect
? t('Use an automatic selection of the currently most profitable validators')
: t('Select targets manually (no auto-selection based on current profitability)')
}
onChange={_toggleAutoSelect}
value={isAutoSelect}
/>
)}
</Modal.Column>
<Modal.Column>
<p>{t('Nominators can be selected automatically based on the current on-chain conditions or supplied manually as selected from the list of all currently available validators. In both cases, your favorites appear for the selection.')}</p>
<p>{t('Once transmitted the new selection will only take effect in 2 eras since the selection criteria for the next era was done at the end of the previous era. Until then, the nominations will show as inactive.')}</p>
</Modal.Column>
</Modal.Columns>
</div>
);
}
export default React.memo(styled(Nominate)`
article.warning {
margin-top: 0;
}
.auto--toggle {
margin: 0.5rem 0 0;
text-align: right;
width: 100%;
}
.ui--Static .ui--AddressMini.padded {
padding-top: 0.5rem;
}
.shortlist {
display: flex;
flex-wrap: wrap;
justify-content: center;
.candidate {
border: 1px solid #eee;
border-radius: 0.25rem;
margin: 0.25rem;
padding-bottom: 0.25rem;
padding-right: 0.5rem;
position: relative;
&::after {
content: '';
position: absolute;
top: 0;
right: 0;
border-color: transparent;
border-style: solid;
border-radius: 0.25em;
border-width: 0.25em;
}
&.isAye {
background: #fff;
border-color: #ccc;
}
&.member::after {
border-color: green;
}
&.runnerup::after {
border-color: steelblue;
}
.ui--AddressMini-icon {
z-index: 1;
}
.candidate-right {
text-align: right;
}
}
}
`);

View File

@ -0,0 +1,79 @@
// 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 { SessionInfo } from './types';
import React, { useEffect, useState } from 'react';
import { InputAddress, Input, Modal } from '@polkadot/react-components';
import { useApi } from '@polkadot/react-hooks';
import { isHex } from '@polkadot/util';
import { useTranslation } from '../../translate';
interface Props {
className?: string;
controllerId: string;
onChange: (info: SessionInfo) => void;
stashId: string;
withSenders?: boolean;
}
const EMPTY_PROOF = new Uint8Array();
function SessionKey ({ className, controllerId, onChange, stashId, withSenders }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const [keys, setKeys] = useState<string | null>(null);
useEffect((): void => {
onChange({
sessionTx: isHex(keys)
// this is weird... :(
? api.tx.session.setKeys(keys as any, EMPTY_PROOF)
: null
});
}, [api, keys, onChange]);
return (
<div className={className}>
{withSenders && (
<Modal.Columns>
<Modal.Column>
<InputAddress
defaultValue={stashId}
isDisabled
label={t('stash account')}
/>
<InputAddress
className='medium'
defaultValue={controllerId}
isDisabled
label={t('controller account')}
/>
</Modal.Column>
<Modal.Column>
<p>{t('The stash and controller pair. This transaction, setting the session keys, will be sent from the controller.')}</p>
</Modal.Column>
</Modal.Columns>
)}
<Modal.Columns>
<Modal.Column>
<Input
autoFocus
help={t('Changing the key only takes effect at the start of the next session. The input here is generates from the author_rotateKeys command')}
isError={!keys}
label={t('Keys from rotateKeys')}
onChange={setKeys}
placeholder='0x...'
/>
</Modal.Column>
<Modal.Column>
<p>{t('The hex output from author_rotateKeys, as executed on the validator node. The keys will show as pending until applied at the start of a new session.')}</p>
</Modal.Column>
</Modal.Columns>
</div>
);
}
export default React.memo(SessionKey);

View File

@ -0,0 +1,76 @@
// 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 { ValidateInfo } from './types';
import BN from 'bn.js';
import React, { useCallback } from 'react';
import { InputAddress, InputNumber, Modal } from '@polkadot/react-components';
import { useApi } from '@polkadot/react-hooks';
import { useTranslation } from '../../translate';
interface Props {
className?: string;
controllerId: string;
onChange: (info: ValidateInfo) => void;
stashId: string;
withSenders?: boolean;
}
const COMM_MUL = new BN(10000000);
const MAX_COMM = new BN(100);
const ZERO = new BN(0);
function Validate ({ className, controllerId, onChange, stashId, withSenders }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const _setCommission = useCallback(
(commission?: BN) => onChange({
validateTx: api.tx.staking.validate({ commission: (commission || ZERO).mul(COMM_MUL) })
}),
[api, onChange]
);
return (
<div className={className}>
{withSenders && (
<Modal.Columns>
<Modal.Column>
<InputAddress
defaultValue={stashId}
isDisabled
label={t('stash account')}
/>
<InputAddress
defaultValue={controllerId}
isDisabled
label={t('controller account')}
/>
</Modal.Column>
<Modal.Column>
<p>{t('The stash and controller pair. This transaction, managing preferences, will be sent from the controller.')}</p>
</Modal.Column>
</Modal.Columns>
)}
<Modal.Columns>
<Modal.Column>
<InputNumber
help={t('The percentage reward (0-100) that should be applied for the validator')}
isZeroable
label={t('reward commission percentage')}
maxValue={MAX_COMM}
onChange={_setCommission}
/>
</Modal.Column>
<Modal.Column>
<p>{t('The commission is deducted from all rewards before the remainder is split with nominators.')}</p>
</Modal.Column>
</Modal.Columns>
</div>
);
}
export default React.memo(Validate);

View File

@ -0,0 +1,25 @@
// 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 { SubmittableExtrinsic } from '@polkadot/api/types';
export interface BondInfo {
bondOwnTx?: SubmittableExtrinsic<'promise'> | null;
bondTx?: SubmittableExtrinsic<'promise'> | null;
controllerId?: string | null;
controllerTx?: SubmittableExtrinsic<'promise'> | null;
stashId?: string | null;
}
export interface NominateInfo {
nominateTx?: SubmittableExtrinsic<'promise'> | null;
}
export interface SessionInfo {
sessionTx?: SubmittableExtrinsic<'promise'> | null;
}
export interface ValidateInfo {
validateTx?: SubmittableExtrinsic<'promise'> | null;
}