From 2081464de867077453e9d5b50cc411ab31a7951d Mon Sep 17 00:00:00 2001 From: Keith Ingram Date: Wed, 10 Jun 2020 00:56:10 +1200 Subject: [PATCH] Rewrite & update to page-contracts (#2873) * first commit * finish * InputMegaGas, use BN consts' * update util' * tags issue * manifest * import bn_zero * rm * restore contract tags * fix tags onClose * sec to ms * ms -> sec Co-authored-by: Jaco Greeff --- .../page-accounts/src/Accounts/Account.tsx | 9 +- packages/page-accounts/src/Accounts/index.tsx | 3 +- .../src/Accounts/modals/MultisigCreate.tsx | 3 +- .../src/Accounts/modals/Transfer.tsx | 5 +- .../page-accounts/src/Contacts/Address.tsx | 13 +- .../page-accounts/src/Sidebar/Sidebar.tsx | 54 +- packages/page-contracts/src/ABI.tsx | 201 -------- packages/page-contracts/src/CodeRow.tsx | 213 -------- packages/page-contracts/src/Codes/Add.tsx | 177 ++++--- packages/page-contracts/src/Codes/Code.tsx | 278 ++++------- packages/page-contracts/src/Codes/Upload.tsx | 206 ++++---- .../page-contracts/src/Codes/ValidateCode.tsx | 88 ++-- packages/page-contracts/src/Codes/index.tsx | 107 ++-- packages/page-contracts/src/Contracts/Add.tsx | 217 ++++---- .../page-contracts/src/Contracts/Call.tsx | 144 +++--- .../page-contracts/src/Contracts/Contract.tsx | 90 ++-- .../page-contracts/src/Contracts/Outcome.tsx | 9 +- .../page-contracts/src/Contracts/index.tsx | 26 +- .../page-contracts/src/Contracts/util.tsx | 2 +- packages/page-contracts/src/Deploy.tsx | 467 ++++++++---------- packages/page-contracts/src/Modal.tsx | 204 -------- packages/page-contracts/src/RemoveABI.tsx | 2 +- packages/page-contracts/src/constants.ts | 4 +- packages/page-contracts/src/index.tsx | 218 ++++---- packages/page-contracts/src/shared/ABI.tsx | 106 ++++ .../page-contracts/src/shared/CodeRow.tsx | 110 +++++ .../src/shared/InputMegaGas.tsx | 81 +++ .../page-contracts/src/shared/InputName.tsx | 47 ++ .../src/{ => shared}/MessageSignature.tsx | 77 +-- .../src/{ => shared}/Messages.tsx | 8 +- .../src/{ => shared}/Params.tsx | 0 packages/page-contracts/src/shared/index.tsx | 11 + packages/page-contracts/src/types.ts | 19 +- packages/page-contracts/src/useAbi.ts | 87 ++++ packages/page-contracts/src/useWeight.ts | 36 ++ .../src/Motions/ProposeMotion.tsx | 3 +- packages/page-council/src/Overview/Vote.tsx | 4 +- .../src/Overview/DispatchEntry.tsx | 5 +- packages/page-democracy/src/useChangeCalc.ts | 5 +- packages/page-democracy/src/util.ts | 18 +- .../page-explorer/src/NodeInfo/Summary.tsx | 8 +- packages/page-explorer/src/Summary.tsx | 6 +- packages/page-generic-asset/src/AssetCard.tsx | 1 - packages/page-generic-asset/src/AssetRow.tsx | 80 ++- packages/page-generic-asset/src/Transfer.tsx | 3 +- .../page-generic-asset/src/modals/Create.tsx | 5 +- .../page-parachains/src/Overview/Register.tsx | 6 +- .../src/Actions/Account/BondExtra.tsx | 5 +- packages/page-staking/src/Actions/index.tsx | 3 +- .../src/Actions/partials/Validate.tsx | 7 +- .../src/Actions/useUnbondDuration.ts | 5 +- packages/page-staking/src/Payouts/index.tsx | 6 +- .../page-staking/src/Payouts/useEraBlocks.ts | 7 +- packages/page-staking/src/useSortedTargets.ts | 12 +- packages/page-sudo/src/Sudo.tsx | 11 +- packages/page-toolbox/src/Rpc/Account.tsx | 3 +- packages/react-components/src/AddressInfo.tsx | 4 +- packages/react-components/src/AddressRow.tsx | 340 +++---------- packages/react-components/src/Balance.tsx | 3 +- packages/react-components/src/Button/types.ts | 1 - packages/react-components/src/CopyButton.tsx | 12 +- .../react-components/src/DemocracyLocks.tsx | 8 +- packages/react-components/src/EditButton.tsx | 49 ++ packages/react-components/src/Input.tsx | 6 +- .../react-components/src/InputBalance.tsx | 6 +- packages/react-components/src/InputNumber.tsx | 25 +- packages/react-components/src/Row.tsx | 376 +++++--------- .../react-components/src/StakingUnbonding.tsx | 4 +- packages/react-components/src/Tags.tsx | 95 ++++ packages/react-components/src/index.tsx | 2 + .../react-components/src/styles/components.ts | 12 + packages/react-components/src/styles/index.ts | 2 +- packages/react-components/src/types.ts | 2 + packages/react-components/src/util/index.ts | 1 + .../react-components/src/util/timeToString.ts | 20 + packages/react-hooks/src/index.ts | 4 + packages/react-hooks/src/translate.ts | 11 + packages/react-hooks/src/types.ts | 2 + packages/react-hooks/src/useAccountInfo.ts | 96 ++-- packages/react-hooks/src/useBlockTime.ts | 37 ++ packages/react-hooks/src/useContracts.ts | 37 ++ packages/react-hooks/src/useFormField.ts | 15 +- packages/react-hooks/src/useNonEmptyString.ts | 12 + packages/react-hooks/src/useNonZeroBn.ts | 14 + packages/react-params/src/initValue.ts | 9 +- packages/react-query/src/BlockToTime.tsx | 64 +-- .../react-signer/src/Checks/ContractCall.tsx | 5 +- .../src/Checks/ContractDeploy.tsx | 5 +- packages/react-signer/src/Checks/Transfer.tsx | 6 +- packages/react-signer/src/Checks/constants.ts | 22 +- packages/react-signer/src/Modal.tsx | 8 +- yarn.lock | 68 +-- 92 files changed, 2197 insertions(+), 2711 deletions(-) delete mode 100644 packages/page-contracts/src/ABI.tsx delete mode 100644 packages/page-contracts/src/CodeRow.tsx delete mode 100644 packages/page-contracts/src/Modal.tsx create mode 100644 packages/page-contracts/src/shared/ABI.tsx create mode 100644 packages/page-contracts/src/shared/CodeRow.tsx create mode 100644 packages/page-contracts/src/shared/InputMegaGas.tsx create mode 100644 packages/page-contracts/src/shared/InputName.tsx rename packages/page-contracts/src/{ => shared}/MessageSignature.tsx (61%) rename packages/page-contracts/src/{ => shared}/Messages.tsx (96%) rename packages/page-contracts/src/{ => shared}/Params.tsx (100%) create mode 100644 packages/page-contracts/src/shared/index.tsx create mode 100644 packages/page-contracts/src/useAbi.ts create mode 100644 packages/page-contracts/src/useWeight.ts create mode 100644 packages/react-components/src/EditButton.tsx create mode 100644 packages/react-components/src/Tags.tsx create mode 100644 packages/react-components/src/util/timeToString.ts create mode 100644 packages/react-hooks/src/translate.ts create mode 100644 packages/react-hooks/src/useBlockTime.ts create mode 100644 packages/react-hooks/src/useContracts.ts create mode 100644 packages/react-hooks/src/useNonEmptyString.ts create mode 100644 packages/react-hooks/src/useNonZeroBn.ts diff --git a/packages/page-accounts/src/Accounts/Account.tsx b/packages/page-accounts/src/Accounts/Account.tsx index f1b34be5ec..db39169edc 100644 --- a/packages/page-accounts/src/Accounts/Account.tsx +++ b/packages/page-accounts/src/Accounts/Account.tsx @@ -13,7 +13,7 @@ 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, StatusContext, Tag } from '@polkadot/react-components'; +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 keyring from '@polkadot/ui-keyring'; @@ -312,12 +312,7 @@ function Account ({ account: { address, meta }, className = '', filter, isFavori
- {tags.map((tag): React.ReactNode => ( - - ))} +
diff --git a/packages/page-accounts/src/Accounts/index.tsx b/packages/page-accounts/src/Accounts/index.tsx index 1d9d2c0395..96d825fb6c 100644 --- a/packages/page-accounts/src/Accounts/index.tsx +++ b/packages/page-accounts/src/Accounts/index.tsx @@ -14,6 +14,7 @@ import { getLedger, isLedger } from '@polkadot/react-api'; import { useApi, useAccounts, useFavorites, useIpfs, useToggle } from '@polkadot/react-hooks'; import { FormatBalance } from '@polkadot/react-query'; import { Button, Input, Table } from '@polkadot/react-components'; +import { BN_ZERO } from '@polkadot/util'; import { useTranslation } from '../translate'; import CreateModal from './modals/Create'; @@ -118,7 +119,7 @@ function Overview ({ className = '', onStatusChange }: Props): React.ReactElemen return { accounts, - balanceTotal: Object.values(accounts).reduce((total: BN, value: BN) => total.add(value), new BN(0)) + balanceTotal: Object.values(accounts).reduce((total: BN, value: BN) => total.add(value), BN_ZERO) }; }), [] diff --git a/packages/page-accounts/src/Accounts/modals/MultisigCreate.tsx b/packages/page-accounts/src/Accounts/modals/MultisigCreate.tsx index b2d5927fd5..cb77d72ee6 100644 --- a/packages/page-accounts/src/Accounts/modals/MultisigCreate.tsx +++ b/packages/page-accounts/src/Accounts/modals/MultisigCreate.tsx @@ -10,6 +10,7 @@ import React, { useCallback, useState } from 'react'; import { Button, Input, InputAddressMulti, InputNumber, Modal } from '@polkadot/react-components'; import { useApi } from '@polkadot/react-hooks'; import keyring from '@polkadot/ui-keyring'; +import { BN_ONE } from '@polkadot/util'; import { useTranslation } from '../../translate'; import useKnownAddresses from '../useKnownAddresses'; @@ -52,7 +53,7 @@ function Multisig ({ className = '', onClose, onStatusChange }: Props): React.Re const availableSignatories = useKnownAddresses(); const [{ isNameValid, name }, setName] = useState({ isNameValid: false, name: '' }); const [signatories, setSignatories] = useState(['']); - const [{ isThresholdValid, threshold }, setThreshold] = useState({ isThresholdValid: true, threshold: new BN(1) }); + const [{ isThresholdValid, threshold }, setThreshold] = useState({ isThresholdValid: true, threshold: BN_ONE }); const _createMultisig = useCallback( (): void => { diff --git a/packages/page-accounts/src/Accounts/modals/Transfer.tsx b/packages/page-accounts/src/Accounts/modals/Transfer.tsx index 14244b63ea..174e979085 100644 --- a/packages/page-accounts/src/Accounts/modals/Transfer.tsx +++ b/packages/page-accounts/src/Accounts/modals/Transfer.tsx @@ -8,6 +8,7 @@ import styled from 'styled-components'; import { InputAddress, InputBalance, Modal, TxButton } from '@polkadot/react-components'; import { useApi } from '@polkadot/react-hooks'; import { Available } from '@polkadot/react-query'; +import { BN_ZERO } from '@polkadot/util'; import { useTranslation } from '../../translate'; @@ -21,9 +22,9 @@ interface Props { function Transfer ({ className = '', onClose, recipientId: propRecipientId, senderId: propSenderId }: Props): React.ReactElement { const { t } = useTranslation(); const { api } = useApi(); - const [amount, setAmount] = useState(new BN(0)); + const [amount, setAmount] = useState(BN_ZERO); const [hasAvailable] = useState(true); - const [maxBalance] = useState(new BN(0)); + const [maxBalance] = useState(BN_ZERO); const [recipientId, setRecipientId] = useState(propRecipientId || null); const [senderId, setSenderId] = useState(propSenderId || null); diff --git a/packages/page-accounts/src/Contacts/Address.tsx b/packages/page-accounts/src/Contacts/Address.tsx index 5798626e14..7680e771c5 100644 --- a/packages/page-accounts/src/Contacts/Address.tsx +++ b/packages/page-accounts/src/Contacts/Address.tsx @@ -5,10 +5,11 @@ import { DeriveAccountInfo, DeriveBalancesAll } from '@polkadot/api-derive/types'; import { KeyringAddress } from '@polkadot/ui-keyring/types'; import { ActionStatus } from '@polkadot/react-components/Status/types'; +import { BareProps } from '@polkadot/react-components/types'; import React, { useCallback, useEffect, useState } from 'react'; import styled from 'styled-components'; -import { AddressSmall, AddressInfo, Button, ChainLock, Icon, LinkExternal, Forget, Menu, Popup, Tag } from '@polkadot/react-components'; +import { AddressSmall, AddressInfo, Button, ChainLock, Icon, LinkExternal, Forget, Menu, Popup, Tags } from '@polkadot/react-components'; import { useApi, useCall } from '@polkadot/react-hooks'; import keyring from '@polkadot/ui-keyring'; import { formatNumber } from '@polkadot/util'; @@ -16,9 +17,8 @@ import { formatNumber } from '@polkadot/util'; import Transfer from '../Accounts/modals/Transfer'; import { useTranslation } from '../translate'; -interface Props { +interface Props extends BareProps { address: string; - className?: string; filter: string; isFavorite: boolean; toggleFavorite: (address: string) => void; @@ -180,12 +180,7 @@ function Address ({ address, className = '', filter, isFavorite, toggleFavorite
- {tags.map((tag): React.ReactNode => ( - - ))} +
diff --git a/packages/page-accounts/src/Sidebar/Sidebar.tsx b/packages/page-accounts/src/Sidebar/Sidebar.tsx index 5a03942b63..41e43c118e 100644 --- a/packages/page-accounts/src/Sidebar/Sidebar.tsx +++ b/packages/page-accounts/src/Sidebar/Sidebar.tsx @@ -8,7 +8,7 @@ import React, { useCallback } from 'react'; import styled from 'styled-components'; import { useAccountInfo, useToggle } from '@polkadot/react-hooks'; import { colorLink } from '@polkadot/react-components/styles/theme'; -import { AccountName, Button, Icon, IdentityIcon, Input, InputTags, LinkExternal, Tag } from '@polkadot/react-components'; +import { AccountName, Button, Icon, IdentityIcon, Input, LinkExternal, Tags } from '@polkadot/react-components'; import Transfer from '../Accounts/modals/Transfer'; import { useTranslation } from '../translate'; @@ -22,10 +22,6 @@ interface Props extends BareProps { onUpdateName: () => void; } -const TAG_OPTS = { - autoFocus: true -}; - function Sidebar ({ address, className = '', onClose, onUpdateName }: Props): React.ReactElement { const { t } = useTranslation(); const { flags, identity, isEditingName, isEditingTags, meta, name, onForgetAddress, onSaveName, onSaveTags, setName, setTags, tags, toggleIsEditingName, toggleIsEditingTags } = useAccountInfo(address); @@ -94,45 +90,15 @@ function Sidebar ({ address, className = '', onClose, onUpdateName }: Props): Re )}
- {isEditingTags - ? ( - - ) - : ( -
- {tags.length - ? tags.map((tag): React.ReactNode => ( - - )) - : - } -
- ) - } - {(!isEditingTags && (flags.isInContacts || flags.isOwned)) && ( - - )} +
diff --git a/packages/page-contracts/src/ABI.tsx b/packages/page-contracts/src/ABI.tsx deleted file mode 100644 index 4505ce6168..0000000000 --- a/packages/page-contracts/src/ABI.tsx +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright 2017-2020 @polkadot/app-contracts 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 { ContractABIPre } from '@polkadot/api-contract/types'; -import { I18nProps } from '@polkadot/react-components/types'; - -import React from 'react'; -import styled from 'styled-components'; -import { Abi } from '@polkadot/api-contract'; -import { registry } from '@polkadot/react-api'; -import { InputFile, Labelled } from '@polkadot/react-components'; -import { u8aToString } from '@polkadot/util'; - -import Messages from './Messages'; -import translate from './translate'; - -interface Props extends I18nProps { - className?: string; - contractAbi?: Abi | null; - errorText?: string | null; - help?: React.ReactNode; - isError?: boolean; - isDisabled?: boolean; - isRequired?: boolean; - label?: React.ReactNode; - onChange: (json: string | null, contractAbi: Abi | null) => void; - onRemove?: () => void; - onRemoved?: () => void; - onSelect?: () => void; - onSelectConstructor?: (constructorIndex?: number) => void; -} - -interface State { - contractAbi: Abi | null; - errorText: string | null; - isAbiValid: boolean; - isEmpty: boolean; - isError: boolean; -} - -class ABI extends React.PureComponent { - public state: State = { - contractAbi: null, - errorText: null, - isAbiValid: false, - isEmpty: true, - isError: false - }; - - constructor (props: Props) { - super(props); - - const { contractAbi, isError, isRequired } = this.props; - const isAbiValid = !!contractAbi; - - this.state = { - contractAbi: contractAbi || null, - errorText: null, - isAbiValid, - isEmpty: !isAbiValid, - isError: isError || (isRequired && !isAbiValid) || false - }; - } - - public static getDerivedStateFromProps ({ contractAbi }: Props): Pick | null { - if (contractAbi) { - return { - contractAbi, - isAbiValid: true, - isError: false - }; - } - - return null; - } - - public render (): React.ReactNode { - const { className } = this.props; - const { contractAbi, isAbiValid } = this.state; - - return ( -
- { - (contractAbi && isAbiValid) - ? this.renderMessages() - : this.renderInputFile() - } -
- ); - } - - private renderInputFile (): React.ReactNode { - const { className = '', help, isDisabled, isRequired, label, t } = this.props; - const { errorText, isAbiValid, isEmpty, isError } = this.state; - - return ( -
- - {t('invalid ABI file selected')} - {!!errorText && ( - <> - {' — '} - {t(errorText)} - - )} - - ) - : t('click to select or drag and drop a JSON ABI file') - } - /> -
- ); - } - - private renderMessages (): React.ReactNode { - const { help, isDisabled, label, onRemove, onSelectConstructor } = this.props; - const { contractAbi } = this.state; - - if (!contractAbi) { - return null; - } - - return ( - - - - ); - } - - private onChange = (u8a: Uint8Array): void => { - const { onChange, t } = this.props; - const json = u8aToString(u8a); - - try { - const abi = JSON.parse(json) as ContractABIPre; - - if ((abi as unknown as Record).deploy || (abi as unknown as Record).messages) { - throw new Error(t('You are using an ABI with an outdated format. Please generate a new one.')); - } - - const contractAbi = new Abi(registry, abi); - - this.setState({ - contractAbi, - isAbiValid: true, - isEmpty: false, - isError: false - }, (): void => onChange(json, contractAbi)); - } catch (error) { - console.error(error); - - this.setState({ - errorText: error as string, - isAbiValid: false, - isEmpty: false, - isError: true - }, (): void => onChange(null, null)); - } - } - - private onRemove = (): void => { - const { onChange, onRemoved } = this.props; - - this.setState( - { - contractAbi: null, - isAbiValid: false, - isEmpty: true - }, - (): void => { - onChange(null, null); - onRemoved && onRemoved(); - } - ); - } -} - -export default translate(styled(ABI as React.ComponentClass)` - min-height: 4rem; -`); diff --git a/packages/page-contracts/src/CodeRow.tsx b/packages/page-contracts/src/CodeRow.tsx deleted file mode 100644 index f72f88c21f..0000000000 --- a/packages/page-contracts/src/CodeRow.tsx +++ /dev/null @@ -1,213 +0,0 @@ -// 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. - -/* eslint-disable camelcase */ - -import { I18nProps } from '@polkadot/react-components/types'; -import { CodeStored } from '@polkadot/app-contracts/types'; - -import React from 'react'; -import styled from 'styled-components'; -import { createType } from '@polkadot/types'; -import { registry } from '@polkadot/react-api'; -import { withMulti } from '@polkadot/react-api/hoc'; -import { classes, toShortAddress } from '@polkadot/react-components/util'; -import Row, { RowProps, RowState, styles } from '@polkadot/react-components/Row'; -import { CopyButton, Icon } from '@polkadot/react-components'; - -import contracts from './store'; -import Messages from './Messages'; -import translate from './translate'; - -interface Props extends I18nProps, RowProps { - code: CodeStored; - withMessages?: boolean; -} - -interface State extends RowState { - codeHash: string; -} - -const DEFAULT_HASH = '0x'; -const DEFAULT_NAME = ''; - -const CodeIcon = styled.div` - & { - margin-right: 1em; - background: #eee; - color: #666; - width: 4rem; - height: 5rem; - padding: 0.5rem; - display: flex; - justify-content: flex-end; - align-items: flex-end; - } -`; - -const DEFAULT_ADDR = '5'.padEnd(16, 'x'); - -class CodeRow extends Row { - public state: State; - - constructor (props: Props) { - super(props); - - this.state = this.createState(); - } - - public static getDerivedStateFromProps ({ accountsInfo, code: { json } }: Props, prevState: State): State | null { - const codeHash = json.codeHash || DEFAULT_HASH; - const name = json.name || DEFAULT_NAME; - const tags = json.tags || []; - const { accountId } = accountsInfo || {}; - const address = accountId - ? accountId.toString() - : DEFAULT_ADDR; - - const state: Partial = { tags }; - let hasChanged = false; - - if (codeHash !== prevState.codeHash) { - state.codeHash = codeHash; - hasChanged = true; - } - - if (!prevState.isEditingName && name !== prevState.name) { - state.name = name; - hasChanged = true; - } - - if (address !== prevState.address) { - state.address = address; - hasChanged = true; - } - - return hasChanged - ? state as State - : null; - } - - public render (): React.ReactNode { - const { className = '', isInline } = this.props; - - return ( -
-
- {this.renderIcon()} -
- {this.renderName()} - {this.renderCodeHash()} - {this.renderTags()} -
- {this.renderButtons()} -
- {this.renderMessages()} - {this.renderChildren()} -
- ); - } - - private createState (): State { - const { code: { json: { codeHash = DEFAULT_HASH, name = DEFAULT_NAME, tags = [] } } } = this.props; - - return { - address: DEFAULT_ADDR, - codeHash, - isEditingName: false, - isEditingTags: false, - name, - tags - }; - } - - protected renderCodeHash (): React.ReactNode { - const { codeHash } = this.state; - - return ( - <> -
- {name} -
-
- - {toShortAddress(codeHash)} - -
- - ); - } - - protected renderButtons (): React.ReactNode { - const { buttons } = this.props; - - if (!buttons) { - return null; - } - - return ( -
- {buttons} -
- ); - } - - protected renderIcon (): React.ReactNode { - return ( - - - - ); - } - - protected renderMessages (): React.ReactNode { - const { code: { contractAbi }, withMessages } = this.props; - - if (!withMessages || !contractAbi) { - return null; - } - - return ( - - ); - } - - protected saveName = async (): Promise => { - const { codeHash, name } = this.state; - const trimmedName = name.trim(); - - // Save only if the name was changed or if it's no empty. - if (trimmedName && codeHash) { - await contracts.saveCode(createType(registry, 'Hash', codeHash), { name }); - - this.setState({ isEditingName: false }); - } - } - - protected saveTags = async (): Promise => { - const { codeHash, tags } = this.state; - - if (codeHash) { - await contracts.saveCode(createType(registry, 'Hash', codeHash), { tags }); - - this.setState({ isEditingTags: false }); - } - } -} - -export default withMulti( - styled(CodeRow as React.ComponentClass)` - ${styles} - `, - translate -); diff --git a/packages/page-contracts/src/Codes/Add.tsx b/packages/page-contracts/src/Codes/Add.tsx index c2b89f0102..9cfa49f836 100644 --- a/packages/page-contracts/src/Codes/Add.tsx +++ b/packages/page-contracts/src/Codes/Add.tsx @@ -2,111 +2,106 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import React from 'react'; +import { StringOrNull } from '@polkadot/react-components/types'; + +import React, { useCallback, useMemo, useState } from 'react'; import { createType } from '@polkadot/types'; import { registry } from '@polkadot/react-api'; -import { Button, Input } from '@polkadot/react-components'; +import { Button, Input, Modal } from '@polkadot/react-components'; +import { useToggle } from '@polkadot/react-hooks'; +import { isNull } from '@polkadot/util'; +import { ABI, InputName } from '../shared'; -import ContractModal, { ContractModalProps as Props, ContractModalState } from '../Modal'; import ValidateCode from './ValidateCode'; import store from '../store'; -import translate from '../translate'; +import { useTranslation } from '../translate'; +import useAbi from '../useAbi'; -interface State extends ContractModalState { - codeHash: string; - isBusy: boolean; - isCodeValid: boolean; -} +function Add (): React.ReactElement { + const { t } = useTranslation(); + const [isOpen, toggleIsOpen, setIsOpen] = useToggle(); + const [codeHash, setCodeHash] = useState(''); + const [isCodeHashValid, setIsCodeHashValid] = useState(false); + const [name, setName] = useState(null); + const { abi, contractAbi, errorText, isAbiError, isAbiSupplied, isAbiValid, onChangeAbi, onRemoveAbi } = useAbi(); -class Add extends ContractModal { - constructor (props: Props) { - super(props); - this.defaultState = { - ...this.defaultState, - codeHash: '', - isBusy: false, - isCodeValid: false - }; - this.state = this.defaultState; - this.headerText = props.t('Add an existing code hash'); - } + const isNameValid = useMemo( + (): boolean => !isNull(name) && name.length > 0, + [name] + ); - protected renderContent = (): React.ReactNode => { - const { t } = this.props; - const { codeHash, isBusy, isCodeValid } = this.state; + const isValid = useMemo( + (): boolean => isCodeHashValid && isNameValid, + [isCodeHashValid, isNameValid] + ); - return ( - <> - ('The code hash for the on-chain deployed code.')} - isDisabled={isBusy} - isError={!isCodeValid} - label={t('code hash')} - onChange={this.onChangeHash} - onEnter={this.submit} - value={codeHash} - /> - - {this.renderInputName()} - {this.renderInputAbi()} - - ); - } + const _onSave = useCallback( + (): void => { + if (!codeHash || !name) { + return; + } - protected renderButtons = (): React.ReactNode => { - const { t } = this.props; - const { isBusy, isCodeValid, isNameValid } = this.state; - const isValid = !isBusy && isCodeValid && isNameValid; - - return ( -
)} {hasRpc && ( ('send as RPC call') @@ -213,10 +217,10 @@ function Call (props: Props): React.ReactElement | null { icon='sign-in' isDisabled={!isValid} isPrimary - label={t('Call')} - onClick={_toggleBusy} - onFailed={_toggleBusy} - onSuccess={_toggleBusy} + label={t('Call')} + onClick={(): void => setIsBusy(true)} + onFailed={(): void => setIsBusy(false)} + onSuccess={(): void => setIsBusy(false)} params={_constructTx} tx='contracts.call' withSpinner diff --git a/packages/page-contracts/src/Contracts/Contract.tsx b/packages/page-contracts/src/Contracts/Contract.tsx index 8df0bf457c..d28be2a168 100644 --- a/packages/page-contracts/src/Contracts/Contract.tsx +++ b/packages/page-contracts/src/Contracts/Contract.tsx @@ -2,73 +2,65 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +import { BareProps } from '@polkadot/react-components/types'; import { ActionStatus } from '@polkadot/react-components/Status/types'; -import React, { useState } from 'react'; +import React, { useCallback } from 'react'; import styled from 'styled-components'; -import { RouteComponentProps } from 'react-router'; -import { withRouter } from 'react-router-dom'; import keyring from '@polkadot/ui-keyring'; import { PromiseContract as ApiContract } from '@polkadot/api-contract'; import { AddressRow, Button, Card, Expander, Forget } from '@polkadot/react-components'; +import { useToggle } from '@polkadot/react-hooks'; -import Messages from '../Messages'; +import Messages from '../shared/Messages'; import { useTranslation } from '../translate'; -interface Props extends RouteComponentProps { - basePath: string; +interface Props extends BareProps { contract: ApiContract; onCall: (_?: number) => () => void; } -const ContractCard = styled(Card)` - && { - min-width: 100%; - max-width: 100%; - } -`; - -function Contract (props: Props): React.ReactElement | null { +function Contract ({ className, contract: { abi, address }, onCall }: Props): React.ReactElement | null { const { t } = useTranslation(); - const { contract: { abi, address }, onCall } = props; - const [isForgetOpen, setIsForgetOpen] = useState(false); + const [isForgetOpen, toggleIsForgetOpen] = useToggle(); + + const _onForget = useCallback( + (): void => { + if (!address) { + return; + } + + const status: Partial = { + account: address, + action: 'forget' + }; + + try { + keyring.forgetContract(address.toString()); + status.status = 'success'; + status.message = t('address forgotten'); + } catch (error) { + status.status = 'error'; + status.message = (error as Error).message; + } + + toggleIsForgetOpen(); + }, + [address, t, toggleIsForgetOpen] + ); if (!address || !abi) { return null; } - const _toggleForget = (): void => setIsForgetOpen(!isForgetOpen); - - const _onForget = (): void => { - if (!address) { - return; - } - - const status: Partial = { - account: address, - action: 'forget' - }; - - try { - keyring.forgetContract(address.toString()); - status.status = 'success'; - status.message = t('address forgotten'); - } catch (error) { - status.status = 'error'; - status.message = (error as Error).message; - } - - _toggleForget(); - }; - return ( - + {isForgetOpen && ( )} @@ -78,7 +70,7 @@ function Contract (props: Props): React.ReactElement | null {