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 <jacogr@gmail.com>
This commit is contained in:
Keith Ingram 2020-06-10 00:56:10 +12:00 committed by GitHub
parent 59b54a8226
commit 2081464de8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
92 changed files with 2197 additions and 2711 deletions

View File

@ -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
</td>
<td className='all'>
<div className='tags'>
{tags.map((tag): React.ReactNode => (
<Tag
key={tag}
label={tag}
/>
))}
<Tags value={tags} />
</div>
</td>
<td className='number ui--media-1500'>

View File

@ -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)
};
}),
[]

View File

@ -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<string[]>(['']);
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 => {

View File

@ -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<Props> {
const { t } = useTranslation();
const { api } = useApi();
const [amount, setAmount] = useState<BN | undefined>(new BN(0));
const [amount, setAmount] = useState<BN | undefined>(BN_ZERO);
const [hasAvailable] = useState(true);
const [maxBalance] = useState(new BN(0));
const [maxBalance] = useState(BN_ZERO);
const [recipientId, setRecipientId] = useState<string | null>(propRecipientId || null);
const [senderId, setSenderId] = useState<string | null>(propSenderId || null);

View File

@ -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
</td>
<td className='all'>
<div className='tags'>
{tags.map((tag): React.ReactNode => (
<Tag
key={tag}
label={tag}
/>
))}
<Tags value={tags} />
</div>
</td>
<td className='number ui--media-1500'>

View File

@ -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<Props> {
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
)}
</AccountName>
<div className='ui--AddressMenu-tags'>
{isEditingTags
? (
<InputTags
defaultValue={tags}
onBlur={onSaveTags}
onChange={setTags}
onClose={onSaveTags}
openOnFocus
searchInput={TAG_OPTS}
value={tags}
withLabel={false}
/>
)
: (
<div
className='tags--toggle'
onClick={toggleIsEditingTags}
>
{tags.length
? tags.map((tag): React.ReactNode => (
<Tag
color='grey'
key={tag}
label={tag}
size='tiny'
/>
))
: <label>{t<string>('no tags')}</label>
}
</div>
)
}
{(!isEditingTags && (flags.isInContacts || flags.isOwned)) && (
<Icon
className='inline-icon'
name='edit'
onClick={toggleIsEditingTags}
/>
)}
<Tags
isEditable
isEditing={isEditingTags}
onChange={setTags}
onSave={onSaveTags}
onToggleIsEditing={toggleIsEditingTags}
size='tiny'
value={tags}
/>
</div>
<Flags flags={flags} />
<div className='ui-AddressMenu--button'>

View File

@ -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<Props, State> {
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<State, never> | 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 (
<div className={className}>
{
(contractAbi && isAbiValid)
? this.renderMessages()
: this.renderInputFile()
}
</div>
);
}
private renderInputFile (): React.ReactNode {
const { className = '', help, isDisabled, isRequired, label, t } = this.props;
const { errorText, isAbiValid, isEmpty, isError } = this.state;
return (
<div className={className}>
<InputFile
help={help}
isDisabled={isDisabled}
isError={!isAbiValid && (isRequired || isError)}
label={label}
onChange={this.onChange}
placeholder={
!isEmpty && !isAbiValid
? (
<>
{t<string>('invalid ABI file selected')}
{!!errorText && (
<>
{' — '}
{t(errorText)}
</>
)}
</>
)
: t<string>('click to select or drag and drop a JSON ABI file')
}
/>
</div>
);
}
private renderMessages (): React.ReactNode {
const { help, isDisabled, label, onRemove, onSelectConstructor } = this.props;
const { contractAbi } = this.state;
if (!contractAbi) {
return null;
}
return (
<Labelled
help={help}
label={label}
withLabel={!!label}
>
<Messages
contractAbi={contractAbi}
isLabelled={!!label}
isRemovable={!isDisabled}
onRemove={onRemove || this.onRemove}
onSelectConstructor={onSelectConstructor}
withConstructors
/>
</Labelled>
);
}
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<string, unknown>).deploy || (abi as unknown as Record<string, unknown>).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<Props, State>)`
min-height: 4rem;
`);

View File

@ -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 = '<unknown>';
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<Props, State> {
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<State> = { 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 (
<div className={classes('ui--Row', isInline && 'inline', className)}>
<div className='ui--Row-base'>
{this.renderIcon()}
<div className='ui--Row-details'>
{this.renderName()}
{this.renderCodeHash()}
{this.renderTags()}
</div>
{this.renderButtons()}
</div>
{this.renderMessages()}
{this.renderChildren()}
</div>
);
}
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 (
<>
<div className='ui--Row-name'>
{name}
</div>
<div className='ui--Row-accountId'>
<CopyButton
isAddress
value={codeHash}
>
<span>{toShortAddress(codeHash)}</span>
</CopyButton>
</div>
</>
);
}
protected renderButtons (): React.ReactNode {
const { buttons } = this.props;
if (!buttons) {
return null;
}
return (
<div className='ui--Row-buttons'>
{buttons}
</div>
);
}
protected renderIcon (): React.ReactNode {
return (
<CodeIcon>
<Icon
name='code'
size='large'
/>
</CodeIcon>
);
}
protected renderMessages (): React.ReactNode {
const { code: { contractAbi }, withMessages } = this.props;
if (!withMessages || !contractAbi) {
return null;
}
return (
<Messages
contractAbi={contractAbi}
isRemovable
/>
);
}
protected saveName = async (): Promise<void> => {
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<void> => {
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<Props>)`
${styles}
`,
translate
);

View File

@ -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<StringOrNull>(null);
const { abi, contractAbi, errorText, isAbiError, isAbiSupplied, isAbiValid, onChangeAbi, onRemoveAbi } = useAbi();
class Add extends ContractModal<Props, State> {
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 (
<>
<Input
autoFocus
help={t<string>('The code hash for the on-chain deployed code.')}
isDisabled={isBusy}
isError={!isCodeValid}
label={t<string>('code hash')}
onChange={this.onChangeHash}
onEnter={this.submit}
value={codeHash}
/>
<ValidateCode
codeHash={codeHash}
onChange={this.onValidateCode}
/>
{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 (
<Button
icon='save'
isDisabled={!isValid}
isPrimary
label={t<string>('Save')}
onClick={this.onSave}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
ref={this.button}
/>
);
}
private onChangeHash = (codeHash: string): void => {
this.setState({ codeHash, isCodeValid: false });
}
private onValidateCode = (isCodeValid: boolean): void => {
this.setState({ isCodeValid });
}
private onSave = (): void => {
const { abi, codeHash, name, tags } = this.state;
if (!codeHash || !name) {
return;
}
this.setState({ isBusy: true }, (): void => {
store
.saveCode(createType(registry, 'Hash', codeHash), { abi, name, tags })
.then((): void => {
this.setState(
{ isBusy: false },
(): void => this.onClose()
);
})
.saveCode(createType(registry, 'Hash', codeHash), { abi, name, tags: [] })
.then((): void => setIsOpen(false))
.catch((error): void => {
console.error('Unable to save code', error);
this.setState({ isBusy: false });
});
});
},
[abi, codeHash, name, setIsOpen]
);
// this.redirect();
}
return (
<>
<Button
icon='add'
label={t('Add an existing code hash')}
onClick={toggleIsOpen}
/>
{isOpen && (
<Modal header={t('Add an existing code hash')}>
<Modal.Content>
<Input
autoFocus
help={t('The code hash for the on-chain deployed code.')}
isError={codeHash.length > 0 && !isCodeHashValid}
label={t('code hash')}
onChange={setCodeHash}
value={codeHash}
/>
<ValidateCode
codeHash={codeHash}
onChange={setIsCodeHashValid}
/>
<InputName
isError={!isNameValid}
onChange={setName}
value={name || undefined}
/>
<ABI
contractAbi={contractAbi}
errorText={errorText}
isError={isAbiError}
isSupplied={isAbiSupplied}
isValid={isAbiValid}
onChange={onChangeAbi}
onRemove={onRemoveAbi}
withLabel
/>
</Modal.Content>
<Modal.Actions onCancel={toggleIsOpen}>
<Button
icon='save'
isDisabled={!isValid}
isPrimary
label={t('Save')}
onClick={_onSave}
/>
</Modal.Actions>
</Modal>
)}
</>
);
}
export default translate(Add);
export default React.memo(Add);

View File

