Clearing of democracy votes (#2721)

* Clearing of democracy votes

* Indicate ongoing referendums
This commit is contained in:
Jaco Greeff 2020-05-12 13:02:18 +02:00 committed by GitHub
parent aa833b8416
commit 259af2bc11
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 467 additions and 322 deletions

View File

@ -8,10 +8,10 @@
"packages/*"
],
"resolutions": {
"@polkadot/api": "^1.14.0-beta.6",
"@polkadot/api-contract": "^1.14.0-beta.6",
"@polkadot/api": "^1.14.0-beta.9",
"@polkadot/api-contract": "^1.14.0-beta.9",
"@polkadot/keyring": "^2.10.0-beta.5",
"@polkadot/types": "^1.14.0-beta.6",
"@polkadot/types": "^1.14.0-beta.9",
"@polkadot/util": "^2.10.0-beta.5",
"@polkadot/util-crypto": "^2.10.0-beta.5",
"babel-core": "^7.0.0-bridge.0",
@ -38,7 +38,7 @@
"@babel/core": "^7.9.6",
"@babel/register": "^7.9.0",
"@babel/runtime": "^7.9.6",
"@polkadot/dev": "^0.52.18",
"@polkadot/dev": "^0.52.19",
"@polkadot/ts": "^0.3.21",
"@types/bn.js": "^4.11.6",
"@types/chart.js": "^2.9.20",
@ -47,9 +47,9 @@
"@types/jest": "^25.2.1",
"@types/react-beautiful-dnd": "^12.1.2",
"@types/react-copy-to-clipboard": "^4.3.0",
"@types/react-dom": "^16.9.7",
"@types/react-dom": "^16.9.8",
"@types/react-router-dom": "^5.1.5",
"@types/react-tooltip": "^3.11.0",
"@types/react-tooltip": "^4.2.4",
"@types/store": "^2.0.2",
"@types/styled-components": "^5.1.0",
"@types/styled-theming": "^2.2.2",
@ -61,6 +61,6 @@
"stylelint-config-styled-components": "^0.1.1",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-plugin-serve": "^0.12.1"
"webpack-plugin-serve": "^1.0.0"
}
}

View File

@ -15,7 +15,7 @@
"dependencies": {
"@babel/polyfill": "^7.8.7",
"@babel/runtime": "^7.9.6",
"@polkadot/dev": "^0.52.18",
"@polkadot/dev": "^0.52.19",
"@polkadot/react-components": "0.42.0-beta.112",
"@polkadot/react-signer": "0.42.0-beta.112",
"query-string": "^6.12.1"
@ -27,7 +27,7 @@
"empty": "^0.10.1",
"file-loader": "^6.0.0",
"html-loader": "^1.1.0",
"html-webpack-plugin": "^4.2.1",
"html-webpack-plugin": "^4.3.0",
"markdown-loader": "^5.1.0",
"mini-css-extract-plugin": "^0.9.0",
"source-map-explorer": "^2.4.2",

View File

@ -147,7 +147,8 @@ function createWebpack ({ alias = {}, context, name = 'index' }) {
chunkFilename: '[name].[chunkhash:8].js',
filename: '[name].[hash:8].js',
globalObject: '(typeof self !== \'undefined\' ? self : this)',
path: path.join(context, 'build')
path: path.join(context, 'build'),
publicPath: ''
},
performance: {
hints: false

View File

@ -15,7 +15,7 @@
"@polkadot/react-components": "0.42.0-beta.112",
"@polkadot/react-qr": "^0.53.0-beta.3",
"@polkadot/vanitygen": "^0.12.0-beta.1",
"detect-browser": "^5.0.0",
"detect-browser": "^5.1.0",
"file-saver": "^2.0.2"
}
}

View File

