From fc5e75f01e06870d845c1728d83a9e6c0d5f162a Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Mon, 15 Jun 2020 09:23:40 +0200 Subject: [PATCH] Alert for multisig approvals (#2953) * Alert for multisig approvals * Trigger on multisig events * Allow display/submission of call data --- .../page-accounts/src/Accounts/Account.tsx | 34 +++-- .../src/Accounts/modals/MultisigApprove.tsx | 126 ++++++++++++++---- .../src/Accounts/useMultisigApprovals.ts | 51 +++++++ packages/react-components/src/Output.tsx | 10 +- .../react-components/src/styles/components.ts | 3 +- packages/react-hooks/src/useIncrement.ts | 8 +- packages/react-signer/src/SignFields.tsx | 19 ++- packages/react-signer/src/TxSigned.tsx | 30 ++++- 8 files changed, 223 insertions(+), 58 deletions(-) create mode 100644 packages/page-accounts/src/Accounts/useMultisigApprovals.ts diff --git a/packages/page-accounts/src/Accounts/Account.tsx b/packages/page-accounts/src/Accounts/Account.tsx index d38267f094..6a218f07b2 100644 --- a/packages/page-accounts/src/Accounts/Account.tsx +++ b/packages/page-accounts/src/Accounts/Account.tsx @@ -5,7 +5,7 @@ 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 { RecoveryConfig } from '@polkadot/types/interfaces'; import { SortedAccount } from './types'; import BN from 'bn.js'; @@ -14,8 +14,8 @@ 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, StatusContext, Tags } from '@polkadot/react-components'; -import { useAccountInfo, useApi, useCall, useIncrement, useToggle } from '@polkadot/react-hooks'; -import { Option, StorageKey } from '@polkadot/types'; +import { useAccountInfo, useApi, useCall, useToggle } from '@polkadot/react-hooks'; +import { Option } from '@polkadot/types'; import keyring from '@polkadot/ui-keyring'; import { formatBalance, formatNumber } from '@polkadot/util'; @@ -28,6 +28,7 @@ import MultisigApprove from './modals/MultisigApprove'; import RecoverAccount from './modals/RecoverAccount'; import RecoverSetup from './modals/RecoverSetup'; import Transfer from './modals/Transfer'; +import useMultisigApprovals from './useMultisigApprovals'; interface Props extends SortedAccount { className?: string; @@ -65,19 +66,13 @@ function Account ({ account: { address, meta }, className = '', filter, isFavori const { t } = useTranslation(); const { queueExtrinsic } = useContext(StatusContext); const api = useApi(); - const [multiInc, refreshMulti] = useIncrement(); const bestNumber = useCall(api.api.derive.chain.bestNumber, []); const balancesAll = useCall(api.api.derive.balances.all, [address]); const democracyLocks = useCall(api.api.derive.democracy?.locks, [address]); const recoveryInfo = useCall(api.api.query.recovery?.recoverable, [address], { transform: (opt: Option) => opt.unwrapOr(null) }); - const multiInfos = useCall<[H256, Multisig][]>(multiInc && (api.api.query.multisig || api.api.query.utility)?.multisigs.entries as any, [address], { - transform: (infos: [StorageKey, Option][]): [H256, Multisig][] => - infos - .filter(([, opt]) => opt.isSome) - .map(([key, opt]) => [key.args[1] as H256, opt.unwrap()]) - }); + const multiInfos = useMultisigApprovals(address); const { flags: { isDevelopment, isExternal, isHardware, isInjected, isMultisig }, genesisHash, name: accName, onSetGenesisHash, tags } = useAccountInfo(address); const [{ democracyUnlockTx }, setUnlockableIds] = useState({ democracyUnlockTx: null, ids: [] }); const [isVisible, setIsVisible] = useState(true); @@ -149,14 +144,6 @@ function Account ({ account: { address, meta }, className = '', filter, isFavori [address, t] ); - const _closeMultisig = useCallback( - (): void => { - toggleMultisig(); - refreshMulti(); - }, - [refreshMulti, toggleMultisig] - ); - const _clearDemocracyLocks = useCallback( (): void => { democracyUnlockTx && queueExtrinsic({ @@ -231,6 +218,15 @@ function Account ({ account: { address, meta }, className = '', filter, isFavori type='online' /> )} + {multiInfos && multiInfos.length !== 0 && ( + ('Multisig approvals pending')} + info={multiInfos.length} + isInline + isTooltip + type='brown' + /> + )} @@ -281,7 +277,7 @@ function Account ({ account: { address, meta }, className = '', filter, isFavori { const { t } = useTranslation(); const { api } = useApi(); + const { allAccounts } = useAccounts(); + const [callData, setCallData] = useState(null); const [hash, setHash] = useState(ongoing[0][0].toHex()); - const [multisig, setMultisig] = useState<[H256, Multisig] | null>(null); + const [{ isMultiCall, multisig }, setMultisig] = useState({ isMultiCall: false, multisig: null }); const [others, setOthers] = useState([]); const [signatory, setSignatory] = useState(null); const [whoFilter, setWhoFilter] = useState([]); const [type, setType] = useState('aye'); + const [tx, setTx] = useState | null>(null); const calltypes = useMemo( () => [ { text: t('Approve this call hash'), value: 'aye' }, @@ -46,12 +56,18 @@ function MultisigApprove ({ className = '', onClose, ongoing, threshold, who }: [ongoing] ); + // filter the current multisig by supplied hash useEffect((): void => { - hash && setMultisig( - ongoing.find(([h]) => h.eq(hash)) || null - ); - }, [hash, ongoing]); + const [, multisig] = ongoing.find(([h]) => h.eq(hash)) || [null, null]; + setMultisig({ + isMultiCall: !!multisig && (multisig.approvals.length + 1) >= threshold, + multisig + }); + setCallData(null); + }, [hash, ongoing, threshold]); + + // the others are all the who elements, without the current signatory (re-encoded) useEffect((): void => { setOthers( who @@ -60,11 +76,55 @@ function MultisigApprove ({ className = '', onClose, ongoing, threshold, who }: ); }, [signatory, who]); + // filter the who by those not approved yet that is an actual account we own useEffect((): void => { setWhoFilter( - who.map((w) => registry.createType('AccountId', w).toString()) + who + .map((w) => registry.createType('AccountId', w).toString()) + .filter((w) => multisig && !multisig.approvals.some((a) => a.eq(w)) && allAccounts.some((a) => a === w)) ); - }, [who]); + }, [allAccounts, multisig, who]); + + // based on the type, multisig, others create the tx. This can be either an approval or final call + useEffect((): void => { + const multiMod = api.tx.multisig || api.tx.utility; + + setTx(() => + hash && multisig + ? type === 'aye' + ? isMultiCall + ? callData + ? multiMod.asMulti.meta.args.length === 5 + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + ? multiMod.asMulti(threshold, others, multisig.when, callData, false) + : multiMod.asMulti(threshold, others, multisig.when, callData) + : null + : multiMod.approveAsMulti(threshold, others, multisig.when, hash) + : multiMod.cancelAsMulti(threshold, others, multisig.when, hash) + : null + ); + }, [api, callData, hash, isMultiCall, others, multisig, threshold, type]); + + // when the actual call input changes, create a call and set it + const _setCallData = useCallback( + (callHex: string): void => { + try { + assert(isHex(callHex), 'Hex call data required'); + + const callData = registry.createType('Call', callHex); + + setCallData( + callData.hash.eq(hash) + ? callData + : null + ); + } catch (error) { + setCallData(null); + } + }, + [hash] + ); return ( ('Pending call hashes')} > - ('The signatory to send the approval/cancel from')} - label={t('signatory')} - onChange={setSignatory} - /> ('The call hashes that have not been executed as of yet.')} label={t('pending hashes')} @@ -85,23 +139,41 @@ function MultisigApprove ({ className = '', onClose, ongoing, threshold, who }: options={hashes} value={hash} /> - ('Either approve or reject this call.')} - label={t('approval type')} - onChange={setType} - options={calltypes} - value={type} - /> + {whoFilter.length !== 0 && ( + <> + ('The signatory to send the approval/cancel from')} + label={t('signatory')} + onChange={setSignatory} + /> + ('Either approve or reject this call.')} + label={t('approval type')} + onChange={setType} + options={calltypes} + value={type} + /> + {type === 'aye' && isMultiCall && ( + + )} + + )} diff --git a/packages/page-accounts/src/Accounts/useMultisigApprovals.ts b/packages/page-accounts/src/Accounts/useMultisigApprovals.ts new file mode 100644 index 0000000000..27ae336842 --- /dev/null +++ b/packages/page-accounts/src/Accounts/useMultisigApprovals.ts @@ -0,0 +1,51 @@ +// Copyright 2017-2020 @polkadot/app-accounts 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 { H256, Multisig } from '@polkadot/types/interfaces'; + +import { useContext, useEffect, useState } from 'react'; +import { useApi, useIncrement, useIsMountedRef } from '@polkadot/react-hooks'; +import { EventsContext } from '@polkadot/react-query'; +import { Option, StorageKey } from '@polkadot/types'; + +export default function useMultisigApprovals (address: string): [H256, Multisig][] { + const events = useContext(EventsContext); + const { api } = useApi(); + const [multiInfos, setMultiInfos] = useState<[H256, Multisig][]>([]); + const [trigger, incTrigger] = useIncrement(); + const mountedRef = useIsMountedRef(); + + // increment the trigger by looking at all events + // - filter the by multisig module (old utility is not supported) + // - find anything data item where the type is AccountId + // - increment the trigger when at least one matches our address + useEffect((): void => { + events + .filter(({ record: { event: { section } } }) => section === 'multisig') + .reduce((hasMultisig: boolean, { record: { event: { data } } }) => + data.reduce((hasMultisig: boolean, item) => + hasMultisig || (item.toRawType() === 'AccountId' && item.eq(address)), + hasMultisig), + false) && incTrigger(); + }, [address, events, incTrigger]); + + // query all the entries for the multisig, extracting approvals with their hash + useEffect((): void => { + const multiModule = api.query.multisig || api.query.utility; + + multiModule && multiModule.multisigs && + multiModule.multisigs + .entries(address) + .then((infos: [StorageKey, Option][]): void => { + mountedRef.current && setMultiInfos( + infos + .filter(([, opt]) => opt.isSome) + .map(([key, opt]) => [key.args[1] as H256, opt.unwrap()]) + ); + }) + .catch(console.error); + }, [address, api, mountedRef, trigger]); + + return multiInfos; +} diff --git a/packages/react-components/src/Output.tsx b/packages/react-components/src/Output.tsx index 2291f31420..40df4a4389 100644 --- a/packages/react-components/src/Output.tsx +++ b/packages/react-components/src/Output.tsx @@ -15,25 +15,31 @@ interface Props extends BareProps { children?: React.ReactNode; help?: React.ReactNode; isError?: boolean; + isFull?: boolean; isHidden?: boolean; isMonospace?: boolean; + isTrimmed?: boolean; label?: React.ReactNode; value?: string; withCopy?: boolean; withLabel?: boolean; } -function Output ({ children, className = '', help, isError, isHidden, isMonospace, label, value, withCopy = false, withLabel }: Props): React.ReactElement { +function Output ({ children, className = '', help, isError, isFull, isHidden, isMonospace, isTrimmed, label, value, withCopy = false, withLabel }: Props): React.ReactElement { return (
- {value} + {isTrimmed && value && (value.length > 256) + ? `${value.substr(0, 96)}…${value.substr(-96)}` + : value + } {children} {withCopy ? ( diff --git a/packages/react-components/src/styles/components.ts b/packages/react-components/src/styles/components.ts index 1c76afd4a2..cb0c3b9f23 100644 --- a/packages/react-components/src/styles/components.ts +++ b/packages/react-components/src/styles/components.ts @@ -11,10 +11,9 @@ export default css` border: 1px dashed #eee; box-sizing: border-box; line-height: 1rem; - margin: 0.25rem; padding: .75rem 1rem; position: relative; - word-wrap: break-word; + word-break: break-all; &.error { background: #fff6f6; diff --git a/packages/react-hooks/src/useIncrement.ts b/packages/react-hooks/src/useIncrement.ts index b16ccba777..942732a3df 100644 --- a/packages/react-hooks/src/useIncrement.ts +++ b/packages/react-hooks/src/useIncrement.ts @@ -3,12 +3,16 @@ // of the Apache-2.0 license. See the LICENSE file for details. import { useCallback, useState } from 'react'; +import useIsMountedRef from './useIsMountedRef'; export default function useIncrement (defaultValue = 1): [number, () => void, (value: number) => void] { + const mountedRef = useIsMountedRef(); const [value, setValue] = useState(defaultValue); const increment = useCallback( - (): void => setValue((value: number) => ++value), - [] + (): void => { + mountedRef.current && setValue((value: number) => ++value); + }, + [mountedRef] ); return [value, increment, setValue]; diff --git a/packages/react-signer/src/SignFields.tsx b/packages/react-signer/src/SignFields.tsx index 9202911bab..6ca87c5889 100644 --- a/packages/react-signer/src/SignFields.tsx +++ b/packages/react-signer/src/SignFields.tsx @@ -73,11 +73,20 @@ function SignFields ({ address, onChange, signedTx }: Props): React.ReactElement {!!signedTx && ( - ('Signed transaction')} - value={signedTx} - withCopy - /> + + + ('Signed transaction')} + value={signedTx} + withCopy + /> + + + {t('The actual fully constructed signed output. This can be used for submission via other channels.')} + + )} ); diff --git a/packages/react-signer/src/TxSigned.tsx b/packages/react-signer/src/TxSigned.tsx index 0a9105b8c4..d050313779 100644 --- a/packages/react-signer/src/TxSigned.tsx +++ b/packages/react-signer/src/TxSigned.tsx @@ -15,7 +15,7 @@ import styled from 'styled-components'; import { ApiPromise } from '@polkadot/api'; import { web3FromSource } from '@polkadot/extension-dapp'; import { registry } from '@polkadot/react-api'; -import { Button, ErrorBoundary, Modal, StatusContext, Toggle } from '@polkadot/react-components'; +import { Button, ErrorBoundary, Modal, Output, StatusContext, Toggle } from '@polkadot/react-components'; import { useApi, useToggle } from '@polkadot/react-hooks'; import { Option } from '@polkadot/types'; import keyring from '@polkadot/ui-keyring'; @@ -185,6 +185,7 @@ function TxSigned ({ className, currentItem, requestAddress }: Props): React.Rea const [senderInfo, setSenderInfo] = useState({ isMultiCall: false, multiRoot: null, proxyRoot: null, signAddress: requestAddress, signPassword: '' }); const [signedOptions, setSignedOptions] = useState>({}); const [signedTx, setSignedTx] = useState(null); + const [multiCall, setMultiCall] = useState(null); const [tip, setTip] = useState(BN_ZERO); useEffect((): void => { @@ -192,6 +193,17 @@ function TxSigned ({ className, currentItem, requestAddress }: Props): React.Rea setPasswordError(null); }, [senderInfo]); + // when we are sending the hash only, get the wrapped call for display (proxies if required) + useEffect((): void => { + setMultiCall( + currentItem.extrinsic && senderInfo.multiRoot + ? senderInfo.proxyRoot + ? api.tx.proxy.proxy(senderInfo.proxyRoot, null, currentItem.extrinsic).method.toHex() + : currentItem.extrinsic.method.toHex() + : null + ); + }, [api, currentItem, senderInfo]); + const _addQrSignature = useCallback( ({ signature }: { signature: string }) => qrResolve && qrResolve({ id: ++qrId, @@ -304,6 +316,22 @@ function TxSigned ({ className, currentItem, requestAddress }: Props): React.Rea signedTx={signedTx} /> )} + {isSubmit && !senderInfo.isMultiCall && multiCall && ( + + + ('multisig call data')} + value={multiCall} + withCopy + /> + + + {t('The call data that can be supplied to a final call to multi approvals')} + + + )} ) }