@ -2,124 +2,118 @@
// 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 { BareProps } from '@polkadot/react-components/types';
import { CodeStored } from '../types';
import React from 'react';
import React, { useCallback } from 'react';
import styled from 'styled-components';
import { RouteComponentProps } from 'react-router';
import { withRouter } from 'react-router-dom';
import { Button, Card, Expander, Forget } from '@polkadot/react-components';
import { useToggle } from '@polkadot/react-hooks';
import ABI from '../ABI';
import CodeRow from '../CodeRow';
import { ABI, CodeRow } from '../shared';
import RemoveABI from '../RemoveABI';
import contracts from '../store';
import translate from '../translate';
import store from '../store';
import useAbi from '../useAbi';
import { useTranslation } from '../translate';
interface Props extends I18nProps, RouteComponentProps {
interface Props extends BareProps {
code: CodeStored;
showDeploy: (codeHash?: string, constructorIndex?: number) => () => void;
onShowDeploy: (codeHash?: string, constructorIndex?: number) => () => void;
}
interface State {
isAbiOpen: boolean;
isForgetOpen: boolean;
isRemoveABIOpen: boolean;
}
function Code ({ className, code, onShowDeploy }: Props): React.ReactElement<Props> {
const { json: { codeHash } } = code;
const { t } = useTranslation();
const [isAbiOpen, toggleIsAbiOpen] = useToggle();
const [isForgetOpen, toggleIsForgetOpen] = useToggle();
const [isRemoveABIOpen, toggleIsRemoveABIOpen] = useToggle();
const { contractAbi, isAbiError, isAbiSupplied, isAbiValid, onChangeAbi, onRemoveAbi } = useAbi([code.json.abi || null, code.contractAbi || null], codeHash, true);
const CodeCard = styled(Card)`
&& {
max-width: 100%;
min-width: 100%;
}
`;
const _onShowDeploy = useCallback(
(): void => onShowDeploy(codeHash)(),
[codeHash, onShowDeploy]
);
class Code extends React.PureComponent<Props, State> {
public state: State = {
isAbiOpen: false,
isForgetOpen: false,
isRemoveABIOpen: false
};
const _onDeployConstructor = useCallback(
(constructorIndex = 0): void => {
codeHash && onShowDeploy && onShowDeploy(codeHash, constructorIndex)();
},
[codeHash, onShowDeploy]
);
public render (): React.ReactNode {
const { code, code: { contractAbi }, t } = this.props;
const { isAbiOpen } = this.state;
const _onForget = useCallback(
(): void => {
if (!codeHash) {
return;
}
const abi = (
<ABI
contractAbi={contractAbi}
onChange={this.onChangeABI}
onRemove={this.toggleRemoveABI}
onSelectConstructor={this.onDeployConstructor}
/>
);
try {
store.forgetCode(codeHash);
} catch (error) {
console.error(error);
} finally {
toggleIsForgetOpen();
}
},
[codeHash, toggleIsForgetOpen]
);
return (
<CodeCard>
{this.renderModals()}
<CodeRow
buttons={this.renderButtons()}
code={code}
isEditable
withTags
>
{contractAbi
? (
<Expander
isOpen={isAbiOpen}
onClick={this.toggleAbi}
summary={t<string>('ABI')}
>
{abi}
</Expander>
)
: abi
}
</CodeRow>
</CodeCard>
);
}
const abiNode = (
<ABI
contractAbi={contractAbi}
isError={isAbiError}
isSupplied={isAbiSupplied}
isValid={isAbiValid}
onChange={onChangeAbi}
onRemove={toggleIsRemoveABIOpen}
onSelectConstructor={_onDeployConstructor}
/>
);
private renderButtons (): React.ReactNode {
const { code: { json: { codeHash } }, showDeploy, t } = this.props;
return (
<>
<Button
icon='trash'
isNegative
onClick={this.toggleForget}
tooltip={t<string>('Forget this code hash')}
/>
<Button
icon='cloud upload'
isPrimary
label={t<string>('deploy')}
onClick={showDeploy(codeHash)}
tooltip={t<string>('Deploy this code hash as a smart contract')}
/>
</>
);
}
private renderModals (): React.ReactNode {
const { code, t } = this.props;
const { isForgetOpen, isRemoveABIOpen } = this.state;
if (!code) {
return null;
}
const modals = [];
if (isForgetOpen) {
modals.push(
return (
<Card className={className}>
<CodeRow
buttons={
<>
<Button
icon='trash'
isNegative
onClick={toggleIsForgetOpen}
size='small'
tooltip={t('Forget this code hash')}
/>
<Button
icon='cloud upload'
isPrimary
label={t('deploy')}
onClick={_onShowDeploy}
size='small'
tooltip={t('Deploy this code hash as a smart contract')}
/>
</>
}
code={code}
withTags
>
{contractAbi
? (
<Expander
isOpen={isAbiOpen}
onClick={toggleIsAbiOpen}
summary={t<string>('ABI')}
>
{abiNode}
</Expander>
)
: abiNode
}
</CodeRow>
{isForgetOpen && (
<Forget
key='modal-forget-account'
mode='code'
onClose={this.toggleForget}
onForget={this.onForget}
onClose={toggleIsForgetOpen}
onForget={_onForget}
>
<CodeRow
code={code || ''}
@ -129,82 +123,22 @@ class Code extends React.PureComponent<Props, State> {
<p>{t<string>('This operation does not remove the uploaded code WASM and ABI from the chain, nor any deployed contracts. The forget operation only limits your access to the code on this browser.')}</p>
</CodeRow>
</Forget>
);
}
if (isRemoveABIOpen) {
modals.push(
)}
{isRemoveABIOpen && (
<RemoveABI
code={code}
key='modal-remove-abi'
onClose={this.toggleRemoveABI}
onRemove={this.onChangeABI}
onClose={toggleIsRemoveABIOpen}
onRemove={onRemoveAbi}
/>
);
}
return modals;
}
private toggleAbi = (event: React.MouseEvent): () => void => {
return (): void => {
event.preventDefault();
const { isAbiOpen } = this.state;
this.setState({
isAbiOpen: !isAbiOpen
});
};
}
private toggleForget = (): void => {
const { isForgetOpen } = this.state;
this.setState({
isForgetOpen: !isForgetOpen
});
}
private toggleRemoveABI = (): void => {
const { isRemoveABIOpen } = this.state;
this.setState({
isRemoveABIOpen: !isRemoveABIOpen
});
}
private onDeployConstructor = (constructorIndex = 0): void => {
const { code: { json: { codeHash } }, showDeploy } = this.props;
codeHash && showDeploy && showDeploy(codeHash, constructorIndex)();
}
private onForget = (): void => {
const { code: { json: { codeHash } } } = this.props;
if (!codeHash) {
return;
}
try {
contracts.forgetCode(codeHash);
} catch (error) {
console.error(error);
} finally {
this.toggleForget();
}
}
private onChangeABI = (abi: string | null = null): void => {
const { code: { json: { codeHash } } } = this.props;
this.setState(
{ isAbiOpen: true },
(): void => {
contracts.saveCode(codeHash, { abi }).catch(console.error);
}
);
}
)}
</Card>
);
}
export default translate(withRouter(Code));
export default React.memo(
styled(Code)`
max-width: 100%;
min-width: 100%;
`
);

View File

@ -3,133 +3,123 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { Hash } from '@polkadot/types/interfaces';
import { ApiProps } from '@polkadot/react-api/types';
import BN from 'bn.js';
import React from 'react';
import React, { useCallback, useMemo, useState } from 'react';
import { SubmittableResult } from '@polkadot/api';
import { withApi, withMulti } from '@polkadot/react-api/hoc';
import { InputFile, TxButton } from '@polkadot/react-components';
import { compactAddLength } from '@polkadot/util';
import { Button, InputAddress, InputFile, Modal, TxButton } from '@polkadot/react-components';
import { useAccountId, useApi, useNonEmptyString, useToggle } from '@polkadot/react-hooks';
import { compactAddLength, isNull } from '@polkadot/util';
import ContractModal, { ContractModalProps, ContractModalState } from '../Modal';
import { ABI, InputName } from '../shared';
import store from '../store';
import translate from '../translate';
import { DEFAULT_GAS_LIMIT } from '../constants';
import { useTranslation } from '../translate';
import useAbi from '../useAbi';
interface Props extends ContractModalProps, ApiProps {}
function Upload (): React.ReactElement {
const { t } = useTranslation();
const { api } = useApi();
const [isOpen, toggleIsOpen] = useToggle();
const [accountId, setAccountId] = useAccountId();
const [[wasm, isWasmValid], setWasm] = useState<[Uint8Array | null, boolean]>([null, false]);
const [name, isNameValid, setName] = useNonEmptyString();
const { abi, contractAbi, errorText, isAbiError, isAbiSupplied, isAbiValid, onChangeAbi, onRemoveAbi } = useAbi();
interface State extends ContractModalState {
gasLimit: BN;
isGasLimit: boolean;
isWasmValid: boolean;
wasm?: Uint8Array | null;
}
const isSubmittable = useMemo(
(): boolean => !!accountId && (!isNull(name) && isNameValid) && isWasmValid && (!isAbiSupplied || isAbiValid),
[accountId, name, isAbiSupplied, isAbiValid, isNameValid, isWasmValid]
);
const WASM_MAGIC = '0,97,115,109'; // '\0asm'
const _onAddWasm = useCallback(
(wasm: Uint8Array, name: string): void => {
setWasm([compactAddLength(wasm), wasm.subarray(0, 4).toString() === '0,97,115,109']);
setName(name);
},
[setName]
);
class Upload extends ContractModal<Props, State> {
constructor (props: Props) {
super(props);
const { api, t } = this.props;
this.defaultState = {
...this.defaultState,
gasLimit: new BN(DEFAULT_GAS_LIMIT),
isGasLimit: api.tx.contracts.putCode.meta.args.length === 2,
isWasmValid: false,
wasm: null
};
this.state = this.defaultState;
this.headerText = t<string>('Upload WASM');
}
protected renderContent = (): React.ReactNode => {
const { t } = this.props;
const { isBusy, isGasLimit, isWasmValid, wasm } = this.state;
return (
<>
{this.renderInputAccount()}
<InputFile
help={t<string>('The compiled WASM for the contract that you wish to deploy. Each unique code blob will be attached with a code hash that can be used to create new instances.')}
isDisabled={isBusy}
isError={!isWasmValid}
label={t<string>('compiled contract WASM')}
onChange={this.onAddWasm}
placeholder={
wasm && !isWasmValid
? t<string>('The code is not recognized as being in valid WASM format')
: null
}
/>
{this.renderInputName()}
{this.renderInputAbi()}
{isGasLimit && this.renderInputGas()}
</>
);
}
protected renderButtons = (): React.ReactNode => {
const { t } = this.props;
const { accountId, gasLimit, isBusy, isGasLimit, isNameValid, isWasmValid, wasm } = this.state;
const isValid = !isBusy && !!accountId && isNameValid && isWasmValid && (isGasLimit || !gasLimit.isZero());
return (
<TxButton
accountId={accountId}
icon='upload'
isDisabled={!isValid}
isPrimary
label={t<string>('Upload')}
onClick={this.toggleBusy(true)}
onFailed={this.toggleBusy(false)}
onSuccess={this.onSuccess}
params={
isGasLimit
? [gasLimit, wasm]
: [wasm]
}
tx='contracts.putCode'
withSpinner
/>
);
}
private onAddWasm = (wasm: Uint8Array, name: string): void => {
this.setState({
isWasmValid: wasm.subarray(0, 4).toString() === WASM_MAGIC,
wasm: compactAddLength(wasm)
});
this.onChangeName(name);
}
private onSuccess = (result: SubmittableResult): void => {
this.setState(({ abi, name, tags }): Pick<State, never> | null => {
const record = result.findRecord('contracts', 'CodeStored');
const _onSuccess = useCallback(
(result: SubmittableResult): void => {
const section = api.tx.contracts ? 'contracts' : 'contract';
const record = result.findRecord(section, 'CodeStored');
if (record) {
const codeHash = record.event.data[0];
if (!codeHash || !name) {
return null;
return;
}
store.saveCode(codeHash as Hash, { abi, name, tags })
.then((): void => this.onClose())
store.saveCode(codeHash as Hash, { abi, name, tags: [] })
.then()
.catch((error: any): void => {
console.error('Unable to save code', error);
});
}
},
[api, abi, name]
);
return { isBusy: false };
});
}
return (
<>
<Button
icon='add'
label={t('Upload WASM')}
onClick={toggleIsOpen}
/>
{isOpen && (
<Modal header={t('Upload WASM')}>
<Modal.Content>
<InputAddress
help={t('Specify the user account to use for this deployment. Any fees will be deducted from this account.')}
isInput={false}
label={t('deployment account')}
onChange={setAccountId}
type='account'
value={accountId}
/>
<InputFile
help={t<string>('The compiled WASM for the contract that you wish to deploy. Each unique code blob will be attached with a code hash that can be used to create new instances.')}
isError={!isWasmValid}
label={t<string>('compiled contract WASM')}
onChange={_onAddWasm}
placeholder={
wasm && !isWasmValid
? t<string>('The code is not recognized as being in valid WASM format')
: null
}
/>
<InputName
isError={!isNameValid}
onChange={setName}
value={name || undefined}
/>
<ABI
contractAbi={contractAbi}
errorText={errorText}
isError={isAbiError}
isSupplied={isAbiSupplied}
isValid={isAbiValid}
onChange={onChangeAbi}
onRemove={onRemoveAbi}
withLabel
/>
</Modal.Content>
<Modal.Actions onCancel={toggleIsOpen}>
<TxButton
accountId={accountId}
icon='upload'
isDisabled={!isSubmittable}
label={t('Upload')}
onClick={toggleIsOpen}
onSuccess={_onSuccess}
params={[wasm]}
tx={api.tx.contracts ? 'contracts.putCode' : 'contract.putCode'}
/>
</Modal.Actions>
</Modal>
)}
</>
);
}
export default withMulti(
Upload,
translate,
withApi
);
export default React.memo(Upload);

View File

@ -5,73 +5,53 @@
/* eslint-disable camelcase */
import { PrefabWasmModule } from '@polkadot/types/interfaces';
import { I18nProps } from '@polkadot/react-components/types';
import { ApiProps } from '@polkadot/react-api/types';
import React from 'react';
import React, { useMemo } from 'react';
import { Option } from '@polkadot/types';
import { withCalls } from '@polkadot/react-api/hoc';
import { InfoForInput } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { isHex } from '@polkadot/util';
import translate from '../translate';
import { useTranslation } from '../translate';
interface Props extends ApiProps, I18nProps {
interface Props {
codeHash?: string | null;
contracts_codeStorage?: Option<PrefabWasmModule>;
onChange: (isValid: boolean) => void;
onChange: React.Dispatch<boolean>;
}
interface State {
isStored: boolean;
isValidHex: boolean;
isValid: boolean;
}
function ValidateCode ({ codeHash, onChange }: Props): React.ReactElement<Props> | null {
const { api } = useApi();
const { t } = useTranslation();
const codeStorage = useCall<Option<PrefabWasmModule>>((api.query.contracts || api.query.contract).codeStorage, [codeHash]);
const [isValidHex, isValid] = useMemo(
(): [boolean, boolean] => {
const isValidHex = !!codeHash && isHex(codeHash) && codeHash.length === 66;
const isStored = !!codeStorage && codeStorage.isSome;
const isValid = isValidHex && isStored;
class ValidateCode extends React.PureComponent<Props, State> {
public state: State = {
isStored: false,
isValid: false,
isValidHex: false
};
onChange(isValid);
public static getDerivedStateFromProps ({ codeHash, contracts_codeStorage, onChange }: Props): State {
const isValidHex = !!codeHash && isHex(codeHash) && codeHash.length === 66;
const isStored = !!contracts_codeStorage && contracts_codeStorage.isSome;
const isValid = isValidHex && isStored;
return [
isValidHex,
isValid
];
},
[codeHash, codeStorage, onChange]
);
// FIXME Really not convinced this is the correct place to do this type of callback?
onChange(isValid);
return {
isStored,
isValid,
isValidHex
};
if (isValid || !isValidHex) {
return null;
}
public render (): React.ReactNode {
const { t } = this.props;
const { isValid, isValidHex } = this.state;
if (isValid || !isValidHex) {
return null;
}
return (
<InfoForInput type='error'>
{
isValidHex
? t<string>('Unable to find on-chain WASM code for the supplied codeHash')
: t<string>('The codeHash is not a valid hex hash')
}
</InfoForInput>
);
}
return (
<InfoForInput type='error'>
{
isValidHex
? t('Unable to find on-chain WASM code for the supplied codeHash')
: t('The codeHash is not a valid hex hash')
}
</InfoForInput>
);
}
export default translate(
withCalls<Props>(
['query.contracts.codeStorage', { fallbacks: ['query.contract.codeStorage'], paramName: 'codeHash' }]
)(ValidateCode)
);
export default React.memo(ValidateCode);

View File

@ -2,95 +2,44 @@
// 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 { ComponentProps } from '../types';
import { ComponentProps as Props } from '../types';
import React from 'react';
import { Button, CardGrid } from '@polkadot/react-components';
import contracts from '../store';
import translate from '../translate';
import { useTranslation } from '../translate';
import Code from './Code';
import Upload from './Upload';
import Add from './Add';
interface Props extends ComponentProps, I18nProps {}
function Codes ({ onShowDeploy }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
interface State {
isAddOpen: boolean;
isUploadOpen: boolean;
return (
<>
<CardGrid
buttons={
<Button.Group isCentered>
<Upload />
<Add />
</Button.Group>
}
emptyText={t('No code hashes available')}
>
{contracts.getAllCode().map((code): React.ReactNode => {
return (
<Code
code={code}
key={code.json.codeHash}
onShowDeploy={onShowDeploy}
/>
);
})}
</CardGrid>
</>
);
}
class Codes extends React.PureComponent<Props, State> {
public state: State = {
isAddOpen: false,
isUploadOpen: false
};
public render (): React.ReactNode {
const { basePath, showDeploy, t } = this.props;
const { isAddOpen, isUploadOpen } = this.state;
return (
<>
<CardGrid
buttons={
<Button.Group>
<Button
icon='upload'
label={t<string>('Upload WASM')}
onClick={this.showUpload}
/>
<Button
icon='add'
label={t<string>('Add an existing code hash')}
onClick={this.showAdd}
/>
</Button.Group>
}
emptyText={t<string>('No code hashes available')}
>
{contracts.getAllCode().map((code): React.ReactNode => {
return (
<Code
code={code}
key={code.json.codeHash}
showDeploy={showDeploy}
/>
);
})}
</CardGrid>
<Upload
basePath={basePath}
isNew
isOpen={isUploadOpen}
onClose={this.hideUpload}
/>
<Add
basePath={basePath}
isOpen={isAddOpen}
onClose={this.hideAdd}
/>
</>
);
}
private showUpload = (): void => {
this.setState({ isUploadOpen: true });
}
private hideUpload = (): void => {
this.setState({ isUploadOpen: false });
}
private showAdd = (): void => {
this.setState({ isAddOpen: true });
}
private hideAdd = (): void => {
this.setState({ isAddOpen: false });
}
}
export default translate(Codes);
export default React.memo(Codes);

View File

@ -2,130 +2,129 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiProps } from '@polkadot/react-api/types';
import { I18nProps } from '@polkadot/react-components/types';
import { StringOrNull } from '@polkadot/react-components/types';
import { ActionStatus } from '@polkadot/react-components/Status/types';
import React from 'react';
import { withApi } from '@polkadot/react-api/hoc';
import { AddressRow, Button, Input } from '@polkadot/react-components';
import React, { useCallback, useMemo, useState } from 'react';
import { AddressRow, Button, Input, Modal } from '@polkadot/react-components';
import { useApi, useNonEmptyString, useToggle } from '@polkadot/react-hooks';
import keyring from '@polkadot/ui-keyring';
import ContractModal, { ContractModalProps, ContractModalState } from '../Modal';
import ValidateAddr from './ValidateAddr';
import { ABI, InputName } from '../shared';
import { useTranslation } from '../translate';
import useAbi from '../useAbi';
import translate from '../translate';
function Add (): React.ReactElement {
const { t } = useTranslation();
const { api } = useApi();
const [isOpen, toggleIsOpen, setIsOpen] = useToggle();
const [address, setAddress] = useState<StringOrNull>(null);
const [isAddressValid, setIsAddressValid] = useState(false);
const [name, isNameValid, setName] = useNonEmptyString('New Contract');
const { abi, contractAbi, errorText, isAbiError, isAbiSupplied, isAbiValid, onChangeAbi, onRemoveAbi } = useAbi([null, null], null, true);
interface Props extends ContractModalProps, ApiProps, I18nProps {}
const isValid = useMemo(
(): boolean => isAddressValid && isNameValid && isAbiValid,
[isAbiValid, isAddressValid, isNameValid]
);
interface State extends ContractModalState {
address?: string | null;
isAddressValid: boolean;
}
const _onAdd = useCallback(
(): void => {
const status: Partial<ActionStatus> = { action: 'create' };
class Add extends ContractModal<Props, State> {
constructor (props: Props) {
super(props);
this.defaultState = {
...this.defaultState,
address: null,
isAddressValid: false,
isNameValid: true,
name: 'New Contract'
};
this.state = this.defaultState;
this.headerText = props.t('Add an existing contract');
}
if (!address || !abi || !name) {
return;
}
public isContract = true;
try {
const json = {
contract: {
abi,
genesisHash: api.genesisHash.toHex()
},
name,
tags: []
};
protected renderContent = (): React.ReactNode => {
const { t } = this.props;
const { address, isAddressValid, isBusy, name } = this.state;
keyring.saveContract(address, json);
return (
<AddressRow
defaultName={name}
isValid
value={address || null}
>
<Input
autoFocus
help={t<string>('The address for the deployed contract instance.')}
isDisabled={isBusy}
isError={!isAddressValid}
label={t<string>('contract address')}
onChange={this.onChangeAddress}
onEnter={this.submit}
value={address || ''}
/>
<ValidateAddr
address={address}
onChange={this.onValidateAddr}
/>
{this.renderInputName()}
{this.renderInputAbi()}
</AddressRow>
);
}
status.account = address;
status.status = address ? 'success' : 'error';
status.message = 'contract added';
protected renderButtons = (): React.ReactNode => {
const { t } = this.props;
const { isAbiValid, isAddressValid, isNameValid } = this.state;
const isValid = isNameValid && isAddressValid && isAbiValid;
setIsOpen(false);
} catch (error) {
console.error(error);
return (
status.status = 'error';
status.message = (error as Error).message;
}
},
[abi, address, api, name, setIsOpen]
);
return (
<>
<Button
icon='save'
isDisabled={!isValid}
isPrimary
label={t<string>('Save')}
onClick={this.onAdd}
icon='add'
label={t('Add an existing contract')}
onClick={toggleIsOpen}
/>
);
}
private onChangeAddress = (address: string): void => {
this.setState({ address, isAddressValid: false });
}
private onValidateAddr = (isAddressValid: boolean): void => {
this.setState({ isAddressValid });
}
private onAdd = (): void => {
const { api } = this.props;
const status: Partial<ActionStatus> = { action: 'create' };
const { abi, address, name, tags } = this.state;
if (!address || !abi || !name) {
return;
}
try {
const json = {
contract: {
abi,
genesisHash: api.genesisHash.toHex()
},
name,
tags
};
keyring.saveContract(address, json);
status.account = address;
status.status = address ? 'success' : 'error';
status.message = 'contract added';
this.onClose();
} catch (error) {
console.error(error);
status.status = 'error';
status.message = (error as Error).message;
}
}
<Modal
header={t('Add an existing contract')}
onClose={toggleIsOpen}
open={isOpen}
>
<Modal.Content>
<AddressRow
defaultName={name}
isValid
value={address || null}
>
<Input
autoFocus
help={t<string>('The address for the deployed contract instance.')}
isError={!isAddressValid}
label={t<string>('contract address')}
onChange={setAddress}
value={address || ''}
/>
<ValidateAddr
address={address}
onChange={setIsAddressValid}
/>
<InputName
isContract
isError={!isNameValid}
onChange={setName}
value={name || undefined}
/>
<ABI
contractAbi={contractAbi}
errorText={errorText}
isContract
isError={isAbiError}
isSupplied={isAbiSupplied}
isValid={isAbiValid}
onChange={onChangeAbi}
onRemove={onRemoveAbi}
withLabel
/>
</AddressRow>
</Modal.Content>
<Modal.Actions onCancel={toggleIsOpen}>
<Button
icon='save'
isDisabled={!isValid}
isPrimary
label={t<string>('Save')}
onClick={_onAdd}
/>
</Modal.Actions>
</Modal>
</>
);
}
export default translate(withApi(Add));
export default React.memo(Add);

View File

@ -6,19 +6,19 @@ import { ContractCallOutcome } from '@polkadot/api-contract/types';
import { BareProps, StringOrNull } from '@polkadot/react-components/types';
import BN from 'bn.js';
import React, { useState, useEffect } from 'react';
import React, { useCallback, useState, useEffect, useMemo } from 'react';
import styled from 'styled-components';
import { Button, ButtonCancel, Dropdown, IconLink, InputAddress, InputBalance, InputNumber, Modal, Toggle, TxButton } from '@polkadot/react-components';
import { Button, ButtonCancel, Dropdown, IconLink, InputAddress, InputBalance, Modal, Toggle, TxButton } from '@polkadot/react-components';
import { PromiseContract as ApiContract } from '@polkadot/api-contract';
import { useAccountId, useFormField, useToggle } from '@polkadot/react-hooks';
import { createValue } from '@polkadot/react-params/values';
import { isNull } from '@polkadot/util';
import { BN_ZERO, isNull } from '@polkadot/util';
import Params from '../Params';
import { InputMegaGas, Params } from '../shared';
import Outcome from './Outcome';
import { useTranslation } from '../translate';
import { DEFAULT_GAS_LIMIT } from '../constants';
import { getCallMessageOptions } from './util';
import useWeight from '../useWeight';
interface Props extends BareProps {
callContract: ApiContract | null;
@ -35,13 +35,14 @@ function Call (props: Props): React.ReactElement<Props> | null {
const hasRpc = callContract?.hasRpcContractsCall;
const callMessage = callContract?.getMessage(isNull(callMessageIndex) ? undefined : callMessageIndex);
const [accountId, setAccountId] = useState<StringOrNull>(null);
const [endowment, setEndowment] = useState<BN>(new BN(0));
const [gasLimit, setGasLimit] = useState<BN>(new BN(DEFAULT_GAS_LIMIT));
const [isBusy, setIsBusy] = useState(false);
const [accountId, setAccountId] = useAccountId();
const [endowment, isEndowmentValid, setEndowment] = useFormField<BN>(BN_ZERO);
const [isBusy, , setIsBusy] = useToggle();
const [outcomes, setOutcomes] = useState<ContractCallOutcome[]>([]);
const [params, setParams] = useState<any[]>(callMessage ? callMessage.def.args.map(({ type }): any => createValue({ type })) : []);
const [useRpc, setUseRpc] = useState(hasRpc && callMessage && !callMessage.def.mutates);
const useWeightHook = useWeight();
const { isValid: isWeightValid, weight } = useWeightHook;
useEffect((): void => {
if (callContract && callMessageIndex) {
@ -63,54 +64,63 @@ function Call (props: Props): React.ReactElement<Props> | null {
setOutcomes([]);
}, [callContract]);
const _onChangeCallMessageIndexString = useCallback(
(callMessageIndexString: string): void => {
onChangeCallMessageIndex && onChangeCallMessageIndex(
parseInt(callMessageIndexString, 10) || 0
);
},
[onChangeCallMessageIndex]
);
const _constructTx = useCallback(
(): any[] => {
if (!accountId || !callMessage || !callMessage.fn || !callContract || !callContract.address) {
return [];
}
return [callContract.address.toString(), endowment, weight, callMessage.fn(...params)];
},
[accountId, callContract, callMessage, endowment, weight, params]
);
const _onSubmitRpc = useCallback(
(): void => {
if (!accountId || !callContract || !callMessage || !endowment || !weight) return;
!!callContract && callContract
.call('rpc', callMessage.def.name, endowment, weight, ...params)
.send(accountId)
.then(
(outcome: ContractCallOutcome): void => {
setOutcomes([outcome, ...outcomes]);
}
);
},
[accountId, callContract, callMessage, endowment, weight, outcomes, params]
);
const _onClearOutcomes = useCallback(
(): void => setOutcomes([]),
[]
);
const _onClearOutcome = useCallback(
(outcomeIndex: number) => (): void => {
setOutcomes(outcomes.slice(0, outcomeIndex).concat(outcomes.slice(outcomeIndex + 1)));
},
[outcomes]
);
const isValid = useMemo(
(): boolean => !!accountId && !!callContract && !!callContract.address && !!callContract.abi && isWeightValid && isEndowmentValid,
[accountId, callContract, isEndowmentValid, isWeightValid]
);
if (isNull(callContract) || isNull(callMessageIndex) || !callMessage) {
return null;
}
const _onChangeAccountId = (accountId: StringOrNull): void => setAccountId(accountId);
const _onChangeCallMessageIndexString = (callMessageIndexString: string): void => {
onChangeCallMessageIndex && onChangeCallMessageIndex(
parseInt(callMessageIndexString, 10) || 0
);
};
const _onChangeEndowment = (endowment?: BN): void => endowment && setEndowment(endowment);
const _onChangeGasLimit = (gasLimit?: BN): void => gasLimit && setGasLimit(gasLimit);
const _onChangeParams = (params: any[]): void => setParams(params);
const _toggleBusy = (): void => setIsBusy(!isBusy);
const _constructTx = (): any[] => {
if (!accountId || !callMessage || !callMessage.fn || !callContract || !callContract.address) {
return [];
}
return [callContract.address.toString(), endowment, gasLimit, callMessage.fn(...params)];
};
const _onSubmitRpc = (): void => {
if (!accountId || !callMessage) return;
callContract
.call('rpc', callMessage.def.name, endowment, gasLimit, ...params)
.send(accountId)
.then((outcome: ContractCallOutcome): void => {
setOutcomes([outcome, ...outcomes]);
})
.catch(console.error);
};
const _onClearOutcomes = (): void => setOutcomes([]);
const _onClearOutcome = (outcomeIndex: number) => (): void => {
setOutcomes(outcomes.slice(0, outcomeIndex).concat(outcomes.slice(outcomeIndex + 1)));
};
const isEndowmentValid = true;
const isGasValid = !gasLimit.isZero();
const isValid = !!accountId && isEndowmentValid && isGasValid && callContract && callContract.address && callContract.abi;
return (
<Modal
className={[className || '', 'app--contracts-Modal'].join(' ')}
@ -126,7 +136,7 @@ function Call (props: Props): React.ReactElement<Props> | null {
help={t<string>('Specify the user account to use for this contract call. And fees will be deducted from this account.')}
isDisabled={isBusy}
label={t<string>('call from account')}
onChange={_onChangeAccountId}
onChange={setAccountId}
type='account'
value={accountId}
/>
@ -152,7 +162,7 @@ function Call (props: Props): React.ReactElement<Props> | null {
/>
<Params
isDisabled={isBusy}
onChange={_onChangeParams}
onChange={setParams}
params={
callMessage
? callMessage.def.args
@ -167,25 +177,19 @@ function Call (props: Props): React.ReactElement<Props> | null {
isError={!isEndowmentValid}
isZeroable
label={t<string>('value')}
onChange={_onChangeEndowment}
onChange={setEndowment}
value={endowment}
/>
<InputNumber
bitLength={128}
defaultValue={DEFAULT_GAS_LIMIT}
help={t<string>('The maximum amount of gas that can be used by this call. If the code requires more, the call will fail.')}
isDisabled={isBusy}
isError={!isGasValid}
<InputMegaGas
help={t<string>('The maximum amount of gas to use for this contract call. If the call requires more, it will fail.')}
label={t<string>('maximum gas allowed')}
onChange={_onChangeGasLimit}
value={gasLimit}
{...useWeightHook}
/>
</div>
)}
{hasRpc && (
<Toggle
className='rpc-toggle'
isDisabled={!!callMessage && callMessage.def.mutates}
label={
useRpc
? t<string>('send as RPC call')
@ -213,10 +217,10 @@ function Call (props: Props): React.ReactElement<Props> | null {
icon='sign-in'
isDisabled={!isValid}
isPrimary
label={t<string>('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

View File

@ -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<Props> | null {
function Contract ({ className, contract: { abi, address }, onCall }: Props): React.ReactElement<Props> | 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<ActionStatus> = {
account: address,
action: 'forget'
};
try {
keyring.forgetContract(address.toString());
status.status = 'success';
status.message = t<string>('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<ActionStatus> = {
account: address,
action: 'forget'
};
try {
keyring.forgetContract(address.toString());
status.status = 'success';
status.message = t<string>('address forgotten');
} catch (error) {
status.status = 'error';
status.message = (error as Error).message;
}
_toggleForget();
};
return (
<ContractCard>
<Card className={className}>
{isForgetOpen && (
<Forget
address={address.toString()}
key='modal-forget-contract'
mode='contract'
onClose={_toggleForget}
onClose={toggleIsForgetOpen}
onForget={_onForget}
/>
)}
@ -78,7 +70,7 @@ function Contract (props: Props): React.ReactElement<Props> | null {
<Button
icon='trash'
isNegative
onClick={_toggleForget}
onClick={toggleIsForgetOpen}
tooltip={t<string>('Forget this contract')}
/>
<Button
@ -91,7 +83,8 @@ function Contract (props: Props): React.ReactElement<Props> | null {
</div>
}
isContract
isEditable
isEditableName
isEditableTags
type='contract'
value={address}
withBalance={false}
@ -107,8 +100,13 @@ function Contract (props: Props): React.ReactElement<Props> | null {
/>
</Expander>
</AddressRow>
</ContractCard>
</Card>
);
}
export default withRouter(Contract);
export default React.memo(
styled(Contract)`
min-width: 100%;
max-width: 100%;
`
);

View File

@ -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<Props> | 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<Props> | null {
const dateTime = new Date(time);
return (

View File

@ -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<Props> {
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<ApiContract[]>(filterContracts(api, props));
const [callContractIndex, setCallContractIndex] = useState<number>(0);
const [callMessageIndex, setCallMessageIndex] = useState<number>(0);
const [isAddOpen, setIsAddOpen] = useState(false);
const [isCallOpen, setIsCallOpen] = useState(false);
useEffect((): void => {
@ -39,7 +38,6 @@ function Contracts (props: Props): React.ReactElement<Props> {
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<Props> {
<>
<CardGrid
buttons={
<Button.Group>
<Button.Group isCentered>
{hasCode && (
<Button
icon='cloud upload'
label={t<string>('Deploy a code hash')}
onClick={showDeploy()}
label={t('Deploy a code hash')}
onClick={onShowDeploy()}
/>
)}
<Button
icon='add'
label={t<string>('Add an existing contract')}
onClick={_toggleAdd}
/>
<Add />
</Button.Group>
}
emptyText={t<string>('No contracts available')}
>
{contracts.map((contract: ApiContract, index): React.ReactNode => (
<ContractCard
basePath={basePath}
contract={contract}
key={contract.address.toString()}
onCall={_onCall(index)}
/>
))}
</CardGrid>
<Add
basePath={basePath}
isOpen={isAddOpen}
onClose={_toggleAdd}
/>
<Call
callContract={callContract}
callMessageIndex={callMessageIndex}

View File

@ -10,7 +10,7 @@ import { ApiPromise } from '@polkadot/api';
import { PromiseContract as Contract } from '@polkadot/api-contract';
import { getContractAbi } from '@polkadot/react-components/util';
import MessageSignature from '../MessageSignature';
import MessageSignature from '../shared/MessageSignature';
export function findCallMethod (callContract: Contract | null, callMethodIndex = 0): ContractABIMessage | null {
const message = callContract && callContract.abi.abi.contract.messages[callMethodIndex];

View File

@ -3,181 +3,197 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId } from '@polkadot/types/interfaces';
import { ApiProps } from '@polkadot/react-api/types';
import { I18nProps } from '@polkadot/react-components/types';
import { StringOrNull, VoidFn } from '@polkadot/react-components/types';
import { CodeStored } from './types';
import BN from 'bn.js';
import React from 'react';
import { RouteComponentProps } from 'react-router';
import { withRouter } from 'react-router-dom';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { SubmittableResult } from '@polkadot/api';
import { Abi } from '@polkadot/api-contract';
import { withApi, withMulti } from '@polkadot/react-api/hoc';
import { Dropdown, InputBalance, TxButton } from '@polkadot/react-components';
import createValues from '@polkadot/react-params/values';
import { Dropdown, InputAddress, InputBalance, Modal, TxButton } from '@polkadot/react-components';
import { useFormField, useNonEmptyString, useNonZeroBn, useApi } from '@polkadot/react-hooks';
import keyring from '@polkadot/ui-keyring';
import { isFunction } from '@polkadot/util';
import MessageSignature from './MessageSignature';
import ContractModal, { ContractModalProps, ContractModalState } from './Modal';
import Params from './Params';
import { ABI, InputMegaGas, InputName, MessageSignature, Params } from './shared';
import store from './store';
import translate from './translate';
import { ENDOWMENT, DEFAULT_GAS_LIMIT } from './constants';
import { useTranslation } from './translate';
import useAbi from './useAbi';
import useWeight from './useWeight';
import { ENDOWMENT } from './constants';
type CodeOptions = { text: string; value: string }[];
type ConstructOptions = { key: string; text: React.ReactNode; value: string }[];
interface Props extends ContractModalProps, ApiProps, I18nProps, RouteComponentProps {
codeHash?: string;
interface Props {
basePath: string;
allCodes: CodeStored[];
codeHash: string;
constructorIndex?: number;
isOpen?: boolean;
onClose: VoidFn;
setCodeHash: React.Dispatch<string>;
setConstructorIndex: React.Dispatch<number>;
}
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<Props, State> {
protected headerText = 'Deploy a new contract';
function Deploy ({ allCodes, basePath, codeHash, constructorIndex = 0, isOpen, onClose, setCodeHash, setConstructorIndex }: Props): React.ReactElement<Props> {
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<StringOrNull>(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<State, never> {
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<State> => {
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<State, never> => {
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<State, never> => {
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: (
<MessageSignature
asConstructor
message={constr}
/>
),
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: (
<MessageSignature
asConstructor
message={constr}
/>
),
value: `${index}`
};
});
},
[contractAbi]
);
const [params, setParams] = useState<any[]>(
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 (
<Modal
header={t('Add an existing code hash')}
onClose={onClose}
open={isOpen}
>
<Modal.Content>
<InputAddress
help={t('Specify the user account to use for this deployment. Any fees will be deducted from this account.')}
isInput={false}
label={t('deployment account')}
onChange={setAccountId}
type='account'
value={accountId}
/>
<Dropdown
defaultValue={defaultCode}
help={t<string>('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<string>('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()}
<InputName
isContract
isError={!isNameValid}
onChange={setName}
value={name || ''}
/>
{
isAbiSupplied
? null
: this.renderInputAbi()
: (
<ABI
contractAbi={contractAbi}
errorText={errorText}
isError={isAbiError}
isSupplied={isAbiSupplied}
isValid={isAbiValid}
onChange={onChangeAbi}
onRemove={onRemoveAbi}
withLabel
/>
)
}
{
contractAbi
@ -185,19 +201,16 @@ class Deploy extends ContractModal<Props, State> {
<Dropdown
help={t<string>('The deployment constructor information for this contract, as provided by the ABI.')}
isDisabled={contractAbi.abi.contract.constructors.length <= 1}
label={t<string>('constructor')}
onChange={this.onChangeConstructorIndex}
label={t('deployment constructor')}
onChange={setConstructorIndex}
options={constructOptions}
value={`${constructorIndex}`}
withLabel
/>
)
: null
}
<Params
isDisabled={isBusy}
onChange={this.onChangeParams}
onEnter={this.sendTx}
onChange={setParams}
params={
contractAbi && constructorIndex >= 0
? contractAbi.abi.contract.constructors[constructorIndex].args
@ -206,121 +219,41 @@ class Deploy extends ContractModal<Props, State> {
/>
<InputBalance
help={t<string>('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<string>('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 (
<TxButton
accountId={accountId}
icon='cloud upload'
isDisabled={!isValid}
isPrimary
label={t<string>('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<State, never> | 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 };
});
}
}
<InputMegaGas
help={t<string>('The maximum amount of gas that can be used by this deployment, if the code requires more, the deployment will fail.')}
label={t<string>('maximum gas allowed')}
{...useWeightHook}
/>
</Modal.Content>
<Modal.Actions onCancel={onClose}>
<TxButton
accountId={accountId}
icon='cloud upload'
isDisabled={!isValid}
isPrimary
label={t('Deploy')}
onClick={onClose}
onSuccess={_onSuccess}
params={_constructCall}
tx={
api.tx.contracts
? (
!api.tx.contracts.instantiate
? 'contracts.create' // V2 (new)
: 'contracts.instantiate' // V2 (old)
)
: 'contract.create' // V1
}
withSpinner
/>
</Modal.Actions>
</Modal>
);
}
export default withMulti(
withRouter(Deploy),
translate,
withApi
);
export default React.memo(Deploy);

View File

@ -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<P extends ContractModalProps, S extends ContractModalState> extends TxComponent<P, S> {
// 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 (
<Modal
className='app--contracts-Modal'
header={t(this.headerText)}
onClose={this.onClose}
open={isOpen}
>
<Modal.Content>
{this.renderContent()}
</Modal.Content>
<Modal.Actions onCancel={this.onClose}>
{this.renderButtons()}
</Modal.Actions>
</Modal>
);
}
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 (
<ABI
help={t(
this.isContract
? '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.'
: 'The ABI for the WASM code. In this step it is optional, but setting it here simplifies the setup of contract instances.'
)}
isDisabled={isBusy}
isRequired={this.isContract}
label={t(
this.isContract
? 'contract ABI'
: 'contract ABI (optional)'
)}
onChange={this.onAddAbi}
/>
);
}
protected renderInputAccount (): React.ReactNode {
const { t } = this.props;
const { accountId, isBusy } = this.state;
return (
<InputAddress
help={t<string>('Specify the user account to use for this deployment. And fees will be deducted from this account.')}
isDisabled={isBusy}
isInput={false}
label={t<string>('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 (
<Input
help={t(
this.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={!isNameValid}
label={t(
this.isContract
? 'contract name'
: 'code bundle name'
)}
onChange={this.onChangeName}
onEnter={this[isNew ? 'sendTx' : 'submit']}
value={name || ''}
/>
);
}
protected renderInputGas (): React.ReactNode {
const { t } = this.props;
const { gasLimit, isBusy } = this.state;
const isGasValid = !gasLimit.isZero();
return (
<InputNumber
bitLength={128}
help={t<string>('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<string>('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;

View File

@ -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 {

View File

@ -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

View File

@ -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<Props> {
const { t } = useTranslation();
const { allAccounts } = useAccounts();
const { allContracts } = useContracts();
const [codeHash, setCodeHash] = useState<string | undefined>();
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<Props, State> {
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<State, never> {
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 (
<main className='contracts--App'>
<HelpOverlay md={introMd as string} />
<header>
<Tabs
basePath={basePath}
hidden={hidden}
items={[
{
name: 'code',
text: 'Code'
},
{
isRoot: true,
name: 'contracts',
text: 'Contracts'
}
].map((tab): TabItem => ({ ...tab, text: t(tab.text) }))
return (
<main className='contracts--App'>
<HelpOverlay md={introMd as string} />
<header>
<Tabs
basePath={basePath}
hidden={hidden}
items={[
{
name: 'code',
text: 'Code'
},
{
isRoot: true,
name: 'contracts',
text: 'Contracts'
}
/>
</header>
<Switch>
<Route
path={`${basePath}/code`}
render={this.renderComponent(Codes)}
/>
<Route
exact
render={this.renderComponent(Contracts)}
/>
</Switch>
].map((tab): TabItem => ({ ...tab, text: t(tab.text) }))
}
/>
</header>
<Switch>
<Route path={`${basePath}/code`}>
<Codes {...componentProps} />
</Route>
<Route exact>
<Contracts {...componentProps} />
</Route>
</Switch>
{codeHash && (
<Deploy
allCodes={allCodes}
basePath={basePath}
codeHash={codeHash}
constructorIndex={constructorIndex}
isOpen={isDeployOpen}
onClose={this.hideDeploy}
onClose={_onCloseDeploy}
setCodeHash={setCodeHash}
setConstructorIndex={setConstructorIndex}
/>
</main>
);
}
private renderComponent (Component: React.ComponentType<ComponentProps>): () => React.ReactNode {
return (): React.ReactNode => {
const { accounts, basePath, contracts, onStatusChange } = this.props;
const { updated } = this.state;
if (!contracts) {
return null;
}
return (
<Component
accounts={accounts}
basePath={basePath}
contracts={contracts}
hasCode={store.hasCode}
onStatusChange={onStatusChange}
showDeploy={this.showDeploy}
updated={updated}
/>
);
};
}
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() });
}
)}
</main>
);
}
export default withMulti(
withRouter(ContractsApp),
translate,
withObservable(keyring.accounts.subject, { propName: 'accounts' }),
withObservable(keyring.contracts.subject, { propName: 'contracts' })
);
export default React.memo(ContractsApp);

View File

@ -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 (
<Messages
contractAbi={contractAbi}
isLabelled={withLabel}
isRemovable={!isDisabled}
onRemove={onRemove}
onSelectConstructor={onSelectConstructor}
withConstructors
/>
);
}
function ABI (props: Props): React.ReactElement<Props> {
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 (
<div className={className}>
{
(contractAbi && isValid)
? (
withLabel
? (
<Labelled
help={help}
label={label}
>
{renderMessages(props)}
</Labelled>
)
: renderMessages(props)
)
: (
<InputFile
help={help}
isDisabled={isDisabled}
isError={isError}
label={label}
onChange={onChange}
placeholder={
isSupplied && !isValid
? (
<>
{t<string>('invalid ABI file selected')}
{!!errorText && (
<>
{' — '}
{t<string>(errorText)}
</>
)}
</>
)
: t<string>('click to select or drag and drop a JSON ABI file')
}
/>
)
}
</div>
);
}
export default React.memo(
styled(ABI)`
min-height: 4rem;
`
);

View File

@ -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 = '<unknown>';
function CodeRow ({ buttons, children, className, code: { json }, isInline, withTags }: Props): React.ReactElement<Props> {
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 (
<Row
address={
<CopyButton
isAddress
value={codeHash}
>
<span>{toShortAddress(codeHash)}</span>
</CopyButton>
}
buttons={buttons}
className={className}
icon={
<div className='ui--CodeRow-icon'>
<Icon
name='code'
size='large'
/>
</div>
}
isEditableName
isEditableTags
isInline={isInline}
name={name}
onChangeName={setName}
onChangeTags={setTags}
onSaveName={_onSaveName}
onSaveTags={_onSaveTags}
tags={withTags && tags}
>
{children}
</Row>
);
}
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;
}
`
);

View File

@ -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<Props> {
const { t } = useTranslation();
return (
<div className={className}>
<InputNumber
className='contracts--InputMegaGas-input'
help={help}
isError={!isValid}
label={label}
onChange={setMegaGas}
value={megaGas}
>
<div className='contracts--InputMegaGas-meter'>
{t<string>('{{executionTime}}s execution time', { replace: { executionTime: executionTime.toFixed(3) } })}
<aside>
{t<string>('{{percentage}}% of block time', { replace: { percentage } })}
</aside>
<Progress
className='contracts--InputMegaGas-progress'
color={percentage < 100 ? 'green' : 'red'}
total={100}
value={percentage}
/>
</div>
</InputNumber>
</div>
);
}
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;
}
}
}
}
`
);

View File

@ -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<Props> {
const { t } = useTranslation();
return (
<Input
className={className}
help={t<string>(
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<string>(
isContract
? 'contract name'
: 'code bundle name'
)}
onChange={onChange}
onEnter={onEnter}
value={value}
/>
);
}
export default React.memo(InputName);

View File

@ -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<Props> {
function MessageSignature ({ className, message: { args, mutates, name, returnType }, params = [], asConstructor = false, withTooltip = false }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
return (
<Signature>
<Name>
<div className={className}>
<span className='ui--MessageSignature-name'>
{name}
</Name>
</span>
(
{args.map(({ name, type }, index): React.ReactNode => {
return (
<React.Fragment key={`${name}-args-${index}`}>
{name}:
{' '}
<Type>
<span className='ui--MessageSignature-type'>
{params && params[index]
? <b>{truncate((params as string[])[index].toString())}</b>
: displayType(type)
}
</Type>
</span>
{index < args.length - 1 && ', '}
</React.Fragment>
);
@ -80,15 +56,15 @@ function MessageSignature ({ message: { args, mutates, name, returnType }, param
<>
:
{' '}
<ReturnType>
<span className='ui--MessageSignature-returnType'>
{displayType(returnType)}
</ReturnType>
</span>
</>
)}
{mutates && (
<>
<Icon
className='mutates'
className='ui--MessageSignature-mutates'
data-for={`mutates-${name}`}
data-tip
name='database'
@ -101,8 +77,33 @@ function MessageSignature ({ message: { args, mutates, name, returnType }, param
)}
</>
)}
</Signature>
</div>
);
}
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;
}
`
);

View File

@ -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;

View File

@ -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';

View File

@ -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<BN | undefined>
}

View File

@ -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
};
}

View File

@ -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<BN | undefined>(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
};
}

View File

@ -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<Props> {
label={t<string>('threshold')}
onChange={_setThreshold}
placeholder={t<string>('Positive number between 1 and {{memberCount}}', { replace: { memberCount: members.length } })}
value={threshold || new BN(0)}
value={threshold || BN_ZERO}
/>
</Modal.Column>
<Modal.Column>

View File

@ -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<Props> {
const [available, setAvailable] = useState<string[]>([]);
const [defaultVotes, setDefaultVotes] = useState<string[]>([]);
const [votes, setVotes] = useState<string[]>([]);
const [voteValue, setVoteValue] = useState(new BN(0));
const [voteValue, setVoteValue] = useState(BN_ZERO);
useEffect((): void => {
if (electionsInfo) {

View File

@ -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<Props> {
const { api } = useApi();
const bestNumber = useCall<BlockNumber>(api.derive.chain.bestNumber, []) || new BN(0);
const bestNumber = useCall<BlockNumber>(api.derive.chain.bestNumber, []) || BN_ZERO;
return (
<tr>

View File

@ -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<BN>(api.derive.democracy.sqrtElectorate, []);
const [result, setResult] = useState<Result>({ changeAye: ZERO, changeNay: ZERO });
const [result, setResult] = useState<Result>({ changeAye: BN_ZERO, changeNay: BN_ZERO });
useEffect((): void => {
sqrtElectorate && setResult(

View File

@ -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)

View File

@ -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<Props> {
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]);

View File

@ -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<string>('target')}
>
<BlockToTime blocks={ONE_BLOCK} />
<BlockToTime blocks={BN_ONE} />
</CardSummary>
{api.query.balances && (
<CardSummary

View File

@ -44,7 +44,6 @@ function AssetCard ({ assetId, className = '', name, onForget, onSaveName }: Pro
/>
)}
defaultName={name}
isEditable
onSaveName={_onSaveName}
/>
</div>

View File

@ -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<RowProps, 'onSaveName'> {
onSaveName: (name: string) => void;
assetId: string;
}
class AssetRow extends Row<Props, RowState> {
constructor (props: Props) {
super(props);
export default function AssetRow ({ assetId, buttons, children, className, defaultName = 'New Asset', isDisabled, isInline, onSaveName }: Props): React.ReactElement<Props> {
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 (
<div
className={`ui--Row ${className}`}
>
<div className='ui--Row-base'>
<div className='ui--Row-details'>
{this.renderName()}
{this.renderAssetId()}
</div>
{this.renderButtons()}
return (
<Row
buttons={buttons}
className={className}
details={
<div>
<CopyButton value={assetId}>
<span>{t('Asset ID')}: {assetId}</span>
</CopyButton>
</div>
</div>
);
}
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 (
<div className='ui--Row-details'>
<CopyButton value={assetId}>
<span>{t<string>('Asset ID')}: {assetId}</span>
</CopyButton>
</div>
);
}
}
isDisabled={isDisabled}
isEditableName
isInline={isInline}
name={name}
onChangeName={setName}
onSaveName={onSaveName}
>
{children}
</Row>
);
}
export default translate(styled(AssetRow)`${styles}`);

View File

@ -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<Props> {
const { api } = useApi();
const [assetId, setAssetId] = useState('0');
const [amount, setAmount] = useState<BN | undefined>(new BN(0));
const [amount, setAmount] = useState<BN | undefined>(BN_ZERO);
const [extrinsic, setExtrinsic] = useState<SubmittableExtrinsic | null>(null);
const [hasAvailable, setHasAvailable] = useState(true);
const [options, setOptions] = useState<Option[]>([]);

View File

@ -5,6 +5,7 @@
import BN from 'bn.js';
import React, { useState } from 'react';
import { Button, Input, InputNumber, Modal } from '@polkadot/react-components';
import { BN_ZERO } from '@polkadot/util';
import { useTranslation } from '../translate';
@ -19,10 +20,10 @@ interface Props extends ModalProps {
function Create ({ onClose, onRegister }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [assetId, setAssetId] = useState(new BN(0));
const [assetId, setAssetId] = useState(BN_ZERO);
const [name, setName] = useState('new asset');
const _onChangeAssetId = (assetId: BN | undefined): void => setAssetId(assetId || new BN(0));
const _onChangeAssetId = (assetId: BN | undefined): void => setAssetId(assetId || BN_ZERO);
const _onCommit = (): void => {
onRegister(assetId, name);

View File

@ -9,7 +9,7 @@ import BN from 'bn.js';
import React, { useMemo, useRef } from 'react';
import { useApi, useFormField, useModal } from '@polkadot/react-hooks';
import { createType } from '@polkadot/types';
import { u8aToHex, u8aToString } from '@polkadot/util';
import { BN_THOUSAND, u8aToHex, u8aToString } from '@polkadot/util';
import { Button, Dropdown, InputFile, InputNumber, InputWasm, Modal, TxButton } from '@polkadot/react-components';
@ -30,9 +30,7 @@ const schedulingOptions = [{
value: 'Dynamic'
}];
const ONE_THOUSAND = new BN(1000);
function Register ({ nextFreeId = ONE_THOUSAND, sudoKey }: Props): React.ReactElement<Props> | null {
function Register ({ nextFreeId = BN_THOUSAND, sudoKey }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const { isOpen, onClose, onOpen } = useModal();

View File

@ -6,6 +6,7 @@ import BN from 'bn.js';
import React, { useState } from 'react';
import { InputAddress, InputBalance, Modal, TxButton } from '@polkadot/react-components';
import { BalanceFree } from '@polkadot/react-query';
import { BN_ZERO } from '@polkadot/util';
import { useTranslation } from '../../translate';
import ValidateAmount from './InputValidateAmount';
@ -15,8 +16,6 @@ interface Props {
stashId: string;
}
const ZERO = new BN(0);
function BondExtra ({ onClose, stashId }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [amountError, setAmountError] = useState<string | null>(null);
@ -73,7 +72,7 @@ function BondExtra ({ onClose, stashId }: Props): React.ReactElement<Props> {
<TxButton
accountId={stashId}
icon='sign-in'
isDisabled={!maxAdditional?.gt(ZERO)}
isDisabled={!maxAdditional?.gt(BN_ZERO)}
isPrimary
label={t<string>('Bond more')}
onStart={onClose}

View File

@ -12,6 +12,7 @@ import { Button, Table } from '@polkadot/react-components';
import { useCall, useApi } from '@polkadot/react-hooks';
import { FormatBalance } from '@polkadot/react-query';
import { Option } from '@polkadot/types';
import { BN_ZERO } from '@polkadot/util';
import ElectionBanner from '../ElectionBanner';
import { useTranslation } from '../translate';
@ -48,7 +49,7 @@ function Actions ({ className = '', isInElection, next, ownStashes, targets, val
stakingLedger
? total.add(stakingLedger.total.unwrap())
: total,
new BN(0)),
BN_ZERO),
foundStashes: ownStashes.sort((a, b) =>
(a.isStashValidating ? 1 : (a.isStashNominating ? 5 : 99)) - (b.isStashValidating ? 1 : (b.isStashNominating ? 5 : 99))
)

View File

@ -8,6 +8,7 @@ import BN from 'bn.js';
import React, { useCallback } from 'react';
import { InputAddress, InputNumber, Modal } from '@polkadot/react-components';
import { useApi } from '@polkadot/react-hooks';
import { BN_ZERO, BN_HUNDRED as MAX_COMM } from '@polkadot/util';
import { useTranslation } from '../../translate';
@ -19,9 +20,7 @@ interface Props {
withSenders?: boolean;
}
const COMM_MUL = new BN(10000000);
const MAX_COMM = new BN(100);
const ZERO = new BN(0);
const COMM_MUL = new BN(1e7);
function Validate ({ className = '', controllerId, onChange, stashId, withSenders }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
@ -29,7 +28,7 @@ function Validate ({ className = '', controllerId, onChange, stashId, withSender
const _setCommission = useCallback(
(value?: BN): void => {
const commission = (value || ZERO).mul(COMM_MUL);
const commission = (value || BN_ZERO).mul(COMM_MUL);
onChange({
validateTx: api.tx.staking.validate({

View File

@ -7,8 +7,7 @@ import { DeriveSessionInfo } from '@polkadot/api-derive/types';
import BN from 'bn.js';
import { useEffect, useState } from 'react';
import { useApi, useCall } from '@polkadot/react-hooks';
const ONE = new BN(1);
import { BN_ONE } from '@polkadot/util';
export default function useUnbondDuration (): BN | undefined {
const { api } = useApi();
@ -18,7 +17,7 @@ export default function useUnbondDuration (): BN | undefined {
useEffect((): void => {
// We check sessionLength, for aura this is not properly calculated (not exposed),
// so the actual real block value would be invalid here
sessionInfo && sessionInfo.sessionLength.gt(ONE) && setDuration(
sessionInfo && sessionInfo.sessionLength.gt(BN_ONE) && setDuration(
sessionInfo.eraLength.mul(api.consts.staking.bondingDuration)
);
}, [api, sessionInfo]);

View File

@ -11,7 +11,7 @@ import styled from 'styled-components';
import { Button, Table } from '@polkadot/react-components';
import { useApi, useOwnEraRewards } from '@polkadot/react-hooks';
import { FormatBalance } from '@polkadot/react-query';
import { isFunction } from '@polkadot/util';
import { BN_ZERO, isFunction } from '@polkadot/util';
import ElectionBanner from '../ElectionBanner';
import { useTranslation } from '../translate';
@ -81,7 +81,7 @@ function extractStashes (allRewards: Record<string, DeriveStakerReward[]>): Payo
.map(([stashId, rewards]): PayoutStash => ({
available: rewards.reduce((result, { validators }) =>
Object.values(validators).reduce((result, { value }) =>
result.iadd(value), result), new BN(0)
result.iadd(value), result), BN_ZERO
),
rewards,
stashId
@ -102,7 +102,7 @@ function Payouts ({ className = '', isInElection }: Props): React.ReactElement<P
if (allRewards) {
const stashes = extractStashes(allRewards);
const stashTotal = stashes.length
? stashes.reduce((total: BN, { available }) => total.add(available), new BN(0))
? stashes.reduce((total: BN, { available }) => total.add(available), BN_ZERO)
: null;
setPayouts({

View File

@ -7,8 +7,7 @@ import { DeriveSessionProgress } from '@polkadot/api-derive/types';
import BN from 'bn.js';
import { useEffect, useState } from 'react';
import { useApi, useCall } from '@polkadot/react-hooks';
const ONE = new BN(1);
import { BN_ONE } from '@polkadot/util';
export default function useEraBlocks (era?: BN): BN | undefined {
const { api } = useApi();
@ -17,12 +16,12 @@ export default function useEraBlocks (era?: BN): BN | undefined {
const [duration, setDuration] = useState<BN | undefined>();
useEffect((): void => {
depth && era && progress && progress.sessionLength.gt(ONE) && setDuration(
depth && era && progress && progress.sessionLength.gt(BN_ONE) && setDuration(
progress.eraLength
.mul(
depth
.sub(progress.activeEra.sub(era))
.add(ONE)
.add(BN_ONE)
)
.sub(progress.eraProgress)
);

View File

@ -11,7 +11,7 @@ import { useEffect, useState } from 'react';
import { registry } from '@polkadot/react-api';
import { useAccounts, useApi, useCall, useDebounce, useFavorites } from '@polkadot/react-hooks';
import { Option } from '@polkadot/types';
import { formatBalance } from '@polkadot/util';
import { BN_ONE, BN_ZERO, formatBalance } from '@polkadot/util';
import { STORE_FAVS_BASE } from './constants';
@ -63,9 +63,9 @@ function sortValidators (list: ValidatorInfo[]): ValidatorInfo[] {
);
}
function extractInfo (allAccounts: string[], amount: BN = baseBalance(), electedInfo: DeriveStakingElected, favorites: string[], lastReward = new BN(1)): Partial<SortedTargets> {
function extractInfo (allAccounts: string[], amount: BN = baseBalance(), electedInfo: DeriveStakingElected, favorites: string[], lastReward = BN_ONE): Partial<SortedTargets> {
const nominators: string[] = [];
let totalStaked = new BN(0);
let totalStaked = BN_ZERO;
const perValidatorReward = lastReward.divn(electedInfo.info.length);
const validators = sortValidators(
electedInfo.info.map(({ accountId, exposure: _exposure, validatorPrefs }): ValidatorInfo => {
@ -86,7 +86,7 @@ function extractInfo (allAccounts: string[], amount: BN = baseBalance(), elected
const rewardSplit = perValidatorReward.sub(validatorPayment);
const rewardPayout = rewardSplit.gtn(0)
? amount.mul(rewardSplit).div(amount.add(bondTotal))
: new BN(0);
: BN_ZERO;
const isNominating = exposure.others.reduce((isNominating, indv): boolean => {
const nominator = indv.who.toString();
@ -105,7 +105,7 @@ function extractInfo (allAccounts: string[], amount: BN = baseBalance(), elected
bondOwn,
bondShare: 0,
bondTotal,
commissionPer: (((prefs as ValidatorPrefs).commission?.unwrap() || new BN(0)).toNumber() / 10_000_000),
commissionPer: (((prefs as ValidatorPrefs).commission?.unwrap() || BN_ZERO).toNumber() / 10_000_000),
isCommission: !!(prefs as ValidatorPrefs).commission,
isFavorite: favorites.includes(key),
isNominating,
@ -134,7 +134,7 @@ export default function useSortedTargets (): SortedTargets {
const [favorites, toggleFavorite] = useFavorites(STORE_FAVS_BASE);
const electedInfo = useCall<DeriveStakingElected>(api.derive.staking.electedInfo, []);
const lastEra = useCall<BN>(api.derive.session.indexes, [], {
transform: ({ activeEra }: DeriveSessionIndexes) => activeEra.gtn(0) ? activeEra.subn(1) : new BN(0)
transform: ({ activeEra }: DeriveSessionIndexes) => activeEra.gtn(0) ? activeEra.subn(1) : BN_ZERO
});
const lastReward = useCall<BN>(lastEra && api.query.staking.erasValidatorReward, [lastEra], {
transform: (optBalance: Option<Balance>) => optBalance.unwrapOrDefault()

View File

@ -10,17 +10,16 @@ import React, { useCallback, useState } from 'react';
import styled from 'styled-components';
import { Button, Icon, Extrinsic, Toggle, TxButton, InputNumber } from '@polkadot/react-components';
import { useApi, useToggle } from '@polkadot/react-hooks';
import { BN_ZERO } from '@polkadot/util';
import { useTranslation } from './translate';
const ZERO = new BN(0);
function Propose ({ className = '', isMine, sudoKey }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api, apiDefaultTxSudo } = useApi();
const [withWeight, toggleWithWeight] = useToggle();
const [method, setMethod] = useState<SubmittableExtrinsic<'promise'> | null>(null);
const [weight, setWeight] = useState<BN>(ZERO);
const [weight, setWeight] = useState<BN>(BN_ZERO);
const _onChangeExtrinsic = useCallback(
(method: SubmittableExtrinsic<'promise'> | null = null) =>
@ -29,7 +28,7 @@ function Propose ({ className = '', isMine, sudoKey }: Props): React.ReactElemen
);
const _onChangeWeight = useCallback(
(weight: BN = ZERO) => setWeight(weight),
(weight: BN = BN_ZERO) => setWeight(weight),
[]
);
@ -45,7 +44,7 @@ function Propose ({ className = '', isMine, sudoKey }: Props): React.ReactElemen
{withWeight && (
<InputNumber
help={t<string>('The unchecked weight as specified for the sudoUncheckedWeight call.')}
isError={weight.eq(ZERO)}
isError={weight.eq(BN_ZERO)}
isZeroable={false}
label={t<string>('unchecked weight for this call')}
onChange={_onChangeWeight}
@ -68,7 +67,7 @@ function Propose ({ className = '', isMine, sudoKey }: Props): React.ReactElemen
<TxButton
accountId={sudoKey}
icon='sign-in'
isDisabled={!method || (withWeight ? weight.eq(ZERO) : false)}
isDisabled={!method || (withWeight ? weight.eq(BN_ZERO) : false)}
label={t<string>('Submit Sudo')}
params={
withWeight

View File

@ -7,6 +7,7 @@ import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { InputAddress, Labelled } from '@polkadot/react-components';
import { Nonce } from '@polkadot/react-query';
import { BN_ZERO } from '@polkadot/util';
import { useTranslation } from '../translate';
@ -20,7 +21,7 @@ interface Props {
function Account ({ className = '', defaultValue, isError, onChange }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [accountId, setAccountId] = useState<string | null | undefined>(defaultValue);
const [accountNonce, setAccountNonce] = useState(new BN(0));
const [accountNonce, setAccountNonce] = useState(BN_ZERO);
useEffect((): void => {
onChange(accountId, accountNonce);

View File

@ -9,7 +9,7 @@ import { BareProps } from './types';
import BN from 'bn.js';
import React from 'react';
import styled from 'styled-components';
import { formatBalance, formatNumber, hexToString, isObject } from '@polkadot/util';
import { BN_ZERO, formatBalance, formatNumber, hexToString, isObject } from '@polkadot/util';
import { Expander, Icon, Tooltip } from '@polkadot/react-components';
import { withCalls, withMulti } from '@polkadot/react-api/hoc';
import { useAccounts } from '@polkadot/react-hooks';
@ -128,7 +128,7 @@ function skipStakingIf ({ stakingInfo, withBalance = true, withValidatorPrefs =
// calculates the bonded, first being the own, the second being nominated
function calcBonded (stakingInfo?: DeriveStakingAccount, bonded?: boolean | BN[]): [BN, BN[]] {
let other: BN[] = [];
let own = new BN(0);
let own = BN_ZERO;
if (Array.isArray(bonded)) {
other = bonded

View File

@ -2,275 +2,64 @@
// 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 { DeriveAccountInfo, DeriveStakingAccount } from '@polkadot/api-derive/types';
import { ApiProps } from '@polkadot/react-api/types';
import { I18nProps } from '@polkadot/react-components/types';
import { AccountId, AccountIndex, Address } from '@polkadot/types/interfaces';
import BN from 'bn.js';
import React from 'react';
import styled from 'styled-components';
import { withCalls, withMulti } from '@polkadot/react-api/hoc';
import { useAccountInfo } from '@polkadot/react-hooks';
import BaseIdentityIcon from '@polkadot/react-identicon';
import keyring from '@polkadot/ui-keyring';
import AddressInfo, { BalanceActiveType, ValidatorPrefsType } from './AddressInfo';
import { classes, getAddressName, getAddressTags, toShortAddress } from './util';
import IdentityIcon, { getIdentityTheme } from './IdentityIcon';
import Row, { RowProps, RowState as State, styles } from './Row';
import translate from './translate';
import { toShortAddress } from './util';
import IdentityIcon from './IdentityIcon';
import Row, { RowProps } from './Row';
export interface Props extends I18nProps, RowProps {
bonded?: BN | BN[];
extraInfo?: [React.ReactNode, React.ReactNode][];
export interface Props extends RowProps {
isContract?: boolean;
isDisabled?: boolean;
isValid?: boolean;
label?: string;
accountsInfo?: DeriveAccountInfo;
noDefaultNameOpacity?: boolean;
overlay?: React.ReactNode;
stakingInfo?: DeriveStakingAccount;
value: AccountId | AccountIndex | Address | string | null;
withAddressOrName?: boolean;
withBalance?: boolean | BalanceActiveType;
withIndex?: boolean;
withIndexOrAddress?: boolean;
withSmallIcon?: boolean;
withValidatorPrefs?: boolean | ValidatorPrefsType;
value: AccountId | AccountIndex | Address | string;
withSidebar?: boolean;
withTags?: boolean;
}
const DEFAULT_ADDR = '5'.padEnd(16, 'x');
const DEFAULT_ADDR = '5'.padEnd(48, 'x');
const ICON_SIZE = 48;
const ICON_SIZE_SMALL = 32;
const EMPTY_INFO: DeriveAccountInfo = {
identity: {
judgements: []
}
};
class AddressRow extends Row<ApiProps & Props, State> {
public state: State;
function AddressRow ({ buttons, children, className, defaultName, isContract = false, isDisabled, isInline, isValid: propsIsValid, overlay, value, withTags = false }: Props): React.ReactElement<Props> | null {
const { accountIndex, isNull, name, onSaveName, onSaveTags, setName, setTags, tags } = useAccountInfo(value ? value.toString() : null, isContract);
constructor (props: ApiProps & Props) {
super(props);
const isValid = !isNull && (propsIsValid || value || accountIndex);
const Icon = value ? IdentityIcon : BaseIdentityIcon;
this.state = this.createState();
}
public static getDerivedStateFromProps ({ accountsInfo = EMPTY_INFO, defaultName, isEditable, noDefaultNameOpacity, type, value }: Props, prevState: State): State | null {
const accountId = accountsInfo.accountId || value;
const address = accountId
? accountId.toString()
: DEFAULT_ADDR;
const [, isDefault, nameInner] = accountsInfo.nickname
? [true, false, accountsInfo.nickname.toUpperCase()]
: getAddressName(address, type, defaultName || '<unknown>');
const name = isDefault && !noDefaultNameOpacity && !isEditable
? <div className='ui--Row-placeholder'>{nameInner}</div>
: nameInner;
const tags = getAddressTags(address, type);
const state: Partial<State> = { tags };
let hasChanged = false;
if (address !== prevState.address) {
state.address = address;
hasChanged = true;
}
if (!prevState.isEditingName && name !== prevState.name) {
state.name = name as string;
hasChanged = true;
}
return hasChanged
? state as State
: null;
}
public render (): React.ReactNode {
const { accountsInfo = EMPTY_INFO, className = '', isContract, isDisabled, isInline, label, overlay } = this.props;
const { accountId, accountIndex } = accountsInfo;
const isValid = this.props.isValid || accountId || accountIndex;
return (
<div className={classes('ui--Row', isDisabled && 'isDisabled', !isValid && 'isInvalid', isInline && 'isInline', className)}>
<div className='ui--Row-base'>
{this.renderIcon()}
<div className='ui--Row-details'>
{label && <label className='account-label'>{label}</label>}
{this.renderAddressAndName()}
{this.renderAccountIndex()}
{!isContract && this.renderBalances()}
{this.renderTags()}
</div>
{this.renderButtons()}
</div>
{this.renderChildren()}
{overlay}
</div>
);
}
private createState (): State {
const { accountsInfo = EMPTY_INFO, defaultName, type, value } = this.props;
const accountId = accountsInfo.accountId || value;
const address = accountId
? accountId.toString()
: DEFAULT_ADDR;
const [, , name] = getAddressName(address, type, defaultName || '<unknown>');
const tags = getAddressTags(address, type);
return {
...this.state,
address,
name,
tags
};
}
protected renderAddressAndName (): React.ReactNode {
const { withAddressOrName = false } = this.props;
if (withAddressOrName) {
return this.renderName(true);
} else {
return (
<>
{this.renderName()}
{this.renderAddress()}
</>
);
}
}
private renderAddress (): React.ReactNode {
const { accountsInfo = EMPTY_INFO, withIndexOrAddress = true } = this.props;
const { address } = this.state;
const { accountIndex } = accountsInfo;
if (accountIndex && withIndexOrAddress) {
return null;
}
return (
<div className='ui--Row-accountId'>
{toShortAddress(address)}
</div>
);
}
private renderAccountIndex (): React.ReactNode {
const { accountsInfo = EMPTY_INFO, withIndex = true, withIndexOrAddress = true, withSmallIcon } = this.props;
const { accountIndex } = accountsInfo;
if (withSmallIcon || !accountIndex || !(withIndex || withIndexOrAddress)) {
return null;
}
return (
<div className='ui--Row-accountIndex'>
{accountIndex.toString()}
</div>
);
}
private renderBalances (): React.ReactNode {
const { accountsInfo = EMPTY_INFO, extraInfo, stakingInfo, withBalance, withValidatorPrefs } = this.props;
const { accountId } = accountsInfo;
if (!(withBalance || withValidatorPrefs) || !accountId) {
return null;
}
return (
<div className='ui--Row-balances'>
<AddressInfo
address={accountId}
extraInfo={extraInfo}
stakingInfo={stakingInfo}
withBalance={withBalance}
withValidatorPrefs={withValidatorPrefs}
return (
<Row
address={toShortAddress(value && isValid ? value : DEFAULT_ADDR)}
buttons={buttons}
className={className}
defaultName={defaultName}
icon={
<Icon
size={ICON_SIZE}
value={value ? value.toString() : null}
/>
</div>
);
}
private renderIcon (): React.ReactNode {
const { accountsInfo = EMPTY_INFO, iconInfo, systemName, withIcon = true, withSmallIcon = false } = this.props;
const { address } = this.state;
const { accountId } = accountsInfo;
if (!withIcon) {
return null;
}
// Since we do queries to storage in the wrapped example, we don't want
// to follow that route if we don't have a valid address.
const Component = accountId
? IdentityIcon
: BaseIdentityIcon;
const theme = getIdentityTheme(systemName);
return (
<div className='ui--Row-icon'>
<Component
size={withSmallIcon ? ICON_SIZE_SMALL : ICON_SIZE}
theme={theme}
value={address}
/>
{iconInfo && (
<div className='ui--Row-icon-info'>
{iconInfo}
</div>
)}
</div>
);
}
protected saveName = (): void => {
const { address, name } = this.state;
const trimmedName = name.trim();
const meta = {
name: trimmedName,
whenEdited: Date.now()
};
// Save only if the name was changed or if it's no empty.
if (trimmedName && address) {
try {
const currentKeyring = keyring.getPair(address);
currentKeyring && keyring.saveAccountMeta(currentKeyring, meta);
} catch (error) {
keyring.saveAddress(address, meta);
}
}
this.setState({ isEditingName: false });
}
protected saveTags = (): void => {
const { address, tags } = this.state;
const meta = {
tags,
whenEdited: Date.now()
};
if (address) {
try {
const currentKeyring = keyring.getPair(address);
currentKeyring && keyring.saveAccountMeta(currentKeyring, meta);
} catch (error) {
keyring.saveAddress(address, meta);
}
this.setState({ isEditingTags: false });
}
}
isDisabled={isDisabled}
isEditableName
isEditableTags
isInline={isInline}
name={name}
onChangeName={setName}
onChangeTags={setTags}
onSaveName={onSaveName}
onSaveTags={onSaveTags}
tags={withTags && tags}
>
{children}
{overlay}
</Row>
);
}
export {
@ -278,21 +67,46 @@ export {
AddressRow
};
export default withMulti(
styled(AddressRow as React.ComponentClass<Props & ApiProps, State>)`
${styles}
export default React.memo(
styled(AddressRow)`
button.ui.icon.editButton {
padding: 0em .3em .3em .3em;
color: #2e86ab;
background: none;
/*trick to let the button in the flow but keep the content centered regardless*/
margin-left: -2em;
position: relative;
right: -2.3em;
z-index: 1;
}
.ui--Row-placeholder {
.editSpan {
white-space: nowrap;
&:before {
content: '';
}
}
.ui--AddressRow-balances {
display: flex;
.column {
display: block;
label,
.result {
display: inline-block;
vertical-align: middle;
}
}
> span {
text-align: left;
}
}
.ui--AddressRow-placeholder {
opacity: 0.5;
}
.ui--Row-accountId,
.ui--Row-accountIndex {
font-family: monospace;
}
`,
translate,
withCalls<Props>(
['derive.accounts.info', { paramName: 'value', propName: 'accountsInfo' }]
)
`
);

View File

@ -8,6 +8,7 @@ import { BareProps } from './types';
import BN from 'bn.js';
import React from 'react';
import { Balance, FormatBalance } from '@polkadot/react-query';
import { BN_ZERO } from '@polkadot/util';
import { classes } from './util';
@ -29,7 +30,7 @@ export function renderProvided ({ className = '', label, value }: RenderProps):
if (Array.isArray(value)) {
const totals = value.filter((_, index): boolean => index !== 0);
const total = totals.reduce((total, value): BN => total.add(value), new BN(0)).gtn(0);
const total = totals.reduce((total, value): BN => total.add(value), BN_ZERO).gtn(0);
if (total) {
others = totals.map((balance, index): React.ReactNode =>

View File

@ -8,7 +8,6 @@ import { BareProps } from '../types';
export type Button$Callback = () => void | Promise<void>;
export interface ButtonProps extends BareProps {
children?: React.ReactNode;
floated?: 'left' | 'right';
icon?: string;
isAnimated?: SUIButtonProps['animated'];

View File

@ -2,6 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { IconProps } from 'semantic-ui-react/dist/commonjs/elements/Icon/Icon';
import { BareProps } from './types';
import React, { useCallback, useContext } from 'react';
@ -17,10 +18,11 @@ interface Props extends BareProps {
className?: string;
icon?: string;
isAddress?: boolean;
value?: string;
size?: IconProps['size'];
value: string;
}
function CopyButton ({ children, className = '', icon = 'copy', isAddress = false, value = '' }: Props): React.ReactElement<Props> {
function CopyButton ({ children, className, icon = 'copy', isAddress = false, size = 'small', value }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { queueAction } = useContext(StatusContext);
@ -46,10 +48,10 @@ function CopyButton ({ children, className = '', icon = 'copy', isAddress = fals
{children}
<span className='copySpan'>
<Button
className='icon-button'
className='icon-button show-on-hover'
icon={icon}
isPrimary
size='mini'
size={size}
/>
</span>
</div>
@ -61,7 +63,7 @@ function CopyButton ({ children, className = '', icon = 'copy', isAddress = fals
export default React.memo(styled(CopyButton)`
cursor: copy;
button.ui.mini.icon.primary.button.icon-button {
button.ui.icon.primary.button.icon-button {
cursor: copy;
}

View File

@ -9,7 +9,7 @@ import React, { useState } from 'react';
import styled from 'styled-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { BlockToTime, FormatBalance } from '@polkadot/react-query';
import { bnMax, formatBalance, formatNumber } from '@polkadot/util';
import { BN_ZERO, bnMax, formatBalance, formatNumber } from '@polkadot/util';
import { useTranslation } from './translate';
import Icon from './Icon';
@ -20,8 +20,6 @@ interface Props {
value?: DeriveDemocracyLock[];
}
const ZERO = new BN(0);
let id = 0;
function DemocracyLocks ({ className = '', value }: Props): React.ReactElement<Props> | null {
@ -36,7 +34,7 @@ function DemocracyLocks ({ className = '', value }: Props): React.ReactElement<P
const max = bnMax(...value.map(({ balance }) => balance));
const mapped = value
.map((info): [DeriveDemocracyLock, BN] => [info, info.unlockAt.gt(bestNumber) ? info.unlockAt.sub(bestNumber) : ZERO])
.map((info): [DeriveDemocracyLock, BN] => [info, info.unlockAt.gt(bestNumber) ? info.unlockAt.sub(bestNumber) : BN_ZERO])
.sort((a, b) => a[1].cmp(b[1]));
return (
@ -55,7 +53,7 @@ function DemocracyLocks ({ className = '', value }: Props): React.ReactElement<P
>
<div>#{referendumId.toString()} {formatBalance(balance, { forceUnit: '-' })} {vote.conviction.toString()}</div>
<div className='faded'>
{blocks.gt(ZERO)
{blocks.gt(BN_ZERO)
? (
<BlockToTime
blocks={blocks}

View File

@ -0,0 +1,49 @@
// 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 { IconProps } from 'semantic-ui-react/dist/commonjs/elements/Icon/Icon';
import { BareProps, VoidFn } from './types';
import React from 'react';
import Button from './Button';
import styled from 'styled-components';
interface Props extends BareProps {
children?: React.ReactNode;
icon?: string;
onClick: VoidFn;
size?: IconProps['size'];
}
function EditButton ({ children, className, icon = 'edit', onClick, size = 'small' }: Props): React.ReactElement<Props> {
return (
<div
className={className}
onClick={onClick}
>
{children}
<span className='editSpan'>
<Button
className='icon-button show-on-hover'
icon={icon}
isPrimary
size={size}
/>
</span>
</div>
);
}
export default React.memo(styled(EditButton)`
cursor: pointer;
button.ui.icon.primary.button.icon-button {
cursor: pointer;
}
.editSpan {
white-space: nowrap;
}
`);

View File

@ -26,6 +26,7 @@ interface Props extends BareProps {
isError?: boolean;
isFull?: boolean;
isHidden?: boolean;
isInPlaceEditor?: boolean;
isReadOnly?: boolean;
label?: React.ReactNode;
labelExtra?: React.ReactNode;
@ -90,7 +91,7 @@ const isSelectAll = (key: string, isPreKeyDown: boolean): boolean =>
let counter = 0;
function Input ({ autoFocus = false, children, className = '', defaultValue, help, icon, inputClassName, isAction = false, isDisabled = false, isDisabledError = false, isEditable = false, isError = false, isFull = false, isHidden = false, isReadOnly = false, label, labelExtra, max, maxLength, min, name, onBlur, onChange, onEnter, onEscape, onKeyDown, onKeyUp, onPaste, placeholder, tabIndex, type = 'text', value, withEllipsis, withLabel }: Props): React.ReactElement<Props> {
function Input ({ autoFocus = false, children, className, defaultValue, help, icon, inputClassName, isAction = false, isDisabled = false, isDisabledError = false, isEditable = false, isError = false, isFull = false, isHidden = false, isInPlaceEditor = false, isReadOnly = false, label, labelExtra, max, maxLength, min, name, onBlur, onChange, onEnter, onEscape, onKeyDown, onKeyUp, onPaste, placeholder, tabIndex, type = 'text', value, withEllipsis, withLabel }: Props): React.ReactElement<Props> {
const [stateName] = useState(`in_${counter++}_at_${Date.now()}`);
const _onBlur = useCallback(
@ -151,6 +152,9 @@ function Input ({ autoFocus = false, children, className = '', defaultValue, hel
isEditable
? 'ui--Input edit icon'
: 'ui--Input',
isInPlaceEditor
? 'inPlaceEditor'
: '',
inputClassName || ''
].join(' ')
}

View File

@ -8,7 +8,7 @@ import BN from 'bn.js';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { BitLengthOption } from '@polkadot/react-components/constants';
import { formatBalance, isBn } from '@polkadot/util';
import { BN_TEN, BN_THOUSAND, formatBalance, isBn } from '@polkadot/util';
import InputNumber from './InputNumber';
interface Props extends BareProps {
@ -33,12 +33,10 @@ interface Props extends BareProps {
}
const DEFAULT_BITLENGTH = BitLengthOption.CHAIN_SPEC as BitLength;
const TEN = new BN(10);
const THOUSAND = new BN(1000);
function reformat (value: string | BN, isDisabled?: boolean): string {
if (isBn(value)) {
let fmt = (value.mul(THOUSAND).div(TEN.pow(new BN(formatBalance.getDefaults().decimals))).toNumber() / 1000).toFixed(3);
let fmt = (value.mul(BN_THOUSAND).div(BN_TEN.pow(new BN(formatBalance.getDefaults().decimals))).toNumber() / 1000).toFixed(3);
while (fmt.length !== 1 && ['.', '0'].includes(fmt[fmt.length - 1])) {
const isLast = fmt.endsWith('.');

View File

@ -7,7 +7,7 @@ import { BareProps, BitLength } from './types';
import BN from 'bn.js';
import React, { useCallback, useEffect, useState } from 'react';
import { formatBalance, isBn } from '@polkadot/util';
import { BN_ZERO, BN_TEN, formatBalance, isBn } from '@polkadot/util';
import { classes } from './util';
import { BitLengthOption } from './constants';
@ -34,15 +34,13 @@ interface Props extends BareProps {
onEnter?: () => void;
onEscape?: () => void;
placeholder?: string;
value?: BN;
value?: BN | null;
withEllipsis?: boolean;
withLabel?: boolean;
withMax?: boolean;
}
const DEFAULT_BITLENGTH = BitLengthOption.NORMAL_NUMBERS as BitLength;
const ZERO = new BN(0);
const TEN = new BN(10);
export class TokenUnit {
public static abbr = 'Unit';
@ -75,7 +73,7 @@ function getSiOptions (): { text: string; value: string }[] {
function getSiPowers (si: SiDef | null): [BN, number, number] {
if (!si) {
return [ZERO, 0, 0];
return [BN_ZERO, 0, 0];
}
const basePower = formatBalance.getDefaults().decimals;
@ -86,11 +84,11 @@ function getSiPowers (si: SiDef | null): [BN, number, number] {
function isValidNumber (bn: BN, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): boolean {
if (
// cannot be negative
bn.lt(ZERO) ||
bn.lt(BN_ZERO) ||
// cannot be > than allowed max
!bn.lt(getGlobalMaxValue(bitLength)) ||
// check if 0 and it should be a value
(!isZeroable && bn.eq(ZERO)) ||
(!isZeroable && bn.isZero()) ||
// check that the bitlengths fit
bn.bitLength() > (bitLength || DEFAULT_BITLENGTH) ||
// cannot be > max (if specified)
@ -120,11 +118,11 @@ function inputToBn (input: string, si: SiDef | null, bitLength: BitLength, isZer
const mod = new BN(modString);
result = div
.mul(TEN.pow(siPower))
.add(mod.mul(TEN.pow(new BN(basePower + siUnitPower - modString.length))));
.mul(BN_TEN.pow(siPower))
.add(mod.mul(BN_TEN.pow(new BN(basePower + siUnitPower - modString.length))));
} else {
result = new BN(input.replace(/[^\d]/g, ''))
.mul(TEN.pow(siPower));
.mul(BN_TEN.pow(siPower));
}
return [
@ -145,7 +143,7 @@ function getValuesFromString (value: string, si: SiDef | null, bitLength: BitLen
function getValuesFromBn (valueBn: BN, si: SiDef | null): [string, BN, boolean] {
const value = si
? valueBn.div(TEN.pow(new BN(formatBalance.getDefaults().decimals + si.power))).toString()
? valueBn.div(BN_TEN.pow(new BN(formatBalance.getDefaults().decimals + si.power))).toString()
: valueBn.toString();
return [
@ -155,13 +153,13 @@ function getValuesFromBn (valueBn: BN, si: SiDef | null): [string, BN, boolean]
];
}
function getValues (value: BN | string = ZERO, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [string, BN, boolean] {
function getValues (value: BN | string = BN_ZERO, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [string, BN, boolean] {
return isBn(value)
? getValuesFromBn(value, si)
: getValuesFromString(value, si, bitLength, isZeroable, maxValue);
}
function InputNumber ({ autoFocus, bitLength = DEFAULT_BITLENGTH, className = '', defaultValue, help, isDecimal, isFull, isSi, isDisabled, isError = false, isZeroable = true, label, labelExtra, maxLength, maxValue, onChange, onEnter, onEscape, placeholder, value: propsValue }: Props): React.ReactElement<Props> {
function InputNumber ({ autoFocus, bitLength = DEFAULT_BITLENGTH, children, className = '', defaultValue, help, isDecimal, isFull, isSi, isDisabled, isError = false, isZeroable = true, label, labelExtra, maxLength, maxValue, onChange, onEnter, onEscape, placeholder, value: propsValue }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [si, setSi] = useState<SiDef | null>(isSi ? formatBalance.findSi('-') : null);
const [isPreKeyDown, setIsPreKeyDown] = useState(false);
@ -272,6 +270,7 @@ function InputNumber ({ autoFocus, bitLength = DEFAULT_BITLENGTH, className = ''
options={getSiOptions()}
/>
)}
{children}
</Input>
);
}

View File

@ -2,17 +2,16 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { DeriveAccountInfo } from '@polkadot/api-derive/types';
import { KeyringItemType } from '@polkadot/ui-keyring/types';
import { BareProps } from './types';
import React from 'react';
import styled from 'styled-components';
import { useToggle } from '@polkadot/react-hooks';
import Button from './Button';
import { classes, toShortAddress } from './util';
import CopyButton from './CopyButton';
import { classes } from './util';
import EditButton from './EditButton';
import Input from './Input';
import InputTags from './InputTags';
import Tag from './Tag';
import Tags from './Tags';
export const styles = `
text-align: left;
@ -41,52 +40,9 @@ export const styles = `
}
}
button.ui.icon.editButton {
padding: 0em .3em .3em .3em;
color: #2e86ab;
background: none;
/*trick to let the button in the flow but keep the content centered regardless*/
margin-left: -2em;
position: relative;
right: -2.3em;
z-index: 1;
}
.editSpan {
white-space: nowrap;
&:before {
content: '';
}
}
.ui--Row-accountId,
.ui--Row-accountIndex {
font-family: monospace;
font-size: 1.25em;
padding: 0;
margin-bottom: 0.25rem;
}
.ui--Row-balances {
display: flex;
.column {
display: block;
label,
.result {
display: inline-block;
vertical-align: middle;
}
}
> span {
text-align: left;
}
}
.ui--Row-base {
display: flex;
min-width: 16rem;
}
.ui--Row-buttons {
@ -124,6 +80,28 @@ export const styles = `
}
}
.ui--Row-address,
.ui--Row-accountIndex {
font-family: monospace;
font-size: 1.25em;
padding: 0;
margin-bottom: 0.25rem;
}
.ui--Row-name {
display: flex;
box-sizing: border-box;
height: 1.5rem;
margin: 0;
padding: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-transform: uppercase;
overflow: hidden;
text-overflow: inherit;
}
.ui--Row-icon {
flex: 0;
margin-right: 1em;
@ -136,30 +114,12 @@ export const styles = `
}
}
.ui--Row-address-or-name {
display: flex;
box-sizing: border-box;
margin: 0;
padding: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: normal;
.withName {
white-space: nowrap;
text-transform: uppercase;
overflow: hidden;
text-overflow: inherit;
}
}
.ui--Row-name-input {
input {
height: 1em;
text-transform: uppercase;
margin-top: -0.3em;
}
}
.ui--Row-tags {
@ -189,195 +149,113 @@ export const styles = `
}
`;
export interface RowProps {
accountsInfo?: DeriveAccountInfo;
export interface RowProps extends BareProps {
address?: string;
buttons?: React.ReactNode;
children?: React.ReactNode;
className?: string;
defaultName?: string;
extraInfo?: React.ReactNode;
details?: React.ReactNode;
icon?: React.ReactNode;
iconInfo?: React.ReactNode;
isEditable?: boolean;
isDisabled?: boolean;
isInline?: boolean;
type?: KeyringItemType;
withIcon?: boolean;
withTags?: boolean;
isEditableName?: boolean;
isEditableTags?: boolean;
name?: string;
onChangeName?: (_: string) => void;
onChangeTags?: (_: string[]) => void;
onSaveName?: () => void;
onSaveTags?: () => void;
tags?: string[];
}
export interface RowState {
address: string;
isEditingName: boolean;
isEditingTags: boolean;
name: string;
tags: string[];
}
function Row ({ address, buttons, children, className, defaultName, details, icon, iconInfo, isDisabled, isEditableName, isEditableTags, isInline, name, onChangeName, onChangeTags, onSaveName, onSaveTags, tags }: RowProps): React.ReactElement<RowProps> {
const [isEditingName, toggleIsEditingName] = useToggle();
const [isEditingTags, toggleIsEditingTags] = useToggle();
// const DEFAULT_ADDR = '5'.padEnd(16, 'x');
// const ICON_SIZE = 48;
export default class Row<P extends RowProps, S extends RowState> extends React.PureComponent<P, S> {
public state: S = {
isEditingName: false,
isEditingTags: false
} as unknown as S;
public static defaultProps = {
defaultName: '<unknown>'
const _onSaveName = (): void => {
onSaveName && onSaveName();
toggleIsEditingName();
};
protected onChangeName = (name: string): void => {
this.setState({ name });
}
protected onChangeTags = (tags: string[]): void => {
this.setState({ tags });
}
protected renderButtons (): React.ReactNode {
const { buttons } = this.props;
return buttons
? <div className='ui--Row-buttons'>{buttons}</div>
: null;
}
protected renderChildren (): React.ReactNode {
const { children } = this.props;
const hasChildren = !children
? false
: Array.isArray(children)
? children.filter((child): boolean => !!child).length !== 0
: true;
if (!hasChildren) {
return null;
}
return (
<div className='ui--Row-children'>
{children}
</div>
);
}
protected renderEditIcon (): React.ReactNode {
return (
<span className='editSpan'>
<Button
className='icon-button'
icon='edit'
isPrimary
key='unlock'
size='mini'
/>
</span>
);
}
protected renderName (withCopy = false): React.ReactNode {
const { defaultName, isEditable } = this.props;
const { address, isEditingName, name } = this.state;
const withName = name !== defaultName;
// can't be both editable and copyable
return isEditingName
? (
<Input
autoFocus
className='ui--Row-name-input'
defaultValue={name}
onBlur={this.saveName}
onChange={this.onChangeName}
onEnter={this.saveName}
withLabel={false}
/>
)
: (
<div
className={classes('ui--Row-address-or-name', isEditable && 'editable')}
onClick={isEditable ? this.toggleNameEditor : undefined}
>
{withCopy && !isEditable
? (
<CopyButton
isAddress
value={address}
>
<span className={`${withName ? 'withName' : 'withAddr'}`}>{
withName ? name : toShortAddress(address)
}
</span>
</CopyButton>
)
: (
<>
<span className='withName'>
{name}
</span>
{isEditable && this.renderEditIcon()}
</>
)
}
</div>
);
}
protected renderTags (): React.ReactNode {
const { isEditingTags, tags } = this.state;
const { isEditable, withTags = false } = this.props;
if (!withTags) {
return null;
}
return isEditingTags
? (
<InputTags
className='ui--Row-tags-input'
defaultValue={tags}
onBlur={this.saveTags}
onChange={this.onChangeTags}
onClose={this.saveTags}
openOnFocus
searchInput={{ autoFocus: true }}
value={tags}
withLabel={false}
/>
)
: (
<div
className={classes('ui--Row-tags', isEditable && 'editable')}
onClick={isEditable ? this.toggleTagsEditor : undefined}
>
{
!tags.length
? (isEditable ? <span className='addTags'>add tags</span> : undefined)
: tags.map((tag): React.ReactNode => (
<Tag
key={tag}
label={tag}
return (
<div
className={classes('ui--Row', isDisabled && 'isDisabled', isInline && 'isInline', className)}
>
<div className='ui--Row-base'>
{icon && (
<div className='ui--Row-icon'>
{icon}
{iconInfo && (
<div className='ui--Row-icon-info'>
{iconInfo}
</div>
)}
</div>
)}
<div className='ui--Row-details'>
{(name || defaultName) && (
isEditableName && isEditingName
? (
<Input
autoFocus
defaultValue={name || defaultName}
isInPlaceEditor
onBlur={_onSaveName}
onChange={onChangeName}
onEnter
withLabel={false}
/>
))
}
{isEditable && this.renderEditIcon()}
)
: (
<div className='ui--Row-name'>
{
isEditableName
? (
<EditButton onClick={toggleIsEditingName}>
{name || defaultName}
</EditButton>
)
: name
}
</div>
)
)}
{address && (
<div className='ui--Row-address'>
{address}
</div>
)}
{details}
{tags && (
<Tags
className='ui--Row-tags'
isEditable={isEditableTags}
isEditing={isEditingTags}
onChange={onChangeTags}
onSave={onSaveTags}
onToggleIsEditing={toggleIsEditingTags}
size='tiny'
value={tags}
/>
)}
</div>
);
}
protected saveName!: () => void;
protected saveTags!: () => void;
protected toggleNameEditor = (): void => {
this.setState(({ isEditingName }): S => ({
isEditingName: !isEditingName
}) as unknown as S);
}
protected toggleTagsEditor = (): void => {
this.setState(({ isEditingTags }): S => ({
isEditingTags: !isEditingTags
}) as unknown as S);
}
{buttons && (
<div className='ui--Row-buttons'>
{buttons}
</div>
)}
</div>
{children && (
<div className='ui--Row-children'>
{children}
</div>
)}
</div>
);
}
export default React.memo(
styled(Row)`${
styles
}`
);

View File

@ -9,7 +9,7 @@ import React from 'react';
import styled from 'styled-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { BlockToTime, FormatBalance } from '@polkadot/react-query';
import { formatBalance, formatNumber } from '@polkadot/util';
import { BN_ZERO, formatBalance, formatNumber } from '@polkadot/util';
import Icon from './Icon';
import Tooltip from './Tooltip';
@ -43,7 +43,7 @@ function StakingUnbonding ({ className = '', value }: Props): React.ReactElement
}
const mapped = filtered.map((unlock): [DeriveUnlocking, BN] => [unlock, remainingBlocks(unlock.remainingEras, progress)]);
const total = mapped.reduce((total, [{ value }]) => total.add(value), new BN(0));
const total = mapped.reduce((total, [{ value }]) => total.add(value), BN_ZERO);
const trigger = `${value.accountId.toHex()}-unlocking-trigger`;
return (

View File

@ -0,0 +1,95 @@
// 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 { VoidFn } from './types';
import React, { useCallback, useMemo } from 'react';
import styled from 'styled-components';
import { classes } from './util';
import EditButton from './EditButton';
import InputTags from './InputTags';
import Tag from './Tag';
import { useTranslation } from './translate';
interface Props {
children?: React.ReactNode;
className?: string;
color?: 'green' | 'grey' | 'red';
isEditable?: boolean;
isEditing?: boolean;
onChange?: (_: string[]) => void;
onToggleIsEditing?: () => void;
onSave?: VoidFn;
size?: 'small' | 'tiny';
value: string[];
}
function Tags ({ children, className, color = 'grey', isEditable, isEditing, onChange, onSave, onToggleIsEditing, size = 'small', value }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const contents = useMemo(
(): React.ReactNode => value.length
? value.map((tag): React.ReactNode => (
<Tag
color={color}
key={tag}
label={tag}
size={size}
/>
))
: <label>{t<string>('no tags')}</label>,
[color, size, t, value]
);
const _onSave = useCallback(
(): void => {
onSave && onSave();
onToggleIsEditing && onToggleIsEditing();
},
[onSave, onToggleIsEditing]
);
return (
<div className={classes('ui--Tags', className)}>
{isEditable && isEditing
? (
<InputTags
defaultValue={value}
onBlur={_onSave}
onChange={onChange}
onClose={_onSave}
openOnFocus
searchInput={{ autoFocus: true }}
value={value}
withLabel={false}
/>
)
: (
<div className='tags--toggle'>
{isEditable
? (
<EditButton onClick={onToggleIsEditing}>
{contents}
</EditButton>
)
: contents}
</div>
)
}
{children}
</div>
);
}
export default React.memo(styled(Tags)`
.tags--toggle {
display: inline-block;
label {
display: inline-block !important;
}
}
`);

View File

@ -31,6 +31,7 @@ export { default as Column } from './Column';
export { default as CopyButton } from './CopyButton';
export { default as CryptoType } from './CryptoType';
export { default as Dropdown } from './Dropdown';
export { default as EditButton } from './EditButton';
export { default as Editor } from './Editor';
export { default as ErrorBoundary } from './ErrorBoundary';
export { default as Event } from './Event';
@ -82,6 +83,7 @@ export { default as SummaryBox } from './SummaryBox';
export { default as Table } from './Table';
export { default as Tabs } from './Tabs';
export { default as Tag } from './Tag';
export { default as Tags } from './Tags';
export { default as Toggle } from './Toggle';
export { default as Tooltip } from './Tooltip';
export { default as TxButton } from './TxButton';

View File

@ -83,6 +83,18 @@ export default css`
}
}
&.inPlaceEditor {
margin: 0 !important;
input {
padding: 0 !important;
background: rgba(230, 230, 230, 0.8) !important;
border: 0 !important;
border-radius: 0 !important;
box-shadow: 0 3px 3px rgba(0,0,0,.2);
}
}
.ui--SiDropdown {
width: 6rem;
text-align: center;

View File

@ -137,7 +137,7 @@ export default createGlobalStyle<Props>`
}
}
.ui.button.mini {
.ui.button.show-on-hover {
visibility: hidden;
}
}

View File

@ -16,7 +16,9 @@ import { TxCallback, TxFailedCallback } from './Status/types';
export type VoidFn = () => void;
export interface BareProps {
children?: React.ReactNode;
className?: string;
style?: React.CSSProperties;
}
export interface AppProps {

View File

@ -8,5 +8,6 @@ export { default as getAddressName } from './getAddressName';
export { default as getAddressTags } from './getAddressTags';
export { default as getContractAbi } from './getContractAbi';
export { default as isTreasuryProposalVote } from './isTreasuryProposalVote';
export { default as timeToString } from './timeToString';
export { default as toAddress } from './toAddress';
export { default as toShortAddress } from './toShortAddress';

View File

@ -0,0 +1,20 @@
// 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 @typescript-eslint/no-unsafe-assignment */
import { TFunction } from 'i18next';
import { Time } from '@polkadot/util/types';
export default function timeToString (t: TFunction, { days, hours, minutes, seconds }: Time): string {
return [
days ? (days > 1) ? t<string>('{{days}} days', { replace: { days } }) : t<string>('1 day') : null,
hours ? (hours > 1) ? t<string>('{{hours}} hrs', { replace: { hours } }) : t<string>('1 hr') : null,
minutes ? (minutes > 1) ? t<string>('{{minutes}} mins', { replace: { minutes } }) : t<string>('1 min') : null,
seconds ? (seconds > 1) ? t<string>('{{seconds}} s', { replace: { seconds } }) : t<string>('1 s') : null
]
.filter((value): value is string => !!value)
.slice(0, 2)
.join(' ');
}

View File

@ -7,8 +7,10 @@ export { default as useAccountInfo } from './useAccountInfo';
export { default as useAccounts } from './useAccounts';
export { default as useAddresses } from './useAddresses';
export { default as useApi } from './useApi';
export { default as useBlockTime } from './useBlockTime';
export { default as useCacheKey } from './useCacheKey';
export { default as useCall } from './useCall';
export { default as useContracts } from './useContracts';
export { default as useFormField } from './useFormField';
export { default as useDebounce } from './useDebounce';
export { default as useFavorites } from './useFavorites';
@ -17,6 +19,8 @@ export { default as useIpfs } from './useIpfs';
export { default as useIsMountedRef } from './useIsMountedRef';
export { default as useMembers } from './useMembers';
export { default as useModal } from './useModal';
export { default as useNonEmptyString } from './useNonEmptyString';
export { default as useNonZeroBn } from './useNonZeroBn';
export { default as useOwnEraRewards } from './useOwnEraRewards';
export { default as useOwnStashes, useOwnStashIds } from './useOwnStashes';
export { default as useOwnStashInfos } from './useOwnStashInfos';

View File

@ -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.
import { useTranslation as useTranslationBase, UseTranslationResponse, withTranslation } from 'react-i18next';
export function useTranslation (): UseTranslationResponse {
return useTranslationBase('react-hooks');
}
export default withTranslation(['react-hooks']);

View File

@ -99,6 +99,7 @@ export interface AddressIdentity extends DeriveAccountRegistration {
}
export interface UseAccountInfo {
accountIndex?: string;
flags: AddressFlags;
name: string;
setName: React.Dispatch<string>;
@ -110,6 +111,7 @@ export interface UseAccountInfo {
meta?: KeyringJson$Meta;
toggleIsEditingName: VoidFn;
isEditingTags: boolean;
isNull: boolean;
toggleIsEditingTags: VoidFn;
onSaveName: VoidFn;
onSaveTags: VoidFn;

View File

@ -32,12 +32,13 @@ const IS_NONE = {
isTechCommittee: false
};
export default function useAccountInfo (value: string): UseAccountInfo {
export default function useAccountInfo (value: string | null, isContract = false): UseAccountInfo {
const { api } = useApi();
const { isAccount } = useAccounts();
const { isAddress } = useAddresses();
const accountInfo = useCall<DeriveAccountInfo>(api.derive.accounts.info as any, [value]);
const accountFlags = useCall<DeriveAccountFlags>(api.derive.accounts.flags as any, [value]);
const [accountIndex, setAccountIndex] = useState<string | undefined>(undefined);
const [tags, setSortedTags] = useState<string[]>([]);
const [name, setName] = useState('');
const [genesisHash, setGenesisHash] = useState<StringOrNull>(null);
@ -55,9 +56,13 @@ export default function useAccountInfo (value: string): UseAccountInfo {
}, [accountFlags]);
useEffect((): void => {
const { identity, nickname } = accountInfo || {};
const accountOrAddress = keyring.getAccount(value) || keyring.getAddress(value);
let name = accountOrAddress?.meta.name;
const { accountIndex: anAccountIndex, identity, nickname } = accountInfo || {};
if (anAccountIndex && accountIndex !== anAccountIndex.toString()) {
setAccountIndex(anAccountIndex.toString());
}
let name;
if (api.query.identity && api.query.identity.identityOf) {
if (identity?.display) {
@ -91,28 +96,29 @@ export default function useAccountInfo (value: string): UseAccountInfo {
} else {
setIdentity(undefined);
}
}, [accountInfo, api, value]);
}, [accountIndex, accountInfo, api]);
useEffect((): void => {
const accountOrAddress = keyring.getAccount(value) || keyring.getAddress(value);
const isOwned = isAccount(value);
const isInContacts = isAddress(value);
if (value) {
const accountOrAddress = keyring.getAccount(value) || keyring.getAddress(value);
const isOwned = isAccount(value);
const isInContacts = isAddress(value);
setGenesisHash(accountOrAddress?.meta.genesisHash || null);
setFlags((flags) => ({
...flags,
isDevelopment: (accountOrAddress?.meta.isTesting as boolean) || false,
isEditable: (!identity?.display && (isInContacts || (accountOrAddress?.meta.isMultisig as boolean) || (accountOrAddress && !(accountOrAddress.meta.isInjected || accountOrAddress.meta.isHardware)))) || false,
isExternal: (accountOrAddress?.meta.isExternal as boolean) || false,
isHardware: (accountOrAddress?.meta.isHardware as boolean) || false,
isInContacts,
isInjected: (accountOrAddress?.meta.isInjected as boolean) || false,
isMultisig: (accountOrAddress?.meta.isMultisig as boolean) || false,
isOwned
}));
setMeta(accountOrAddress?.meta);
setSortedTags(accountOrAddress?.meta.tags ? (accountOrAddress.meta.tags as string[]).sort() : []);
}, [identity?.display, isAccount, isAddress, value]);
setGenesisHash(accountOrAddress?.meta.genesisHash || null);
setFlags((flags): AddressFlags => ({
...flags,
isDevelopment: accountOrAddress?.meta.isTesting || false,
isEditable: !!(!identity?.display && (isInContacts || accountOrAddress?.meta.isMultisig || (accountOrAddress && !(accountOrAddress.meta.isInjected || accountOrAddress.meta.isHardware)))) || false,
isExternal: !!accountOrAddress?.meta.isExternal || false,
isInContacts,
isMultisig: !!accountOrAddress?.meta.isMultisig || false,
isOwned
}));
setMeta(accountOrAddress?.meta);
setName(accountOrAddress?.meta.name || '');
setSortedTags(accountOrAddress?.meta.tags ? (accountOrAddress.meta.tags as string[]).sort() : []);
}
}, [identity, isAccount, isAddress, value]);
const onSaveName = useCallback(
(): void => {
@ -122,7 +128,17 @@ export default function useAccountInfo (value: string): UseAccountInfo {
const meta = { name, whenEdited: Date.now() };
if (value) {
if (isContract) {
try {
if (value) {
const originalMeta = keyring.getAddress(value)?.meta;
keyring.saveContract(value, { ...originalMeta, ...meta });
}
} catch (error) {
console.error(error);
}
} else if (value) {
try {
const pair = keyring.getPair(value);
@ -138,18 +154,24 @@ export default function useAccountInfo (value: string): UseAccountInfo {
}
}
},
[api, isEditingName, name, toggleIsEditingName, value]
[api, isContract, isEditingName, name, toggleIsEditingName, value]
);
const onSaveTags = useCallback(
(): void => {
if (isEditingTags) {
toggleIsEditingTags();
}
const meta = { tags, whenEdited: Date.now() };
if (value) {
if (isContract) {
try {
if (value) {
const originalMeta = keyring.getAddress(value)?.meta;
value && keyring.saveContract(value, { ...originalMeta, ...meta });
}
} catch (error) {
console.error(error);
}
} else if (value) {
try {
const currentKeyring = keyring.getPair(value);
@ -159,7 +181,7 @@ export default function useAccountInfo (value: string): UseAccountInfo {
}
}
},
[isEditingTags, tags, toggleIsEditingTags, value]
[isContract, tags, value]
);
const onForgetAddress = useCallback(
@ -173,7 +195,7 @@ export default function useAccountInfo (value: string): UseAccountInfo {
}
try {
keyring.forgetAddress(value);
value && keyring.forgetAddress(value);
} catch (e) {
console.error(e);
}
@ -183,11 +205,13 @@ export default function useAccountInfo (value: string): UseAccountInfo {
const onSetGenesisHash = useCallback(
(genesisHash: string | null): void => {
const account = keyring.getPair(value);
if (value) {
const account = keyring.getPair(value);
account && keyring.saveAccountMeta(account, { ...account.meta, genesisHash });
account && keyring.saveAccountMeta(account, { ...account.meta, genesisHash });
setGenesisHash(genesisHash);
setGenesisHash(genesisHash);
}
},
[value]
);
@ -198,11 +222,13 @@ export default function useAccountInfo (value: string): UseAccountInfo {
);
return {
accountIndex,
flags,
genesisHash,
identity,
isEditingName,
isEditingTags,
isNull: !value,
meta,
name,
onForgetAddress,

View File

@ -0,0 +1,37 @@
// Copyright 2017-2020 @polkadot/app-democracy 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 @typescript-eslint/no-unsafe-call */
import BN from 'bn.js';
import { useMemo } from 'react';
import { timeToString } from '@polkadot/react-components/util';
import { useApi } from '@polkadot/react-hooks';
import { BN_ONE, extractTime } from '@polkadot/util';
import { useTranslation } from './translate';
type Result = [number, string];
const DEFAULT_TIME = new BN(6000);
export default function useBlockTime (blocks = BN_ONE): Result {
const { t } = useTranslation();
const { api } = useApi();
return useMemo(
(): Result => {
const blockTime = (
api.consts.babe?.expectedBlockTime ||
api.consts.timestamp?.minimumPeriod.muln(2) ||
DEFAULT_TIME
);
return [
blockTime.toNumber(),
timeToString(t, extractTime(blockTime.mul(blocks).toNumber()))
];
},
[api, blocks, t]
);
}

View File

@ -0,0 +1,37 @@
// 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 { useEffect, useState } from 'react';
import contractObservable from '@polkadot/ui-keyring/observable/contracts';
import useIsMountedRef from './useIsMountedRef';
interface UseContracts {
allContracts: string[];
hasContracts: boolean;
isContract: (address: string) => boolean;
}
export default function useContracts (): UseContracts {
const mountedRef = useIsMountedRef();
const [state, setState] = useState<UseContracts>({ allContracts: [], hasContracts: false, isContract: () => false });
useEffect((): () => void => {
const subscription = contractObservable.subject.subscribe((contracts): void => {
if (mountedRef.current) {
const allContracts = contracts ? Object.keys(contracts) : [];
const hasContracts = allContracts.length !== 0;
const isContract = (address: string): boolean => allContracts.includes(address);
setState({ allContracts, hasContracts, isContract });
}
});
return (): void => {
setTimeout(() => subscription.unsubscribe(), 0);
};
}, [mountedRef]);
return state;
}

View File

@ -2,25 +2,22 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { useCallback, useMemo, useState } from 'react';
import { useMemo, useState } from 'react';
import { isUndefined } from '@polkadot/util';
type FormField<T> = [
export type FormField<T> = [
T | null,
boolean,
(_?: T | null) => void
];
function isTruthy<T> (value?: T | null): boolean {
return !!value;
}
export default function useFormField<T> (defaultValue: T | null, validate: (_?: T | null) => boolean = (): boolean => true): FormField<T> {
export default function useFormField<T> (defaultValue: T | null, validate: (_: T) => boolean = (): boolean => true): FormField<T> {
const [value, setValue] = useState<T | null>(defaultValue);
const isValid = useMemo(
(): boolean => isTruthy<T>(value) && validate(value),
(): boolean => !!value && validate(value),
[validate, value]
);
const setter = useCallback((value?: T | null): void => setValue(value || null), []);
const setter = (value?: T | null) => !isUndefined(value) && setValue(value);
return [
value,

View File

@ -0,0 +1,12 @@
// 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 useFormField, { FormField } from './useFormField';
export default function useNonEmptyString (initialValue = ''): FormField<string> {
return useFormField(
initialValue,
(value?: string | null): boolean => (value && value.length > 0) || false
);
}

View File

@ -0,0 +1,14 @@
// 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 BN from 'bn.js';
import useFormField, { FormField } from './useFormField';
import { BN_ZERO } from '@polkadot/util';
export default function useNonZeroBn (initialValue: BN = BN_ZERO): FormField<BN> {
return useFormField(
initialValue,
(value: BN): boolean => !value.isZero()
);
}

View File

@ -5,10 +5,9 @@
import { TypeDef, TypeDefInfo } from '@polkadot/types/types';
import { RawParamValue } from './types';
import BN from 'bn.js';
import { registry } from '@polkadot/react-api';
import { Bytes, Raw, createType, getTypeDef } from '@polkadot/types';
import { isBn } from '@polkadot/util';
import { BN_ZERO, isBn } from '@polkadot/util';
const warnList: string[] = [];
@ -61,7 +60,7 @@ export default function getInitValue (def: TypeDef): unknown | unknown[] {
case 'u64':
case 'u128':
case 'VoteIndex':
return new BN(0);
return BN_ZERO;
case 'bool':
return false;
@ -71,7 +70,7 @@ export default function getInitValue (def: TypeDef): unknown | unknown[] {
return '';
case 'Moment':
return new BN(0);
return BN_ZERO;
case 'Vote':
return -1;
@ -123,7 +122,7 @@ export default function getInitValue (def: TypeDef): unknown | unknown[] {
const raw = getTypeDef(instance.toRawType());
if (isBn(instance)) {
return new BN(0);
return BN_ZERO;
} else if ([TypeDefInfo.Enum, TypeDefInfo.Struct].includes(raw.info)) {
return getInitValue(raw);
}

View File

@ -5,10 +5,8 @@
import { BareProps } from '@polkadot/react-api/types';
import BN from 'bn.js';
import React, { useMemo } from 'react';
import { useApi } from '@polkadot/react-hooks';
import { useTranslation } from './translate';
import React from 'react';
import { useBlockTime } from '@polkadot/react-hooks';
interface Props extends BareProps {
blocks?: BN;
@ -16,62 +14,8 @@ interface Props extends BareProps {
label?: React.ReactNode;
}
type Time = [number, number, number, number];
const HRS = 60 * 60;
const DAY = HRS * 24;
const DEFAULT_TIME = new BN(6000);
function addTime (a: Time, b: Time): Time {
return [a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]];
}
function extractTime (value?: number): Time {
if (!value) {
return [0, 0, 0, 0];
} else if (value < 60) {
return [0, 0, 0, value];
}
const mins = value / 60;
if (mins < 60) {
const round = Math.floor(mins);
return addTime([0, 0, round, 0], extractTime(value - (round * 60)));
}
const hrs = mins / 60;
if (hrs < 24) {
const round = Math.floor(hrs);
return addTime([0, round, 0, 0], extractTime(value - (round * HRS)));
}
const round = Math.floor(hrs / 24);
return addTime([round, 0, 0, 0], extractTime(value - (round * DAY)));
}
function BlockToTime ({ blocks, children, className = '', label }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const time = useMemo((): string => {
const blockTime = (
api.consts.babe?.expectedBlockTime ||
api.consts.timestamp?.minimumPeriod.muln(2) ||
DEFAULT_TIME
).divn(1000);
const time = extractTime(blocks && blocks.mul(blockTime).toNumber());
return [
time[0] ? (time[0] > 1) ? t<string>('{{d}} days', { replace: { d: time[0] } }) : t<string>('1 day') : null,
time[1] ? (time[1] > 1) ? t<string>('{{h}} hrs', { replace: { h: time[1] } }) : t<string>('1 hr') : null,
time[2] ? (time[2] > 1) ? t<string>('{{m}} mins', { replace: { m: time[2] } }) : t<string>('1 min') : null,
time[3] ? (time[3] > 1) ? t<string>('{{s}} s', { replace: { s: time[3] } }) : t<string>('1 s') : null
].filter((value): value is string => !!value).slice(0, 2).join(' ');
}, [api, blocks, t]);
const [, text] = useBlockTime(blocks);
if (blocks?.ltn(0)) {
return null;
@ -79,7 +23,7 @@ function BlockToTime ({ blocks, children, className = '', label }: Props): React
return (
<div className={className}>
{label || ''}{time}{children}
{label || ''}{text}{children}
</div>
);
}

View File

@ -8,6 +8,7 @@ import { ExtraFees as State } from './types';
import BN from 'bn.js';
import React, { useEffect, useState } from 'react';
import { Compact, UInt } from '@polkadot/types';
import { BN_ZERO } from '@polkadot/util';
interface Props {
endowment: BN | Compact<UInt>;
@ -17,8 +18,8 @@ interface Props {
function ContractCall ({ endowment, fees, onChange }: Props): React.ReactElement<Props> | null {
const [, setState] = useState<State>({
extraAmount: new BN(0),
extraFees: new BN(0),
extraAmount: BN_ZERO,
extraFees: BN_ZERO,
extraWarn: false
});

View File

@ -8,6 +8,7 @@ import { ExtraFees as State } from './types';
import BN from 'bn.js';
import React, { useEffect, useState } from 'react';
import { Compact, UInt } from '@polkadot/types';
import { BN_ZERO } from '@polkadot/util';
interface Props {
endowment: BN | Compact<UInt>;
@ -17,8 +18,8 @@ interface Props {
function ContractDeploy ({ endowment, fees, onChange }: Props): React.ReactElement<Props> | null {
const [, setState] = useState<State>({
extraAmount: new BN(0),
extraFees: new BN(0),
extraAmount: BN_ZERO,
extraFees: BN_ZERO,
extraWarn: false
});

View File

@ -11,7 +11,7 @@ import React, { useEffect, useState } from 'react';
import { Compact, UInt } from '@polkadot/types';
import { Icon } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { formatBalance } from '@polkadot/util';
import { BN_ZERO, formatBalance } from '@polkadot/util';
import { useTranslation } from '../translate';
@ -32,8 +32,8 @@ function Transfer ({ amount, fees, onChange, recipientId }: Props): React.ReactE
const { api } = useApi();
const allBalances = useCall<DeriveBalancesAll>(api.derive.balances.all, [recipientId]);
const [{ isCreation, isNoEffect }, setState] = useState<State>({
extraAmount: new BN(0),
extraFees: new BN(0),
extraAmount: BN_ZERO,
extraFees: BN_ZERO,
extraWarn: false,
isCreation: false,
isNoEffect: false

View File

@ -4,9 +4,9 @@
import { DeriveFees, DeriveBalancesAll, DeriveContractFees } from '@polkadot/api-derive/types';
import BN from 'bn.js';
import { registry } from '@polkadot/react-api';
import { createType } from '@polkadot/types';
import { BN_ZERO } from '@polkadot/util';
const ZERO_BALANCE: DeriveBalancesAll = {
accountId: createType(registry, 'AccountId'),
@ -35,16 +35,16 @@ const ZERO_FEES_BALANCES: DeriveFees = {
const ZERO_FEES = ZERO_FEES_BALANCES;
const ZERO_FEES_CONTRACT: DeriveContractFees = {
callBaseFee: new BN(0),
contractFee: new BN(0),
creationFee: new BN(0),
rentByteFee: new BN(0),
rentDepositOffset: new BN(0),
surchargeReward: new BN(0),
tombstoneDeposit: new BN(0),
transactionBaseFee: new BN(0),
transactionByteFee: new BN(0),
transferFee: new BN(0)
callBaseFee: BN_ZERO,
contractFee: BN_ZERO,
creationFee: BN_ZERO,
rentByteFee: BN_ZERO,
rentDepositOffset: BN_ZERO,
surchargeReward: BN_ZERO,
tombstoneDeposit: BN_ZERO,
transactionBaseFee: BN_ZERO,
transactionByteFee: BN_ZERO,
transferFee: BN_ZERO
};
const MAX_SIZE_MB = 10;

View File

@ -21,7 +21,7 @@ import { Button, InputBalance, Modal, Toggle, Output, ErrorBoundary, InputNumber
import { registry } from '@polkadot/react-api';
import { withApi, withMulti, withObservable } from '@polkadot/react-api/hoc';
import keyring from '@polkadot/ui-keyring';
import { assert, isFunction } from '@polkadot/util';
import { BN_ZERO, assert, isFunction } from '@polkadot/util';
import { blake2AsU8a } from '@polkadot/util-crypto';
import { format } from '@polkadot/util/logger';
@ -388,7 +388,7 @@ class Signer extends React.PureComponent<Props, State> {
/>
{showTip && (
<InputBalance
defaultValue={new BN(0)}
defaultValue={BN_ZERO}
help={t<string>('Add a tip to this extrinsic, paying the block author for greater priority')}
isDisabled={!!signedTx}
isZeroable
@ -484,11 +484,11 @@ class Signer extends React.PureComponent<Props, State> {
}
private onChangeNonce = (value?: BN): void => {
this.setState({ nonce: value || new BN(0) });
this.setState({ nonce: value || BN_ZERO });
}
private onChangeBlocks = (value?: BN): void => {
this.setState({ blocks: value || new BN(0) });
this.setState({ blocks: value || BN_ZERO });
}
private onChangeSignatory = (signatory?: string | null): void => {

View File

@ -2926,11 +2926,11 @@ __metadata:
linkType: hard
"@octokit/types@npm:^4.0.1":
version: 4.1.8
resolution: "@octokit/types@npm:4.1.8"
version: 4.1.9
resolution: "@octokit/types@npm:4.1.9"
dependencies:
"@types/node": ">= 8"
checksum: 3/ae05cec4102f0997411d64388f70fa9ee3e354e064a4b64cf737d190ddf008f16473fb5d5b9f1573b5c2cf644185b64dbf5998b60865b43e8ef9046d396ec964
checksum: 3/52cb142f82494ff163ede265e5c8922c615b6f76e0176f119106d7d8f969591df40f2e8078141e9569a022db7385f220c46cfc41e384c125af67ef833d89603d
languageName: node
linkType: hard
@ -3361,27 +3361,27 @@ __metadata:
linkType: hard
"@polkadot/extension-dapp@npm:^0.26.0-beta.26":
version: 0.26.0-beta.26
resolution: "@polkadot/extension-dapp@npm:0.26.0-beta.26"
version: 0.26.0-beta.27
resolution: "@polkadot/extension-dapp@npm:0.26.0-beta.27"
dependencies:
"@babel/runtime": ^7.10.2
"@polkadot/extension-inject": 0.26.0-beta.26
"@polkadot/util": ^2.12.2
"@polkadot/util-crypto": ^2.12.2
"@polkadot/extension-inject": 0.26.0-beta.27
"@polkadot/util": ^2.13.0-beta.3
"@polkadot/util-crypto": ^2.13.0-beta.3
peerDependencies:
"@polkadot/api": "*"
checksum: 3/02646ea6e3caa65a4fae80b771fd6787f256f47dd455ec3e32217dadfdf5517fa7fb8153f92ce57256cd424bdaf75125278ca8ae5e1667a6af46db112041a39b
checksum: 3/9239b2cc58f5ab6153131b649d4a6c7fd2638fa54ead6b68e28b14c31b019a4f71327228e2f49859bc6c4f5036ac3e8736558cfd9da0159534928c891f94a255
languageName: node
linkType: hard
"@polkadot/extension-inject@npm:0.26.0-beta.26":
version: 0.26.0-beta.26
resolution: "@polkadot/extension-inject@npm:0.26.0-beta.26"
"@polkadot/extension-inject@npm:0.26.0-beta.27":
version: 0.26.0-beta.27
resolution: "@polkadot/extension-inject@npm:0.26.0-beta.27"
dependencies:
"@babel/runtime": ^7.10.2
peerDependencies:
"@polkadot/api": "*"
checksum: 3/3736ce7542ee00224d376c4e14e706d990c91fb8bce1d50c613d73147c6d9ce6229cc61e5eddb09e725d93b9e026b95e771df5d2c10fbf59444c1a068535149a
checksum: 3/6c0dce3510059efb673b74616ba0887e1ed6e72e5bfd03b74004229d23074155b55f03af368f3723f652bff3595a856f9cdc2d7505e2fe7276c0632626ba1cef
languageName: node
linkType: hard
@ -4095,9 +4095,9 @@ __metadata:
linkType: hard
"@types/node@npm:*, @types/node@npm:>= 8, @types/node@npm:^12.0.12":
version: 12.12.44
resolution: "@types/node@npm:12.12.44"
checksum: 3/a950f71a368a6e5ff807d6c3a05b1957f6288e0651da3d5be06aebec59facfb143db79206d8e966c5a57ae983b8470951df9400ffe4b94d116117fe6f960cfdc
version: 12.12.45
resolution: "@types/node@npm:12.12.45"
checksum: 3/05e386a75ebfbac78374497010afde72c0fa41db5b3a5f8d52363974c495f08831f660acfa75e842b99bf2d7bedd1fef7ba5ae76e3fbea0b8c7a5c38726d78aa
languageName: node
linkType: hard
@ -6841,9 +6841,9 @@ __metadata:
linkType: hard
"caniuse-lite@npm:^1.0.0, caniuse-lite@npm:^1.0.30001043, caniuse-lite@npm:^1.0.30001061":
version: 1.0.30001078
resolution: "caniuse-lite@npm:1.0.30001078"
checksum: 3/b1b8ba57107b27b1d8b1eba01077cd52221a6ad5d4324a1dccee5a5092e1064920c09ed1c5656b4f93d7a33a4beaac9b9c044fd90e980539b47aeb35c42f4d9a
version: 1.0.30001079
resolution: "caniuse-lite@npm:1.0.30001079"
checksum: 3/af920b295b172060f740dee5e305e847f0d0ceb64645d936cb2b26fb87bb67c4d38fc072f2c87ad95ce958ddfa50fa39634ae61c226d3c34ea66a5bfe433495a
languageName: node
linkType: hard
@ -9509,9 +9509,9 @@ __metadata:
linkType: hard
"electron-to-chromium@npm:^1.3.413":
version: 1.3.463
resolution: "electron-to-chromium@npm:1.3.463"
checksum: 3/27f10984fe4c6eb600c21b128d9609b5b613dc645a47d22ce0e9f5f1a264d95ab3ecc6d27d0655756958ba7583657336fe63a5d09cf602f950e37f87c6e5c18c
version: 1.3.465
resolution: "electron-to-chromium@npm:1.3.465"
checksum: 3/b750cc3abedb0bf85c516e22e21d2674011ecf7861f15d19e009fb42ca748924e47743c3251dc300c2847587efa810be016c62964ff853ed42ea04cfd9c49d84
languageName: node
linkType: hard
@ -10575,9 +10575,9 @@ __metadata:
linkType: hard
"fast-deep-equal@npm:^3.1.1":
version: 3.1.1
resolution: "fast-deep-equal@npm:3.1.1"
checksum: 3/38fe57c5ea7dbb42cf84f5d94166358b930beb49345619205ff16c4a0c896f8679a444f0fbd0f352a633f2ea800673173e2a150d81d3d85933d714d24498c688
version: 3.1.3
resolution: "fast-deep-equal@npm:3.1.3"
checksum: 3/451526766b219503131d11e823eaadd1533080b0be4860e316670b039dcaf31cd1007c2fe036a9b922abba7c040dfad5e942ed79d21f2ff849e50049f36e0fb7
languageName: node
linkType: hard
@ -12624,11 +12624,11 @@ __metadata:
linkType: hard
"iconv-lite@npm:^0.5.1":
version: 0.5.1
resolution: "iconv-lite@npm:0.5.1"
version: 0.5.2
resolution: "iconv-lite@npm:0.5.2"
dependencies:
safer-buffer: ">= 2.1.2 < 3"
checksum: 3/e21730d7f434b74c55863cbb13ace62b070e0f15dd07825bc652ac5d1f7884b34cdbb7b75e74a4a71bbb61326417a8040c1b93631c0b38ee9fdc8672657ee158
checksum: 3/b54433bf0128a26c5720d35785a7bc7ca0f72e8984e2fefcead1baeaee20266a8a6c397dd0598e74a9615b79142afb46bc937a218c887b10ca967278b508d933
languageName: node
linkType: hard
@ -19903,8 +19903,8 @@ __metadata:
linkType: hard
"remark-stringify@npm:^8.0.0":
version: 8.0.0
resolution: "remark-stringify@npm:8.0.0"
version: 8.1.0
resolution: "remark-stringify@npm:8.1.0"
dependencies:
ccount: ^1.0.0
is-alphanumeric: ^1.0.0
@ -19920,7 +19920,7 @@ __metadata:
stringify-entities: ^3.0.0
unherit: ^1.0.4
xtend: ^4.0.1
checksum: 3/57b620d1becc700bc188563dc7a7757eeb1b5a42f389f550384ebd127f6266953aeb070d0bcdde689bacdfa68e7910ddbe312fd62cc2a18b8ebb85275e0cc387
checksum: 3/acc73ce9b8a96a52b43f791dbd59e5778443a73305b12e196c332fbe1bb6c71c9d6c68305c43b077c22b44314bd47ad901e15ac91f1a4b670a0335af3c951cdc
languageName: node
linkType: hard
@ -24443,11 +24443,11 @@ __metadata:
linkType: hard
"windows-release@npm:^3.1.0":
version: 3.3.0
resolution: "windows-release@npm:3.3.0"
version: 3.3.1
resolution: "windows-release@npm:3.3.1"
dependencies:
execa: ^1.0.0
checksum: 3/23318b65efd3a14c9d1401c005706ba54f41b8bad16f85a2511744f2daa4ff04385111271c8ea1824bbad898cf75797ca9d0ba03d770b4bbaab37ba5aea86e80
checksum: 3/209dd36f044399c4d1c52b8352ba924d2d79da51959a1e5aa34a22b67e869a513df430f618cb897002c4be014e180f57a5c3d160208605352053f54887bffb2d
languageName: node
linkType: hard