@ -2,16 +2,18 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { DeriveBalancesAll } from '@polkadot/api-derive/types';
import { SubmittableExtrinsic } from '@polkadot/api/types';
import { DeriveBalancesAll, DeriveDemocracyLock } from '@polkadot/api-derive/types';
import { ActionStatus } from '@polkadot/react-components/Status/types';
import { H256, Multisig, RecoveryConfig } from '@polkadot/types/interfaces';
import { SortedAccount } from './types';
import BN from 'bn.js';
import React, { useCallback, useState, useEffect } from 'react';
import React, { useCallback, useContext, useState, useEffect } from 'react';
import styled from 'styled-components';
import { ApiPromise } from '@polkadot/api';
import { getLedger } from '@polkadot/react-api';
import { AddressInfo, AddressMini, AddressSmall, Badge, Button, ChainLock, CryptoType, Forget, Icon, IdentityIcon, LinkExternal, Menu, Popup, Tag } from '@polkadot/react-components';
import { AddressInfo, AddressMini, AddressSmall, Badge, Button, ChainLock, CryptoType, Forget, Icon, IdentityIcon, LinkExternal, Menu, Popup, StatusContext, Tag } from '@polkadot/react-components';
import { useAccountInfo, useApi, useCall, useIncrement, useToggle } from '@polkadot/react-hooks';
import { Option, StorageKey } from '@polkadot/types';
import keyring from '@polkadot/ui-keyring';
@ -34,6 +36,11 @@ interface Props extends SortedAccount {
toggleFavorite: (address: string) => void;
}
interface DemocracyUnlockable {
democracyUnlockTx: SubmittableExtrinsic<'promise'> | null;
ids: BN[];
}
function calcVisible (filter: string, name: string, tags: string[]): boolean {
if (filter.length === 0) {
return true;
@ -46,11 +53,22 @@ function calcVisible (filter: string, name: string, tags: string[]): boolean {
}, name.toLowerCase().includes(_filter));
}
function createClearDemocracyTx (api: ApiPromise, address: string, unlockableIds: BN[]): SubmittableExtrinsic<'promise'> {
return api.tx.utility.batch(
unlockableIds
.map((id) => api.tx.democracy.removeVote(id))
.concat(api.tx.democracy.unlock(address))
);
}
function Account ({ account: { address, meta }, className, filter, isFavorite, setBalance, toggleFavorite }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { queueExtrinsic } = useContext(StatusContext);
const api = useApi();
const [multiInc, refreshMulti] = useIncrement();
const bestNumber = useCall<BN>(api.api.derive.chain.bestNumber, []);
const balancesAll = useCall<DeriveBalancesAll>(api.api.derive.balances.all, [address]);
const democracyLocks = useCall<DeriveDemocracyLock[]>(api.api.derive.democracy.locks, [address]);
const recoveryInfo = useCall<RecoveryConfig | null>(api.api.query.recovery?.recoverable, [address], {
transform: (opt: Option<RecoveryConfig>) => opt.unwrapOr(null)
});
@ -61,6 +79,7 @@ function Account ({ account: { address, meta }, className, filter, isFavorite, s
.map(([key, opt]) => [key.args[1] as H256, opt.unwrap()])
});
const { flags: { isDevelopment, isExternal, isHardware, isInjected, isMultisig }, genesisHash, name: accName, onSetGenesisHash, tags } = useAccountInfo(address);
const [{ democracyUnlockTx }, setUnlockableIds] = useState<DemocracyUnlockable>({ democracyUnlockTx: null, ids: [] });
const [isVisible, setIsVisible] = useState(true);
const [isBackupOpen, toggleBackup] = useToggle();
const [isDeriveOpen, toggleDerive] = useToggle();
@ -83,8 +102,27 @@ function Account ({ account: { address, meta }, className, filter, isFavorite, s
);
}, [accName, filter, tags]);
useEffect((): void => {
bestNumber && democracyLocks && setUnlockableIds(
(prev): DemocracyUnlockable => {
const ids = democracyLocks
.filter(({ isFinished, unlockAt }) => isFinished && bestNumber.gt(unlockAt))
.map(({ referendumId }) => referendumId);
if (JSON.stringify(prev.ids) === JSON.stringify(ids)) {
return prev;
}
return {
democracyUnlockTx: createClearDemocracyTx(api.api, address, ids),
ids
};
}
);
}, [address, api, bestNumber, democracyLocks]);
const _onFavorite = useCallback(
(): void => toggleFavorite(address),
() => toggleFavorite(address),
[address, toggleFavorite]
);
@ -119,6 +157,16 @@ function Account ({ account: { address, meta }, className, filter, isFavorite, s
[refreshMulti, toggleMultisig]
);
const _clearDemocracyLocks = useCallback(
(): void => {
democracyUnlockTx && queueExtrinsic({
accountId: address,
extrinsic: democracyUnlockTx
});
},
[address, democracyUnlockTx, queueExtrinsic]
);
const _showOnHardware = useCallback(
(): void => {
// TODO: we should check the hardwareType from metadata here as well,
@ -312,6 +360,13 @@ function Account ({ account: { address, meta }, className, filter, isFavorite, s
>
{t('Set on-chain identity')}
</Menu.Item>
<Menu.Item
disabled={!democracyUnlockTx}
onClick={_clearDemocracyLocks}
>
{t('Clear expired democracy locks')}
</Menu.Item>
<Menu.Divider />
<Menu.Item
disabled={isExternal || isInjected || isMultisig}
onClick={toggleDerive}

View File

@ -12,6 +12,6 @@
"license": "Apache-2.0",
"dependencies": {
"@babel/runtime": "^7.9.6",
"@polkadot/api-contract": "^1.14.0-beta.6"
"@polkadot/api-contract": "^1.14.0-beta.9"
}
}

View File

@ -31,7 +31,7 @@
"homepage": "https://github.com/polkadot-js/ui/tree/master/packages/ui-reactive#readme",
"dependencies": {
"@babel/runtime": "^7.9.6",
"@polkadot/api": "^1.14.0-beta.6",
"@polkadot/api": "^1.14.0-beta.9",
"@polkadot/extension-dapp": "^0.25.0-beta.6",
"rxjs-compat": "^6.5.5"
}

View File

@ -26,13 +26,13 @@
"react-chartjs-2": "^2.9.0",
"react-copy-to-clipboard": "^5.0.2",
"react-dom": "^16.13.1",
"react-dropzone": "^10.2.2",
"react-dropzone": "^11.0.1",
"react-i18next": "^11.4.0",
"react-is": "^16.13.1",
"react-markdown": "^4.3.1",
"react-router": "^5.1.2",
"react-router-dom": "^5.1.2",
"react-tooltip": "^4.2.5",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-tooltip": "^4.2.6",
"semantic-ui-css": "^2.4.1",
"semantic-ui-react": "^0.88.2",
"store": "^2.0.12",

View File

@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { DeriveBalancesAll, DeriveStakingAccount } from '@polkadot/api-derive/types';
import { DeriveBalancesAll, DeriveDemocracyLock, DeriveStakingAccount } from '@polkadot/api-derive/types';
import { LockIdentifier, ValidatorPrefsTo145 } from '@polkadot/types/interfaces';
import { BareProps } from './types';
@ -15,6 +15,7 @@ import { withCalls, withMulti } from '@polkadot/react-api/hoc';
import { useAccounts } from '@polkadot/react-hooks';
import { FormatBalance } from '@polkadot/react-query';
import DemocracyLocks from './DemocracyLocks';
import StakingRedeemable from './StakingRedeemable';
import StakingUnbonding from './StakingUnbonding';
import CryptoType from './CryptoType';
@ -48,6 +49,7 @@ interface Props extends BareProps {
address: string;
balancesAll?: DeriveBalancesAll;
children?: React.ReactNode;
democracyLocks?: DeriveDemocracyLock[];
extraInfo?: [string, string][];
stakingInfo?: DeriveStakingAccount;
withBalance?: boolean | BalanceActiveType;
@ -214,7 +216,7 @@ function renderValidatorPrefs ({ stakingInfo, withValidatorPrefs = false }: Prop
}
function renderBalances (props: Props, allAccounts: string[], t: (key: string) => string): React.ReactNode {
const { address, balancesAll, stakingInfo, withBalance = true, withBalanceToggle = false } = props;
const { address, balancesAll, democracyLocks, stakingInfo, withBalance = true, withBalanceToggle = false } = props;
const balanceDisplay = withBalance === true
? DEFAULT_BALANCES
: withBalance || false;
@ -329,7 +331,15 @@ function renderBalances (props: Props, allAccounts: string[], t: (key: string) =
<>
<Label label={t('unbonding')} />
<div className='result'>
<StakingUnbonding stakingInfo={stakingInfo} />
<StakingUnbonding value={stakingInfo} />
</div>
</>
)}
{balanceDisplay.unlocking && democracyLocks && (democracyLocks.length !== 0) && (
<>
<Label label={t('democracy')} />
<div className='result'>
<DemocracyLocks value={democracyLocks} />
</div>
</>
)}
@ -467,6 +477,11 @@ export default withMulti(
paramName: 'address',
propName: 'stakingInfo',
skipIf: skipStakingIf
}],
['derive.democracy.locks', {
paramName: 'address',
propName: 'democracyLocks',
skipIf: skipStakingIf
}]
)
);

View File

@ -0,0 +1,89 @@
// Copyright 2017-2020 @polkadot/react-components 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 { DeriveDemocracyLock } from '@polkadot/api-derive/types';
import BN from 'bn.js';
import React, { useState } from 'react';
import styled from 'styled-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { BlockToTime, FormatBalance } from '@polkadot/react-query';
import { bnMax, formatBalance, formatNumber } from '@polkadot/util';
import { useTranslation } from './translate';
import Icon from './Icon';
import Tooltip from './Tooltip';
interface Props {
className?: string;
value?: DeriveDemocracyLock[];
}
const ZERO = new BN(0);
let id = 0;
function DemocracyLocks ({ className, value }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const bestNumber = useCall<BN>(api.derive.chain.bestNumber, []);
const [trigger] = useState(`${Date.now()}-democracy-locks-${++id}`);
if (!value || !value.length || !bestNumber) {
return null;
}
const max = bnMax(...value.map(({ balance }) => balance));
const mapped = value
.map((info): [DeriveDemocracyLock, BN] => [info, info.unlockAt.gt(bestNumber) ? info.unlockAt.sub(bestNumber) : ZERO])
.sort((a, b) => a[1].cmp(b[1]));
return (
<div className={className}>
<Icon
data-for={trigger}
data-tip
name='clock'
/>
<FormatBalance value={max} />
<Tooltip
text={mapped.map(([{ balance, isFinished, referendumId, vote }, blocks], index): React.ReactNode => (
<div
className='row'
key={index}
>
<div>#{referendumId.toString()} {formatBalance(balance, { forceUnit: '-' })} {vote.conviction.toString()}</div>
<div className='faded'>
{blocks.gt(ZERO)
? (
<BlockToTime
blocks={blocks}
label={`${t('{{blocks}} blocks', { replace: { blocks: formatNumber(blocks) } })}, `}
/>
)
: isFinished
? t('lock expired')
: t('ongoing referendum')
}
</div>
</div>
))}
trigger={trigger}
/>
</div>
);
}
export default React.memo(styled(DemocracyLocks)`
white-space: nowrap;
i.icon {
margin-left: 0;
margin-right: 0.25rem;
}
.ui--FormatBalance {
display: inline-block;
}
`);

View File

@ -17,7 +17,7 @@ import { useTranslation } from './translate';
interface Props {
className?: string;
stakingInfo?: DeriveStakingAccount;
value?: DeriveStakingAccount;
}
function remainingBlocks (remainingEras: BN, { eraLength, eraProgress }: DeriveSessionProgress): BN {
@ -27,16 +27,16 @@ function remainingBlocks (remainingEras: BN, { eraLength, eraProgress }: DeriveS
.add(eraLength.sub(eraProgress));
}
function StakingUnbonding ({ className, stakingInfo }: Props): React.ReactElement<Props> | null {
function StakingUnbonding ({ className, value }: Props): React.ReactElement<Props> | null {
const { api } = useApi();
const progress = useCall<DeriveSessionProgress>(api.derive.session.progress, []);
const { t } = useTranslation();
if (!stakingInfo?.unlocking || !progress) {
if (!value?.unlocking || !progress) {
return null;
}
const filtered = stakingInfo.unlocking.filter(({ remainingEras, value }) => value.gtn(0) && remainingEras.gtn(0));
const filtered = value.unlocking.filter(({ remainingEras, value }) => value.gtn(0) && remainingEras.gtn(0));
if (!filtered.length) {
return null;
@ -44,7 +44,7 @@ function StakingUnbonding ({ className, stakingInfo }: Props): React.ReactElemen
const mapped = filtered.map((unlock): [DeriveUnlocking, BN] => [unlock, remainingBlocks(unlock.remainingEras, progress)]);
const total = mapped.reduce((total, [{ value }]) => total.add(value), new BN(0));
const trigger = `${stakingInfo.accountId}-unlocking-trigger`;
const trigger = `${value.accountId}-unlocking-trigger`;
return (
<div className={className}>
@ -61,10 +61,12 @@ function StakingUnbonding ({ className, stakingInfo }: Props): React.ReactElemen
key={index}
>
<div>{t('Unbonding {{value}}, ', { replace: { value: formatBalance(value, { forceUnit: '-' }) } })}</div>
<BlockToTime
blocks={blocks}
label={`${t('{{blocks}} blocks', { replace: { blocks: formatNumber(blocks) } })}, `}
/>
<div className='faded'>
<BlockToTime
blocks={blocks}
label={`${t('{{blocks}} blocks', { replace: { blocks: formatNumber(blocks) } })}, `}
/>
</div>
</div>
))}
trigger={trigger}

View File

@ -93,7 +93,7 @@ export default React.memo(styled(Tooltip)`
.faded {
margin-top: -0.25rem;
opacity: 0.75 !important;
font-size: 0.75em !important;
font-size: 0.85em !important;
}
.faded+.faded {

559
yarn.lock

File diff suppressed because it is too large Load Diff