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 {
('Forget this contract')}
/>
| null {
}
isContract
- isEditable
+ isEditableName
+ isEditableTags
type='contract'
value={address}
withBalance={false}
@@ -107,8 +100,13 @@ function Contract (props: Props): React.ReactElement | null {
/>
-
+
);
}
-export default withRouter(Contract);
+export default React.memo(
+ styled(Contract)`
+ min-width: 100%;
+ max-width: 100%;
+ `
+);
diff --git a/packages/page-contracts/src/Contracts/Outcome.tsx b/packages/page-contracts/src/Contracts/Outcome.tsx
index c1b30f1d97..2035592dd3 100644
--- a/packages/page-contracts/src/Contracts/Outcome.tsx
+++ b/packages/page-contracts/src/Contracts/Outcome.tsx
@@ -3,21 +3,20 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { ContractCallOutcome } from '@polkadot/api-contract/types';
+import { BareProps } from '@polkadot/react-components/types';
import React from 'react';
import styled from 'styled-components';
import { AddressMini, Button, Output } from '@polkadot/react-components';
-import MessageSignature from '../MessageSignature';
+import MessageSignature from '../shared/MessageSignature';
-interface Props {
- className?: string;
+interface Props extends BareProps {
onClear?: () => void;
outcome: ContractCallOutcome;
}
-function Outcome (props: Props): React.ReactElement | null {
- const { className = '', onClear, outcome: { isSuccess, message, origin, output, params, time } } = props;
+function Outcome ({ className = '', onClear, outcome: { isSuccess, message, origin, output, params, time } }: Props): React.ReactElement | null {
const dateTime = new Date(time);
return (
diff --git a/packages/page-contracts/src/Contracts/index.tsx b/packages/page-contracts/src/Contracts/index.tsx
index d6923fb6a0..fd54d7ce3e 100644
--- a/packages/page-contracts/src/Contracts/index.tsx
+++ b/packages/page-contracts/src/Contracts/index.tsx
@@ -18,19 +18,18 @@ import Call from './Call';
import { getContractForAddress } from './util';
function filterContracts (api: ApiPromise, { accounts, contracts: keyringContracts }: Props): ApiContract[] {
- return accounts && keyringContracts && Object.keys(keyringContracts)
- .map((address): ApiContract | null => getContractForAddress(api, address))
+ return accounts && keyringContracts && keyringContracts
+ .map((address): ApiContract | null => getContractForAddress(api, address.toString()))
.filter((contract: ApiContract | null): boolean => !!contract) as ApiContract[];
}
function Contracts (props: Props): React.ReactElement {
const { t } = useTranslation();
const { api } = useApi();
- const { accounts, basePath, contracts: keyringContracts, hasCode, showDeploy } = props;
+ const { accounts, contracts: keyringContracts, hasCode, onShowDeploy } = props;
const [contracts, setContracts] = useState(filterContracts(api, props));
const [callContractIndex, setCallContractIndex] = useState(0);
const [callMessageIndex, setCallMessageIndex] = useState(0);
- const [isAddOpen, setIsAddOpen] = useState(false);
const [isCallOpen, setIsCallOpen] = useState(false);
useEffect((): void => {
@@ -39,7 +38,6 @@ function Contracts (props: Props): React.ReactElement {
const callContract = contracts[callContractIndex] || null;
- const _toggleAdd = (): void => setIsAddOpen(!isAddOpen);
const _toggleCall = (): void => setIsCallOpen(!isCallOpen);
const _onChangeCallContractAddress = (newCallContractAddress: StringOrNull): void => {
@@ -69,37 +67,27 @@ function Contracts (props: Props): React.ReactElement {
<>
+
{hasCode && (
('Deploy a code hash')}
- onClick={showDeploy()}
+ label={t('Deploy a code hash')}
+ onClick={onShowDeploy()}
/>
)}
- ('Add an existing contract')}
- onClick={_toggleAdd}
- />
+
}
emptyText={t('No contracts available')}
>
{contracts.map((contract: ApiContract, index): React.ReactNode => (
))}
-
;
+ setConstructorIndex: React.Dispatch;
}
-interface State extends ContractModalState {
- codeHash?: string;
- constructorIndex: number;
- constructOptions: ConstructOptions;
- endowment: BN;
- isHashValid: boolean;
- params: any[];
+function defaultContractName (name: string) {
+ return `${name} (instance)`;
}
-class Deploy extends ContractModal {
- protected headerText = 'Deploy a new contract';
+function Deploy ({ allCodes, basePath, codeHash, constructorIndex = 0, isOpen, onClose, setCodeHash, setConstructorIndex }: Props): React.ReactElement {
+ const { t } = useTranslation();
+ const { api } = useApi();
+ const history = useHistory();
+ const useWeightHook = useWeight();
+ const { isValid: isWeightValid, weight } = useWeightHook;
- public isContract = true;
+ const code = useMemo(
+ (): CodeStored => store.getCode(codeHash),
+ [codeHash]
+ );
+ const [accountId, isAccountIdValid, setAccountId] = useFormField(null);
+ const [endowment, isEndowmentValid, setEndowment] = useNonZeroBn(new BN(ENDOWMENT));
+ const [name, isNameValid, setName] = useNonEmptyString(t(defaultContractName(code.json.name)));
+ const { abi, contractAbi, errorText, isAbiError, isAbiSupplied, isAbiValid, onChangeAbi, onRemoveAbi } = useAbi([code.json.abi || null, code.contractAbi || null], codeHash, true);
- constructor (props: Props) {
- super(props);
-
- this.defaultState = {
- ...this.defaultState,
- constructOptions: [],
- constructorIndex: -1,
- endowment: new BN(ENDOWMENT),
- gasLimit: new BN(DEFAULT_GAS_LIMIT),
- isHashValid: false,
- params: [],
- ...Deploy.getCodeState(props.codeHash)
- };
- this.state = this.defaultState;
- }
-
- public static getDerivedStateFromProps (props: Props, state: State): Pick {
- if (props.codeHash && (!state.codeHash || state.codeHash !== props.codeHash)) {
- return Deploy.getCodeState(props.codeHash, Math.max(props.constructorIndex || 0));
- }
-
- return {};
- }
-
- private static getContractAbiState = (abi: string | null | undefined, contractAbi: Abi | null = null, constructorIndex = 0): Partial => {
- if (contractAbi) {
- return {
- abi,
- constructorIndex,
- contractAbi,
- isAbiValid: !!contractAbi,
- ...Deploy.getConstructorState(contractAbi, Math.max(constructorIndex, 0))
- };
- } else {
- return {
- abi: null,
- constructOptions: [] as ConstructOptions,
- constructorIndex: -1,
- contractAbi: null,
- isAbiSupplied: false,
- isAbiValid: false,
- ...Deploy.getConstructorState()
- };
- }
- }
-
- private static getCodeState = (codeHash: string | null = null, constructorIndex = 0): Pick => {
- if (codeHash) {
- const code = store.getCode(codeHash);
-
- if (code) {
- const { contractAbi, json } = code;
-
- return {
- codeHash,
- isAbiSupplied: !!contractAbi,
- isHashValid: true,
- isNameValid: true,
- name: `${json.name} (instance)`,
- ...Deploy.getContractAbiState(json.abi, contractAbi, Math.max(constructorIndex, 0))
- };
- }
- }
-
- return {};
- }
-
- private static getConstructorState = (contractAbi: Abi | null = null, ci = 0): Pick => {
- const constructorIndex = Math.max(ci, 0);
-
- if (!contractAbi || constructorIndex < 0 || constructorIndex >= contractAbi.constructors.length) {
- return {
- constructOptions: [],
- constructorIndex: -1,
- params: []
- };
- }
-
- const { abi: { contract: { constructors } } } = contractAbi;
- const constructor = constructors[constructorIndex];
- const constructOptions: ConstructOptions = constructors.map(
- (constr, index) => {
- return {
- key: `${index}`,
- text: (
-
- ),
- value: `${index}`
- };
- });
-
- return {
- constructOptions,
- constructorIndex,
- params: createValues(constructor.args)
- };
- }
-
- protected renderContent = (): React.ReactNode => {
- const { t } = this.props;
- const { codeHash, constructOptions, constructorIndex, contractAbi, endowment, isAbiSupplied, isBusy, isHashValid } = this.state;
-
- const codeOptions = store.getAllCode().map(({ json: { codeHash, name } }): { text: string; value: string } => ({
+ const isValid = useMemo(
+ (): boolean => isNameValid && isEndowmentValid && isWeightValid && isAccountIdValid,
+ [isAccountIdValid, isEndowmentValid, isNameValid, isWeightValid]
+ );
+ const codeOptions = useMemo(
+ (): CodeOptions => allCodes.map(({ json: { codeHash, name } }): { text: string; value: string } => ({
text: `${name} (${codeHash})`,
value: codeHash
- }));
+ })),
+ [allCodes]
+ );
- const defaultCode = codeOptions.length
- ? codeOptions[codeOptions.length - 1].value
- : undefined;
+ const constructOptions = useMemo(
+ (): ConstructOptions => {
+ if (!contractAbi) {
+ return [];
+ }
- return (
- <>
- {this.renderInputAccount()}
+ return contractAbi.abi.contract.constructors.map(
+ (constr, index) => {
+ return {
+ key: `${index}`,
+ text: (
+
+ ),
+ value: `${index}`
+ };
+ });
+ },
+ [contractAbi]
+ );
+
+ const [params, setParams] = useState(
+ contractAbi && constructorIndex >= 0 ? contractAbi.abi.contract.constructors[constructorIndex].args : []
+ );
+
+ useEffect(
+ (): void => {
+ setParams(contractAbi ? contractAbi.abi.contract.constructors[constructorIndex].args : []);
+ },
+ [constructorIndex, contractAbi]
+ );
+
+ useEffect(
+ (): void => {
+ setName(t(defaultContractName(code.json.name)));
+ },
+ [code, setName, t]
+ );
+
+ const _constructCall = useCallback(
+ (): any[] => {
+ if (!contractAbi || constructorIndex < 0) {
+ return [];
+ }
+
+ return [endowment, weight, codeHash, contractAbi.constructors[constructorIndex](...params)];
+ },
+ [codeHash, constructorIndex, contractAbi, endowment, params, weight]
+ );
+
+ const _onSuccess = useCallback(
+ (result: SubmittableResult): void => {
+ const section = api.tx.contracts ? 'contracts' : 'contract';
+ const records = result.filterRecords(section, 'Instantiated');
+
+ if (records.length) {
+ // find the last EventRecord (in the case of multiple contracts deployed - we should really be
+ // more clever here to find the exact contract deployed, this works for eg. Delegator)
+ const address = records[records.length - 1].event.data[1] as unknown as AccountId;
+
+ keyring.saveContract(address.toString(), {
+ contract: {
+ abi,
+ genesisHash: api.genesisHash.toHex()
+ },
+ name,
+ tags: []
+ });
+
+ history.push(basePath);
+
+ onClose && onClose();
+ }
+ },
+ [abi, api, basePath, history, name, onClose]
+ );
+
+ return (
+
+
+
('The contract WASM previously deployed. Internally this is identified by the hash of the code, as either created or attached.')}
- isDisabled={isBusy}
- isError={!isHashValid}
- label={t('code for this contract')}
- onChange={this.onChangeCode}
+ defaultValue={
+ codeOptions.length
+ ? codeOptions[codeOptions.length - 1].value
+ : undefined
+ }
+ help={t('The contract WASM previously deployed. Internally this is identified by the hash of the code, as either created or attached.')}
+ label={t('code for this contract')}
+ onChange={setCodeHash}
options={codeOptions}
value={codeHash}
/>
- {this.renderInputName()}
+
{
isAbiSupplied
? null
- : this.renderInputAbi()
+ : (
+
+ )
}
{
contractAbi
@@ -185,19 +201,16 @@ class Deploy extends ContractModal {
('The deployment constructor information for this contract, as provided by the ABI.')}
isDisabled={contractAbi.abi.contract.constructors.length <= 1}
- label={t('constructor')}
- onChange={this.onChangeConstructorIndex}
+ label={t('deployment constructor')}
+ onChange={setConstructorIndex}
options={constructOptions}
value={`${constructorIndex}`}
- withLabel
/>
)
: null
}
= 0
? contractAbi.abi.contract.constructors[constructorIndex].args
@@ -206,121 +219,41 @@ class Deploy extends ContractModal {
/>
('The allotted endowment for this contract, i.e. the amount transferred to the contract upon instantiation.')}
- isDisabled={isBusy}
- isError={endowment.isZero()}
+ isError={!isEndowmentValid}
label={t('endowment')}
- onChange={this.onChangeEndowment}
- onEnter={this.sendTx}
+ onChange={setEndowment}
value={endowment}
/>
- {this.renderInputGas()}
- >
- );
- }
-
- protected renderButtons = (): React.ReactNode => {
- const { api, t } = this.props;
- const { accountId, endowment, gasLimit, isAbiValid, isHashValid, isNameValid } = this.state;
- const isEndowValid = !endowment.isZero();
- const isGasValid = !gasLimit.isZero();
- const isValid = isAbiValid && isHashValid && isEndowValid && isGasValid && !!accountId && isNameValid;
-
- return (
- ('Deploy')}
- onClick={this.toggleBusy(true)}
- onFailed={this.toggleBusy(false)}
- onSuccess={this.onSuccess}
- params={this.constructCall}
- tx={
- isFunction(api.tx.contracts.instantiate)
- ? 'contracts.instantiate' // V2 (new)
- : 'contracts.create' // V2 (old)
- }
- withSpinner
- />
- );
- }
-
- private constructCall = (): any[] => {
- const { codeHash, constructorIndex, contractAbi, endowment, gasLimit, params } = this.state;
-
- if (!contractAbi || constructorIndex < 0) {
- return [];
- }
-
- return [endowment, gasLimit, codeHash, contractAbi.constructors[constructorIndex](...params)];
- }
-
- protected onAddAbi = (abi: string | null | undefined, contractAbi?: Abi | null): void => {
- this.setState({
- ...(Deploy.getContractAbiState(abi, contractAbi) as State)
- });
- }
-
- private onChangeCode = (codeHash: string): void => {
- this.setState(
- Deploy.getCodeState(codeHash)
- );
- }
-
- private onChangeConstructorIndex = (constructorIndexString: string): void => {
- const { contractAbi } = this.state;
- const constructorIndex = Math.max(0, parseInt(constructorIndexString, 10) || 0);
-
- this.setState(
- Deploy.getConstructorState(contractAbi, constructorIndex)
- );
- };
-
- private onChangeEndowment = (endowment?: BN | null): void => {
- this.setState({ endowment: endowment || new BN(0) });
- }
-
- private onChangeParams = (params: any[]): void => {
- this.setState({ params });
- }
-
- private onSuccess = (result: SubmittableResult): void => {
- const { api, history } = this.props;
-
- const records = result.filterRecords('contracts', 'Instantiated');
-
- if (records.length) {
- // find the last EventRecord (in the case of multiple contracts deployed - we should really be
- // more clever here to find the exact contract deployed, this works for eg. Delegator)
- const address = records[records.length - 1].event.data[1] as unknown as AccountId;
-
- this.setState(({ abi, name, tags }): Pick | unknown => {
- if (!abi || !name) {
- return;
- }
-
- keyring.saveContract(address.toString(), {
- contract: {
- abi,
- genesisHash: api.genesisHash.toHex()
- },
- name,
- tags
- });
-
- history.push(this.props.basePath);
-
- this.onClose();
-
- return { isBusy: false };
- });
- }
- }
+ ('The maximum amount of gas that can be used by this deployment, if the code requires more, the deployment will fail.')}
+ label={t('maximum gas allowed')}
+ {...useWeightHook}
+ />
+
+
+
+
+
+ );
}
-export default withMulti(
- withRouter(Deploy),
- translate,
- withApi
-);
+export default React.memo(Deploy);
diff --git a/packages/page-contracts/src/Modal.tsx b/packages/page-contracts/src/Modal.tsx
deleted file mode 100644
index 46e07b1e78..0000000000
--- a/packages/page-contracts/src/Modal.tsx
+++ /dev/null
@@ -1,204 +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 { I18nProps } from '@polkadot/react-components/types';
-
-import BN from 'bn.js';
-import React from 'react';
-import { Abi } from '@polkadot/api-contract';
-import { Input, InputAddress, InputNumber, Modal, TxComponent } from '@polkadot/react-components';
-
-import ABI from './ABI';
-
-export interface ContractModalProps extends I18nProps {
- basePath: string;
- isNew?: boolean;
- isOpen: boolean;
- onClose?: () => void;
-}
-
-export interface ContractModalState {
- abi?: string | null;
- accountId?: string | null;
- contractAbi?: Abi | null;
- gasLimit: BN;
- isAbiSupplied: boolean;
- isAbiValid: boolean;
- isBusy: boolean;
- isNameValid: boolean;
- name?: string | null;
- tags: string[];
-}
-
-class ContractModal extends TxComponent {
- // horrible :(
- protected defaultState: S = {
- accountId: null,
- gasLimit: new BN(0),
- isAbiSupplied: false,
- isAbiValid: false,
- isBusy: false,
- isNameValid: false,
- name: null,
- tags: [] as string[]
- } as S;
-
- public state: S = this.defaultState;
-
- protected isContract?: boolean;
-
- public render (): React.ReactNode {
- const { isOpen, t } = this.props;
-
- return (
-
-
- {this.renderContent()}
-
-
- {this.renderButtons()}
-
-
- );
- }
-
- protected headerText = '';
-
- protected renderContent: () => React.ReactNode | null = (): React.ReactNode => null;
-
- protected renderButtons: () => React.ReactNode | null = (): React.ReactNode => null;
-
- protected renderInputAbi (): React.ReactNode {
- const { t } = this.props;
- const { isBusy } = this.state;
-
- return (
-
- );
- }
-
- protected renderInputAccount (): React.ReactNode {
- const { t } = this.props;
- const { accountId, isBusy } = this.state;
-
- return (
- ('Specify the user account to use for this deployment. And fees will be deducted from this account.')}
- isDisabled={isBusy}
- isInput={false}
- label={t('deployment account')}
- onChange={this.onChangeAccount}
- type='account'
- value={accountId}
- />
- );
- }
-
- protected renderInputName (): React.ReactNode {
- const { isNew, t } = this.props;
- const { isBusy, isNameValid, name } = this.state;
-
- return (
-
- );
- }
-
- protected renderInputGas (): React.ReactNode {
- const { t } = this.props;
- const { gasLimit, isBusy } = this.state;
- const isGasValid = !gasLimit.isZero();
-
- return (
- ('The maximum amount of gas that can be used by this deployment, if the code requires more, the deployment will fail.')}
- isDisabled={isBusy}
- isError={!isGasValid}
- label={t('maximum gas allowed')}
- onChange={this.onChangeGas}
- onEnter={this.sendTx}
- value={gasLimit || ''}
- />
- );
- }
-
- protected reset = (): void => {
- this.setState(
- this.defaultState
- );
- }
-
- protected toggleBusy = (isBusy?: boolean): () => void =>
- (): void => {
- this.setState((state: S): S => {
- return {
- isBusy: isBusy === undefined ? !state.isBusy : isBusy
- } as unknown as S;
- });
- }
-
- protected onClose = (): void => {
- const { onClose } = this.props;
- const { isBusy } = this.state;
-
- onClose && onClose();
-
- if (!isBusy) {
- this.reset();
- }
- }
-
- protected onAddAbi = (abi: string | null | undefined, contractAbi: Abi | null = null, isAbiSupplied = false): void => {
- this.setState({ abi, contractAbi, isAbiSupplied, isAbiValid: !!abi });
- }
-
- protected onChangeAccount = (accountId: string | null): void => {
- this.setState({ accountId });
- }
-
- protected onChangeName = (name: string): void => {
- this.setState({ isNameValid: name.length !== 0, name });
- }
-
- protected onChangeGas = (gasLimit: BN | undefined): void => {
- this.setState({ gasLimit: gasLimit || new BN(0) });
- }
-}
-
-export default ContractModal;
diff --git a/packages/page-contracts/src/RemoveABI.tsx b/packages/page-contracts/src/RemoveABI.tsx
index 9a9fa51bf5..a71c27c6c2 100644
--- a/packages/page-contracts/src/RemoveABI.tsx
+++ b/packages/page-contracts/src/RemoveABI.tsx
@@ -7,7 +7,7 @@ import { CodeStored } from '@polkadot/app-contracts/types';
import React, { useCallback } from 'react';
import { Button, Modal } from '@polkadot/react-components';
-import CodeRow from './CodeRow';
+import CodeRow from './shared/CodeRow';
import { useTranslation } from './translate';
interface Props {
diff --git a/packages/page-contracts/src/constants.ts b/packages/page-contracts/src/constants.ts
index 1316a23955..36da5a56e4 100644
--- a/packages/page-contracts/src/constants.ts
+++ b/packages/page-contracts/src/constants.ts
@@ -3,9 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
export const ENDOWMENT = 1000;
-
-export const DEFAULT_GAS_LIMIT = '100000000000';
-
+export const GAS_LIMIT = '100000000000';
export const CONTRACT_NULL = {
abi: null,
address: null
diff --git a/packages/page-contracts/src/index.tsx b/packages/page-contracts/src/index.tsx
index f814704e12..881de74410 100644
--- a/packages/page-contracts/src/index.tsx
+++ b/packages/page-contracts/src/index.tsx
@@ -2,157 +2,125 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
-import { AppProps, I18nProps } from '@polkadot/react-components/types';
+import { AppProps as Props } from '@polkadot/react-components/types';
import { TabItem } from '@polkadot/react-components/Tabs';
import { ComponentProps } from './types';
-import React from 'react';
-import { Route, Switch, RouteComponentProps } from 'react-router';
-import { withRouter } from 'react-router-dom';
+import React, { useCallback, useEffect, useMemo, useState } from 'react';
+import { Route, Switch } from 'react-router';
import { HelpOverlay, Tabs } from '@polkadot/react-components';
-import { withMulti, withObservable } from '@polkadot/react-api/hoc';
-import keyring from '@polkadot/ui-keyring';
-import { SubjectInfo } from '@polkadot/ui-keyring/observable/types';
+import { useAccounts, useContracts, useToggle } from '@polkadot/react-hooks';
import introMd from './md/intro.md';
import store from './store';
-import translate from './translate';
import Contracts from './Contracts';
import Codes from './Codes';
import Deploy from './Deploy';
+import { useTranslation } from './translate';
-interface Props extends AppProps, I18nProps, RouteComponentProps {
- accounts: SubjectInfo[];
- contracts: SubjectInfo[];
-}
+function ContractsApp ({ basePath, onStatusChange }: Props): React.ReactElement {
+ const { t } = useTranslation();
+ const { allAccounts } = useAccounts();
+ const { allContracts } = useContracts();
+ const [codeHash, setCodeHash] = useState();
+ const [constructorIndex, setConstructorIndex] = useState(0);
+ const [isDeployOpen, toggleIsDeployOpen, setIsDeployOpen] = useToggle();
+ const [updated, setUpdated] = useState(0);
-interface State {
- codeHash?: string;
- constructorIndex: number;
- hasContracts: boolean;
- isDeployOpen: boolean;
- updated: number;
-}
+ const [allCodes, setAllCodes] = useState(store.getAllCode());
-class ContractsApp extends React.PureComponent {
- public state: State = {
- constructorIndex: 0,
- hasContracts: false,
- isDeployOpen: false,
- updated: 0
- };
+ const _triggerUpdate = useCallback(
+ (): void => {
+ setUpdated(Date.now());
+ setAllCodes(store.getAllCode());
+ },
+ []
+ );
- constructor (props: Props) {
- super(props);
+ const _onShowDeploy = useCallback(
+ (codeHash?: string, constructorIndex = 0): () => void =>
+ (): void => {
+ setCodeHash(codeHash || (allCodes && allCodes[0] ? allCodes[0].json.codeHash : undefined));
+ setConstructorIndex(constructorIndex);
+ toggleIsDeployOpen();
+ },
+ [allCodes, toggleIsDeployOpen]
+ );
- store.on('new-code', this.triggerUpdate);
- store.on('removed-code', this.triggerUpdate);
+ const componentProps = useMemo(
+ (): ComponentProps => ({
+ accounts: allAccounts,
+ basePath,
+ contracts: allContracts,
+ hasCode: store.hasCode,
+ onShowDeploy: _onShowDeploy,
+ onStatusChange,
+ updated
+ }),
+ [allAccounts, allContracts, basePath, _onShowDeploy, onStatusChange, updated]
+ );
- // since we have a dep on the async API, we load here
- store.loadAll().catch((): void => {
- // noop, handled internally
- });
- }
+ useEffect(
+ (): void => {
+ store.on('new-code', _triggerUpdate);
+ store.on('removed-code', _triggerUpdate);
- public static getDerivedStateFromProps ({ contracts }: Props): Pick {
- const hasContracts = !!contracts && Object.keys(contracts).length >= 1;
+ store.loadAll()
+ .then((): void => setAllCodes(store.getAllCode()))
+ .catch((): void => {
+ // noop, handled internally
+ });
+ },
+ [_triggerUpdate]
+ );
- return {
- hasContracts
- };
- }
+ const hidden: string[] = [];
- public render (): React.ReactNode {
- const { basePath, t } = this.props;
- const { codeHash, constructorIndex, isDeployOpen } = this.state;
- const hidden: string[] = [];
+ const _onCloseDeploy = (): void => setIsDeployOpen(false);
- return (
-
-
-
- ({ ...tab, text: t(tab.text) }))
+ return (
+
+
+
-
-
-
-
+ ].map((tab): TabItem => ({ ...tab, text: t(tab.text) }))
+ }
+ />
+
+
+
+
+
+
+
+
+
+ {codeHash && (
-
- );
- }
-
- private renderComponent (Component: React.ComponentType): () => React.ReactNode {
- return (): React.ReactNode => {
- const { accounts, basePath, contracts, onStatusChange } = this.props;
- const { updated } = this.state;
-
- if (!contracts) {
- return null;
- }
-
- return (
-
- );
- };
- }
-
- private showDeploy = (codeHash?: string, constructorIndex = 0): () => void =>
- (): void => {
- this.setState({
- codeHash: codeHash || undefined,
- constructorIndex,
- isDeployOpen: true
- });
- }
-
- private hideDeploy = (): void => {
- this.setState({ isDeployOpen: false });
- }
-
- private triggerUpdate = (): void => {
- this.setState({ updated: Date.now() });
- }
+ )}
+
+ );
}
-export default withMulti(
- withRouter(ContractsApp),
- translate,
- withObservable(keyring.accounts.subject, { propName: 'accounts' }),
- withObservable(keyring.contracts.subject, { propName: 'contracts' })
-);
+export default React.memo(ContractsApp);
diff --git a/packages/page-contracts/src/shared/ABI.tsx b/packages/page-contracts/src/shared/ABI.tsx
new file mode 100644
index 0000000000..02cdcea36b
--- /dev/null
+++ b/packages/page-contracts/src/shared/ABI.tsx
@@ -0,0 +1,106 @@
+// 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 { BareProps } from '@polkadot/react-components/types';
+
+import React from 'react';
+import styled from 'styled-components';
+import { Abi } from '@polkadot/api-contract';
+import { InputFile, Labelled } from '@polkadot/react-components';
+
+import Messages from './Messages';
+import { useTranslation } from '../translate';
+
+interface Props extends BareProps {
+ contractAbi?: Abi | null;
+ errorText?: string | null;
+ isContract?: boolean;
+ isError?: boolean;
+ isDisabled?: boolean;
+ isRequired?: boolean;
+ isValid?: boolean;
+ isSupplied?: boolean;
+ label?: React.ReactNode;
+ onChange: (u8a: Uint8Array) => void;
+ onRemove?: () => void;
+ onRemoved?: () => void;
+ onSelect?: () => void;
+ onSelectConstructor?: (constructorIndex?: number) => void;
+ withLabel?: boolean;
+}
+
+function renderMessages ({ contractAbi, isDisabled, onRemove, onSelectConstructor, withLabel }: Props): React.ReactNode {
+ return (
+
+ );
+}
+
+function ABI (props: Props): React.ReactElement {
+ const { className, contractAbi, errorText, isContract = false, isDisabled, isError, isSupplied, isValid, onChange, withLabel } = props;
+ const { t } = useTranslation();
+
+ const help = isContract
+ ? t('The ABI for the WASM code. Since we will be making a call into the code, the ABI is required and stored for future operations such as sending messages.')
+ : t('The ABI for the WASM code. In this step it is optional, but setting it here simplifies the setup of contract instances.');
+ const label = isContract
+ ? 'contract ABI'
+ : 'contract ABI (optional)';
+
+ return (
+
+ {
+ (contractAbi && isValid)
+ ? (
+ withLabel
+ ? (
+
+ {renderMessages(props)}
+
+ )
+ : renderMessages(props)
+ )
+ : (
+
+ {t('invalid ABI file selected')}
+ {!!errorText && (
+ <>
+ {' — '}
+ {t(errorText)}
+ >
+ )}
+ >
+ )
+ : t('click to select or drag and drop a JSON ABI file')
+ }
+ />
+ )
+ }
+
+ );
+}
+
+export default React.memo(
+ styled(ABI)`
+ min-height: 4rem;
+ `
+);
diff --git a/packages/page-contracts/src/shared/CodeRow.tsx b/packages/page-contracts/src/shared/CodeRow.tsx
new file mode 100644
index 0000000000..3ce4a47f0a
--- /dev/null
+++ b/packages/page-contracts/src/shared/CodeRow.tsx
@@ -0,0 +1,110 @@
+// 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 { CodeStored } from '@polkadot/app-contracts/types';
+import { BareProps } from '@polkadot/react-components/types';
+
+import React, { useCallback, useEffect, useState } from 'react';
+import styled from 'styled-components';
+import { createType } from '@polkadot/types';
+import { registry } from '@polkadot/react-api';
+import { toShortAddress } from '@polkadot/react-components/util';
+import Row from '@polkadot/react-components/Row';
+import { CopyButton, Icon } from '@polkadot/react-components';
+
+import contracts from '../store';
+
+interface Props extends BareProps {
+ buttons?: React.ReactNode;
+ code: CodeStored;
+ isInline?: boolean;
+ withTags?: boolean;
+}
+
+const DEFAULT_HASH = '0x';
+const DEFAULT_NAME = '';
+
+function CodeRow ({ buttons, children, className, code: { json }, isInline, withTags }: Props): React.ReactElement {
+ const [name, setName] = useState(json.name || DEFAULT_NAME);
+ const [tags, setTags] = useState(json.tags || []);
+ const [codeHash, setCodeHash] = useState(json.codeHash || DEFAULT_HASH);
+
+ useEffect((): void => {
+ setName(json.name || DEFAULT_NAME);
+ setTags(json.tags || []);
+ setCodeHash(json.codeHash || DEFAULT_HASH);
+ }, [json]);
+
+ const _onSaveName = useCallback(
+ (): void => {
+ const trimmedName = name.trim();
+
+ if (trimmedName && codeHash) {
+ contracts.saveCode(createType(registry, 'Hash', codeHash), { name })
+ .catch((e): void => console.error(e));
+ }
+ },
+ [codeHash, name]
+ );
+
+ const _onSaveTags = useCallback(
+ (): void => {
+ if (codeHash) {
+ contracts.saveCode(createType(registry, 'Hash', codeHash), { tags })
+ .catch((e): void => console.error(e));
+ }
+ },
+ [codeHash, tags]
+ );
+
+ return (
+
+ {toShortAddress(codeHash)}
+
+ }
+ buttons={buttons}
+ className={className}
+ icon={
+
+
+
+ }
+ isEditableName
+ isEditableTags
+ isInline={isInline}
+ name={name}
+ onChangeName={setName}
+ onChangeTags={setTags}
+ onSaveName={_onSaveName}
+ onSaveTags={_onSaveTags}
+ tags={withTags && tags}
+ >
+ {children}
+
+ );
+}
+
+export default React.memo(
+ styled(CodeRow)`
+ .ui--CodeRow-icon {
+ margin-right: 1em;
+ background: #eee;
+ color: #666;
+ width: 4rem;
+ height: 5rem;
+ padding: 0.5rem;
+ display: flex;
+ justify-content: flex-end;
+ align-items: flex-end;
+ }
+ `
+);
diff --git a/packages/page-contracts/src/shared/InputMegaGas.tsx b/packages/page-contracts/src/shared/InputMegaGas.tsx
new file mode 100644
index 0000000000..cab9b572e9
--- /dev/null
+++ b/packages/page-contracts/src/shared/InputMegaGas.tsx
@@ -0,0 +1,81 @@
+// 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 { BareProps } from '@polkadot/react-components/types';
+import { UseWeight } from '../types';
+
+import React from 'react';
+import styled from 'styled-components';
+import { InputNumber, Progress } from '@polkadot/react-components';
+
+import { useTranslation } from '../translate';
+
+interface Props extends BareProps, UseWeight {
+ help: React.ReactNode;
+ label: React.ReactNode;
+}
+
+function InputMegaGas ({ className, executionTime, help, isValid, label, megaGas, percentage, setMegaGas }: Props): React.ReactElement {
+ const { t } = useTranslation();
+
+ return (
+
+
+
+ {t ('{{executionTime}}s execution time', { replace: { executionTime: executionTime.toFixed(3) } })}
+
+
+
+
+
+ );
+}
+
+export default React.memo(
+ styled(InputMegaGas)`
+ .contracts--InputMegaGas-input {
+
+ .ui.input {
+ display: flex;
+
+ input {
+ max-width: 15rem;
+ }
+
+ .contracts--InputMegaGas-meter {
+ flex: 1;
+ padding: 0.8rem 0.8rem 0;
+
+ aside {
+ float: right;
+ }
+
+ .contracts--InputMegaGas-progress {
+ margin-top: 0.4rem;
+ position: relative;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ }
+ }
+
+ }
+ }
+
+ `
+);
diff --git a/packages/page-contracts/src/shared/InputName.tsx b/packages/page-contracts/src/shared/InputName.tsx
new file mode 100644
index 0000000000..e2b4593a71
--- /dev/null
+++ b/packages/page-contracts/src/shared/InputName.tsx
@@ -0,0 +1,47 @@
+// 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 { BareProps, VoidFn } from '@polkadot/react-components/types';
+
+import React from 'react';
+import { Input } from '@polkadot/react-components';
+
+import { useTranslation } from '../translate';
+
+interface Props extends BareProps {
+ isBusy?: boolean;
+ isContract?: boolean;
+ isError?: boolean;
+ isDisabled?: boolean;
+ onChange: (_: string) => void;
+ onEnter?: VoidFn;
+ value?: string;
+}
+
+function InputName ({ className, isBusy, isContract, isError, onChange, onEnter, value = '' }: Props): React.ReactElement {
+ const { t } = useTranslation();
+
+ return (
+ (
+ isContract
+ ? 'A name for the deployed contract to help users distinguish. Only used for display purposes.'
+ : 'A name for this WASM code to help users distinguish. Only used for display purposes.'
+ )}
+ isDisabled={isBusy}
+ isError={isError}
+ label={t(
+ isContract
+ ? 'contract name'
+ : 'code bundle name'
+ )}
+ onChange={onChange}
+ onEnter={onEnter}
+ value={value}
+ />
+ );
+}
+
+export default React.memo(InputName);
diff --git a/packages/page-contracts/src/MessageSignature.tsx b/packages/page-contracts/src/shared/MessageSignature.tsx
similarity index 61%
rename from packages/page-contracts/src/MessageSignature.tsx
rename to packages/page-contracts/src/shared/MessageSignature.tsx
index ed445825b2..6eb2bbcbec 100644
--- a/packages/page-contracts/src/MessageSignature.tsx
+++ b/packages/page-contracts/src/shared/MessageSignature.tsx
@@ -3,74 +3,50 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { ContractABIMessage } from '@polkadot/api-contract/types';
+import { BareProps } from '@polkadot/react-components/types';
import React from 'react';
import styled from 'styled-components';
import { Icon, Tooltip } from '@polkadot/react-components';
import { displayType } from '@polkadot/types';
-import { useTranslation } from './translate';
+import { useTranslation } from '../translate';
const MAX_PARAM_LENGTH = 20;
-export interface Props {
+export interface Props extends BareProps {
asConstructor?: boolean;
message: ContractABIMessage;
params?: any[];
withTooltip?: boolean;
}
-const Signature = styled.div`
- font-family: monospace;
- font-weight: normal;
- flex-grow: 1;
-
- .mutates {
- color: #ff8600;
- margin-left: 0.5rem;
- opacity: 0.6;
- }
-`;
-
-const Name = styled.span`
- color: #2f8ddb;
- font-weight: bold;
-`;
-
-const Type = styled.span`
- color: #21a2b2;
-`;
-
-const ReturnType = styled.span`
- color: #ff8600;
-`;
-
function truncate (param: string): string {
return param.length > MAX_PARAM_LENGTH
? `${param.substring(0, MAX_PARAM_LENGTH / 2)}…${param.substring(param.length - MAX_PARAM_LENGTH / 2)}`
: param;
}
-function MessageSignature ({ message: { args, mutates, name, returnType }, params = [], asConstructor = false, withTooltip = false }: Props): React.ReactElement {
+function MessageSignature ({ className, message: { args, mutates, name, returnType }, params = [], asConstructor = false, withTooltip = false }: Props): React.ReactElement {
const { t } = useTranslation();
return (
-
-
+
+
{name}
-
+
(
{args.map(({ name, type }, index): React.ReactNode => {
return (
{name}:
{' '}
-
+
{params && params[index]
? {truncate((params as string[])[index].toString())}
: displayType(type)
}
-
+
{index < args.length - 1 && ', '}
);
@@ -80,15 +56,15 @@ function MessageSignature ({ message: { args, mutates, name, returnType }, param
<>
:
{' '}
-
+
{displayType(returnType)}
-
+
>
)}
{mutates && (
<>
)}
-
+
);
}
-export default React.memo(MessageSignature);
+export default React.memo(
+ styled(MessageSignature)`
+ font-family: monospace;
+ font-weight: normal;
+ flex-grow: 1;
+
+ .ui--MessageSignature-mutates {
+ color: #ff8600;
+ margin-left: 0.5rem;
+ opacity: 0.6;
+ }
+
+ .ui--MessageSignature-name {
+ color: #2f8ddb;
+ font-weight: bold;
+ }
+
+ .ui--MessageSignature-type {
+ color: #21a2b2;
+ }
+
+ .ui--MessageSignature-returnType {
+ color: #ff8600;
+ }
+ `
+);
diff --git a/packages/page-contracts/src/Messages.tsx b/packages/page-contracts/src/shared/Messages.tsx
similarity index 96%
rename from packages/page-contracts/src/Messages.tsx
rename to packages/page-contracts/src/shared/Messages.tsx
index 0214c7860b..7de42dd5fa 100644
--- a/packages/page-contracts/src/Messages.tsx
+++ b/packages/page-contracts/src/shared/Messages.tsx
@@ -3,6 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { ContractABIMessage } from '@polkadot/api-contract/types';
+import { BareProps } from '@polkadot/react-components/types';
import React from 'react';
import styled from 'styled-components';
@@ -11,11 +12,10 @@ import { classes } from '@polkadot/react-components/util';
import { Button, Expander, IconLink } from '@polkadot/react-components';
import MessageSignature from './MessageSignature';
-import { useTranslation } from './translate';
+import { useTranslation } from '../translate';
-export interface Props {
+export interface Props extends BareProps {
address?: string;
- className?: string;
contractAbi: Abi;
isLabelled?: boolean;
isRemovable: boolean;
@@ -196,7 +196,7 @@ export default React.memo(styled(Messages)`
.execute {
display: none;
- background: transparent;
+ background: transparent !important;
font-size: 1.5rem;
margin: 0;
padding: 0;
diff --git a/packages/page-contracts/src/Params.tsx b/packages/page-contracts/src/shared/Params.tsx
similarity index 100%
rename from packages/page-contracts/src/Params.tsx
rename to packages/page-contracts/src/shared/Params.tsx
diff --git a/packages/page-contracts/src/shared/index.tsx b/packages/page-contracts/src/shared/index.tsx
new file mode 100644
index 0000000000..1e14b18ac5
--- /dev/null
+++ b/packages/page-contracts/src/shared/index.tsx
@@ -0,0 +1,11 @@
+// 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.
+
+export { default as ABI } from './ABI';
+export { default as CodeRow } from './CodeRow';
+export { default as InputMegaGas } from './InputMegaGas';
+export { default as InputName } from './InputName';
+export { default as Messages } from './Messages';
+export { default as MessageSignature } from './MessageSignature';
+export { default as Params } from './Params';
diff --git a/packages/page-contracts/src/types.ts b/packages/page-contracts/src/types.ts
index 03e17d2d42..71b0e7638b 100644
--- a/packages/page-contracts/src/types.ts
+++ b/packages/page-contracts/src/types.ts
@@ -2,17 +2,15 @@
// 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 { Abi } from '@polkadot/api-contract';
import { AppProps } from '@polkadot/react-components/types';
-import { SubjectInfo } from '@polkadot/ui-keyring/observable/types';
-
-// export interface LocationProps extends RouteComponentProps {}
export interface ComponentProps extends AppProps {
- accounts: SubjectInfo[];
- contracts: SubjectInfo[];
+ accounts: string[];
+ contracts: string[];
hasCode: boolean;
- showDeploy: (codeHash?: string, constructorIndex?: number) => () => void;
+ onShowDeploy: (codeHash?: string, constructorIndex?: number) => () => void;
updated: number;
}
@@ -35,3 +33,12 @@ export interface ContractJsonOld {
address: string;
name: string;
}
+
+export interface UseWeight {
+ isValid: boolean;
+ weight: BN;
+ executionTime: number;
+ megaGas: BN;
+ percentage: number;
+ setMegaGas: React.Dispatch
+}
diff --git a/packages/page-contracts/src/useAbi.ts b/packages/page-contracts/src/useAbi.ts
new file mode 100644
index 0000000000..191fbf9c51
--- /dev/null
+++ b/packages/page-contracts/src/useAbi.ts
@@ -0,0 +1,87 @@
+// Copyright 2017-2020 @polkadot/react-hooks 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 { StringOrNull } from '@polkadot/react-components/types';
+
+import { useCallback, useEffect, useState } from 'react';
+import { Abi } from '@polkadot/api-contract';
+import { registry } from '@polkadot/react-api';
+import { u8aToString } from '@polkadot/util';
+
+import store from './store';
+import { useTranslation } from './translate';
+
+interface UseAbi {
+ abi: string | null;
+ contractAbi: Abi | null;
+ errorText: string | null;
+ isAbiError: boolean;
+ isAbiValid: boolean;
+ isAbiSupplied: boolean;
+ onChangeAbi: (u8a: Uint8Array) => void;
+ onRemoveAbi: () => void;
+}
+
+interface ContractABIOutdated {
+ deploy?: any;
+ messages?: any;
+}
+
+export default function useAbi (initialValue: [string | null, Abi | null] = [null, null], codeHash: StringOrNull = null, isRequired = false): UseAbi {
+ const { t } = useTranslation();
+ const [[abi, contractAbi, isAbiSupplied, isAbiValid], setAbi] = useState<[StringOrNull, Abi | null, boolean, boolean]>([initialValue[0], initialValue[1], !!initialValue[1], !isRequired || !!initialValue[1]]);
+ const [[isAbiError, errorText], setError] = useState<[boolean, string | null]>([false, null]);
+
+ useEffect(
+ (): void => {
+ if (!!initialValue[0] && abi !== initialValue[0]) {
+ setAbi([initialValue[0], initialValue[1], !!initialValue[1], !isRequired || !!initialValue[1]]);
+ }
+ },
+ [abi, initialValue, isRequired]
+ );
+
+ const onChangeAbi = useCallback(
+ (u8a: Uint8Array): void => {
+ const json = u8aToString(u8a);
+
+ try {
+ const abiOutdated = JSON.parse(json) as ContractABIOutdated;
+
+ if (abiOutdated.deploy || abiOutdated.messages) {
+ throw new Error(t('You are using an ABI with an outdated format. Please generate a new one.'));
+ }
+
+ setAbi([json, new Abi(registry, JSON.parse(json)), true, true]);
+ codeHash && store.saveCode(
+ codeHash,
+ { abi: json }
+ );
+ } catch (error) {
+ console.error(error);
+
+ setAbi([null, null, false, false]);
+ setError([true, error]);
+ }
+ },
+ [codeHash, t]
+ );
+
+ const onRemoveAbi = useCallback(
+ (): void => {
+ setAbi([null, null, false, false]);
+ setError([false, null]);
+
+ codeHash && store.saveCode(
+ codeHash,
+ { abi: null }
+ );
+ },
+ [codeHash]
+ );
+
+ return {
+ abi, contractAbi, errorText, isAbiError, isAbiSupplied, isAbiValid, onChangeAbi, onRemoveAbi
+ };
+}
diff --git a/packages/page-contracts/src/useWeight.ts b/packages/page-contracts/src/useWeight.ts
new file mode 100644
index 0000000000..63c7f94f2b
--- /dev/null
+++ b/packages/page-contracts/src/useWeight.ts
@@ -0,0 +1,36 @@
+// Copyright 2017-2020 @polkadot/react-hooks 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 { UseWeight } from './types';
+
+import BN from 'bn.js';
+import { useMemo, useState } from 'react';
+import { useBlockTime } from '@polkadot/react-hooks';
+import { BN_ZERO } from '@polkadot/util';
+
+const BN_MILLION = new BN(1e6);
+
+export default function useWeight (initialValue: BN = BN_MILLION): UseWeight {
+ const [blockTime] = useBlockTime();
+ const [megaGas, setMegaGas] = useState(initialValue);
+ const [executionTime, isValid, percentage, weight] = useMemo(
+ (): [number, boolean, number, BN] => {
+ if (!megaGas) {
+ return [0, false, 0, BN_ZERO];
+ }
+
+ const weight = megaGas.mul(BN_MILLION);
+ const executionTime = megaGas.toNumber() / 1e6;
+ const percentage = Math.round((executionTime / (blockTime / 1000)) * 100);
+ const isValid = !megaGas.isZero() && percentage < 100;
+
+ return [executionTime, isValid, percentage, weight];
+ },
+ [blockTime, megaGas]
+ );
+
+ return {
+ executionTime, isValid, megaGas: megaGas || BN_ZERO, percentage, setMegaGas, weight
+ };
+}
diff --git a/packages/page-council/src/Motions/ProposeMotion.tsx b/packages/page-council/src/Motions/ProposeMotion.tsx
index ea2ba33ce3..a6b2802050 100644
--- a/packages/page-council/src/Motions/ProposeMotion.tsx
+++ b/packages/page-council/src/Motions/ProposeMotion.tsx
@@ -8,6 +8,7 @@ import BN from 'bn.js';
import React, { useCallback, useEffect, useState } from 'react';
import { Button, Extrinsic, InputAddress, InputNumber, Modal, TxButton } from '@polkadot/react-components';
import { useApi, useToggle } from '@polkadot/react-hooks';
+import { BN_ZERO } from '@polkadot/util';
import { useTranslation } from '../translate';
@@ -95,7 +96,7 @@ function Propose ({ isMember, members }: Props): React.ReactElement {
label={t('threshold')}
onChange={_setThreshold}
placeholder={t('Positive number between 1 and {{memberCount}}', { replace: { memberCount: members.length } })}
- value={threshold || new BN(0)}
+ value={threshold || BN_ZERO}
/>
diff --git a/packages/page-council/src/Overview/Vote.tsx b/packages/page-council/src/Overview/Vote.tsx
index eb43cb8a0a..0215a07069 100644
--- a/packages/page-council/src/Overview/Vote.tsx
+++ b/packages/page-council/src/Overview/Vote.tsx
@@ -4,10 +4,10 @@
import { DeriveElectionsInfo } from '@polkadot/api-derive/types';
-import BN from 'bn.js';
import React, { useEffect, useState } from 'react';
import { Button, InputAddress, InputAddressMulti, Modal, TxButton, VoteValue } from '@polkadot/react-components';
import { useApi, useToggle } from '@polkadot/react-hooks';
+import { BN_ZERO } from '@polkadot/util';
import { useTranslation } from '../translate';
@@ -26,7 +26,7 @@ function Vote ({ electionsInfo }: Props): React.ReactElement {
const [available, setAvailable] = useState([]);
const [defaultVotes, setDefaultVotes] = useState([]);
const [votes, setVotes] = useState([]);
- const [voteValue, setVoteValue] = useState(new BN(0));
+ const [voteValue, setVoteValue] = useState(BN_ZERO);
useEffect((): void => {
if (electionsInfo) {
diff --git a/packages/page-democracy/src/Overview/DispatchEntry.tsx b/packages/page-democracy/src/Overview/DispatchEntry.tsx
index 136003fc7d..3a05c925e1 100644
--- a/packages/page-democracy/src/Overview/DispatchEntry.tsx
+++ b/packages/page-democracy/src/Overview/DispatchEntry.tsx
@@ -5,12 +5,11 @@
import { DeriveDispatch } from '@polkadot/api-derive/types';
import { BlockNumber } from '@polkadot/types/interfaces';
-import BN from 'bn.js';
import React from 'react';
import { LinkExternal } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { BlockToTime } from '@polkadot/react-query';
-import { formatNumber } from '@polkadot/util';
+import { BN_ZERO, formatNumber } from '@polkadot/util';
import ProposalCell from './ProposalCell';
import PreImageButton from './PreImageButton';
@@ -21,7 +20,7 @@ interface Props {
function DispatchEntry ({ value: { at, image, imageHash, index } }: Props): React.ReactElement {
const { api } = useApi();
- const bestNumber = useCall(api.derive.chain.bestNumber, []) || new BN(0);
+ const bestNumber = useCall(api.derive.chain.bestNumber, []) || BN_ZERO;
return (
diff --git a/packages/page-democracy/src/useChangeCalc.ts b/packages/page-democracy/src/useChangeCalc.ts
index 7c08e38212..0f5af475fc 100644
--- a/packages/page-democracy/src/useChangeCalc.ts
+++ b/packages/page-democracy/src/useChangeCalc.ts
@@ -7,6 +7,7 @@ import { VoteThreshold } from '@polkadot/types/interfaces';
import BN from 'bn.js';
import { useEffect, useState } from 'react';
import { useApi, useCall } from '@polkadot/react-hooks';
+import { BN_ZERO } from '@polkadot/util';
import { approxChanges } from './util';
@@ -15,12 +16,10 @@ interface Result {
changeNay: BN;
}
-const ZERO = new BN(0);
-
export default function useChangeCalc (threshold: VoteThreshold, votedAye: BN, votedNay: BN, votedTotal: BN): Result {
const { api } = useApi();
const sqrtElectorate = useCall(api.derive.democracy.sqrtElectorate, []);
- const [result, setResult] = useState({ changeAye: ZERO, changeNay: ZERO });
+ const [result, setResult] = useState({ changeAye: BN_ZERO, changeNay: BN_ZERO });
useEffect((): void => {
sqrtElectorate && setResult(
diff --git a/packages/page-democracy/src/util.ts b/packages/page-democracy/src/util.ts
index 5a82780513..47e79eb389 100644
--- a/packages/page-democracy/src/util.ts
+++ b/packages/page-democracy/src/util.ts
@@ -6,6 +6,7 @@ import { VoteThreshold } from '@polkadot/types/interfaces';
import BN from 'bn.js';
import { calcPassing } from '@polkadot/api-derive/democracy/util';
+import { BN_ZERO, BN_ONE, BN_TEN } from '@polkadot/util';
interface Approx {
changeAye: BN;
@@ -18,11 +19,8 @@ interface ApproxState {
votedTotal: BN;
}
-const ZERO = new BN(0);
-const ONE = new BN(1);
const ONEMIN = new BN(-1);
const DIVISOR = new BN(2);
-const TEN = new BN(10);
/**
* This is where we tweak the input values, based on what was specified, be it the input number
@@ -37,18 +35,18 @@ const TEN = new BN(10);
*/
function getDiffs (votes: BN, total: BN, change: BN, inc: BN, totalInc: 0 | 0.1 | 1, direction: 1 | -1): [BN, BN, BN] {
// setup
- const multiplier = direction === 1 ? ONE : ONEMIN;
+ const multiplier = direction === 1 ? BN_ONE : ONEMIN;
const voteChange = change.add(inc);
// since we allow 0.1 as well, we first multiply by 10, before dividing by the same
- const totalChange = ONE.muln(totalInc * 10).mul(voteChange).div(TEN);
+ const totalChange = BN_ONE.muln(totalInc * 10).mul(voteChange).div(BN_TEN);
// return the change, vote with change applied and the total with the same. For the total we don't want
// to go negative (total votes/turnout), since will do sqrt on it (and negative is non-sensical anyway)
return [
voteChange,
votes.add(multiplier.mul(voteChange)),
- BN.max(ZERO, total.add(multiplier.mul(totalChange)))
+ BN.max(BN_ZERO, total.add(multiplier.mul(totalChange)))
];
}
@@ -101,8 +99,8 @@ export function approxChanges (threshold: VoteThreshold, sqrtElectorate: BN, sta
};
}
- let changeAye = ZERO;
- let changeNay = ZERO;
+ let changeAye = BN_ZERO;
+ let changeNay = BN_ZERO;
let inc = state.votedTotal.div(DIVISOR);
// - starting from a large increment (total/2) see if that changes the outcome
@@ -130,12 +128,12 @@ export function approxChanges (threshold: VoteThreshold, sqrtElectorate: BN, sta
// - Always ensure that we don't go above max available (generally should be covered by above)
return {
changeAye: state.votedNay.isZero()
- ? ZERO
+ ? BN_ZERO
: isPassing
? BN.min(changeAye, state.votedAye)
: changeAye,
changeNay: state.votedAye.isZero()
- ? ZERO
+ ? BN_ZERO
: isPassing
? changeNay
: BN.min(changeNay, state.votedNay)
diff --git a/packages/page-explorer/src/NodeInfo/Summary.tsx b/packages/page-explorer/src/NodeInfo/Summary.tsx
index 96fe0dcc35..ea3a37b5d7 100644
--- a/packages/page-explorer/src/NodeInfo/Summary.tsx
+++ b/packages/page-explorer/src/NodeInfo/Summary.tsx
@@ -4,11 +4,10 @@
import { Info } from './types';
-import BN from 'bn.js';
import React, { useState, useEffect } from 'react';
import { SummaryBox, CardSummary } from '@polkadot/react-components';
-import { formatNumber } from '@polkadot/util';
import { BestNumber, Elapsed } from '@polkadot/react-query';
+import { BN_ZERO, formatNumber } from '@polkadot/util';
import { useTranslation } from '../translate';
@@ -17,12 +16,11 @@ interface Props {
info: Info;
}
-const ZERO = new BN(0);
const EMPTY_INFO = { extrinsics: null, health: null, peers: null };
function Summary ({ info: { extrinsics, health, peers } = EMPTY_INFO, nextRefresh }: Props): React.ReactElement {
const { t } = useTranslation();
- const [peerBest, setPeerBest] = useState(ZERO);
+ const [peerBest, setPeerBest] = useState(BN_ZERO);
useEffect((): void => {
if (peers) {
@@ -31,7 +29,7 @@ function Summary ({ info: { extrinsics, health, peers } = EMPTY_INFO, nextRefres
setPeerBest(
bestPeer
? bestPeer.bestNumber
- : new BN(0)
+ : BN_ZERO
);
}
}, [peers]);
diff --git a/packages/page-explorer/src/Summary.tsx b/packages/page-explorer/src/Summary.tsx
index 3ae8380a7c..f328440d1e 100644
--- a/packages/page-explorer/src/Summary.tsx
+++ b/packages/page-explorer/src/Summary.tsx
@@ -2,17 +2,15 @@
// 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 from 'react';
import { useApi } from '@polkadot/react-hooks';
import { SummaryBox, CardSummary } from '@polkadot/react-components';
import { BestFinalized, BestNumber, BlockToTime, TimeNow, TotalIssuance } from '@polkadot/react-query';
+import { BN_ONE } from '@polkadot/util';
import SummarySession from './SummarySession';
import { useTranslation } from './translate';
-const ONE_BLOCK = new BN(1);
-
function Summary (): React.ReactElement {
const { t } = useTranslation();
const { api } = useApi();
@@ -27,7 +25,7 @@ function Summary (): React.ReactElement {
className='ui--media-small'
label={t('target')}
>
-
+
{api.query.balances && (
)}
defaultName={name}
- isEditable
onSaveName={_onSaveName}
/>
diff --git a/packages/page-generic-asset/src/AssetRow.tsx b/packages/page-generic-asset/src/AssetRow.tsx
index 7bbed46187..a00099f0e5 100644
--- a/packages/page-generic-asset/src/AssetRow.tsx
+++ b/packages/page-generic-asset/src/AssetRow.tsx
@@ -2,65 +2,41 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
-import React from 'react';
-import styled from 'styled-components';
+import React, { useState } from 'react';
import { CopyButton } from '@polkadot/react-components';
-import Row, { styles, RowProps, RowState } from '@polkadot/react-components/Row';
-import { I18nProps } from '@polkadot/react-components/types';
+import Row, { RowProps } from '@polkadot/react-components/Row';
-import translate from './translate';
+import { useTranslation } from './translate';
-type Props = I18nProps & RowProps & {
+interface Props extends Omit {
onSaveName: (name: string) => void;
assetId: string;
}
-class AssetRow extends Row {
- constructor (props: Props) {
- super(props);
+export default function AssetRow ({ assetId, buttons, children, className, defaultName = 'New Asset', isDisabled, isInline, onSaveName }: Props): React.ReactElement {
+ const { t } =
+ useTranslation();
+ const [name, setName] = useState(defaultName);
- this.state.name = this.props.defaultName || 'New Asset';
- }
-
- public render (): React.ReactNode {
- const { className = '' } = this.props;
-
- return (
-
-
-
- {this.renderName()}
- {this.renderAssetId()}
-
- {this.renderButtons()}
+ return (
+
+
+ {t('Asset ID')}: {assetId}
+
-
- );
- }
-
- protected saveName = (): void => {
- const { name } = this.state;
- const { onSaveName } = this.props;
-
- const trimmedName = name.trim();
-
- onSaveName(trimmedName);
- this.setState({ isEditingName: false });
- }
-
- private renderAssetId (): React.ReactNode {
- const { assetId, t } = this.props;
-
- return (
-
-
- {t('Asset ID')}: {assetId}
-
-
- );
- }
+ }
+ isDisabled={isDisabled}
+ isEditableName
+ isInline={isInline}
+ name={name}
+ onChangeName={setName}
+ onSaveName={onSaveName}
+ >
+ {children}
+
+ );
}
-
-export default translate(styled(AssetRow)`${styles}`);
diff --git a/packages/page-generic-asset/src/Transfer.tsx b/packages/page-generic-asset/src/Transfer.tsx
index 3c869bf74c..68c4119ec9 100644
--- a/packages/page-generic-asset/src/Transfer.tsx
+++ b/packages/page-generic-asset/src/Transfer.tsx
@@ -13,6 +13,7 @@ import { useApi } from '@polkadot/react-hooks';
import { Available } from '@polkadot/react-query';
import Checks from '@polkadot/react-signer/Checks';
import { withMulti, withObservable } from '@polkadot/react-api/hoc';
+import { BN_ZERO } from '@polkadot/util';
import assetRegistry, { AssetsSubjectInfo } from './assetsRegistry';
import translate from './translate';
@@ -33,7 +34,7 @@ interface Option {
function Transfer ({ assets, className = '', onClose, recipientId: propRecipientId, senderId: propSenderId, t }: Props): React.ReactElement {
const { api } = useApi();
const [assetId, setAssetId] = useState('0');
- const [amount, setAmount] = useState(new BN(0));
+ const [amount, setAmount] = useState(BN_ZERO);
const [extrinsic, setExtrinsic] = useState(null);
const [hasAvailable, setHasAvailable] = useState(true);
const [options, setOptions] = useState |