From 7d071d147dca4e2d2239d6be8cc8ceb5fd53650a Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Thu, 17 Dec 2020 11:18:34 +0100 Subject: [PATCH] Remove global registry imports (only use on api) (#4218) * Remove global registry imports (only use on api) * Additional * QR only displayed when valid * ApiSigner --- .../src/modals/MultisigApprove.tsx | 13 ++++---- .../src/modals/ProxyOverview.tsx | 13 ++++---- .../page-contracts/src/shared/CodeRow.tsx | 11 ++++--- packages/page-contracts/src/store.ts | 4 +-- packages/page-settings/src/Developer.tsx | 7 +++-- .../src/Metadata/NetworkSpecs.tsx | 10 +++--- packages/page-settings/src/useChainInfo.ts | 31 +++++++++++-------- packages/page-settings/src/useExtensions.ts | 15 +++++---- packages/page-staking/src/useSortedTargets.ts | 9 +++--- packages/react-api/src/Api.tsx | 2 +- packages/react-api/src/index.ts | 2 -- packages/react-components/src/InputNumber.tsx | 22 +++++++------ .../react-components/src/Params/Proposal.tsx | 7 ++--- .../react-components/src/Status/Queue.tsx | 9 +++--- packages/react-hooks/src/useOwnEraRewards.ts | 10 +++--- packages/react-params/src/index.tsx | 6 ++-- packages/react-signer/src/TxSigned.tsx | 17 +++++----- .../react-signer/src/signers/AccountSigner.ts | 10 +++--- .../react-signer/src/signers/ApiSigner.ts | 10 +++--- .../react-signer/src/signers/LedgerSigner.ts | 14 +++++---- packages/react-signer/src/signers/QrSigner.ts | 9 +++--- 21 files changed, 119 insertions(+), 112 deletions(-) diff --git a/packages/page-accounts/src/modals/MultisigApprove.tsx b/packages/page-accounts/src/modals/MultisigApprove.tsx index 07e2a2f57c..287a7f8f88 100644 --- a/packages/page-accounts/src/modals/MultisigApprove.tsx +++ b/packages/page-accounts/src/modals/MultisigApprove.tsx @@ -7,7 +7,6 @@ import type { AccountId, Call, H256, Multisig } from '@polkadot/types/interfaces import React, { useCallback, useEffect, useMemo, useState } from 'react'; import styled from 'styled-components'; -import { registry } from '@polkadot/react-api'; import { Dropdown, Input, InputAddress, Modal, Toggle, TxButton } from '@polkadot/react-components'; import { useAccounts, useApi, useWeight } from '@polkadot/react-hooks'; import { assert, isHex } from '@polkadot/util'; @@ -74,10 +73,10 @@ function MultisigApprove ({ className = '', onClose, ongoing, threshold, who }: useEffect((): void => { setOthers( who - .map((w) => registry.createType('AccountId', w)) + .map((w) => api.createType('AccountId', w)) .filter((w) => !w.eq(signatory)) ); - }, [signatory, who]); + }, [api, signatory, who]); // Filter the who by those not approved yet that is an actual account we own. In the case of // rejections, we defer to the the first approver, since he is the only one to send the cancel @@ -87,14 +86,14 @@ function MultisigApprove ({ className = '', onClose, ongoing, threshold, who }: setWhoFilter( who - .map((w) => registry.createType('AccountId', w).toString()) + .map((w) => api.createType('AccountId', w).toString()) .filter((w) => allAccounts.some((a) => a === w) && multisig && ( type === 'nay' ? multisig.approvals[0].eq(w) : hasThreshold || !multisig.approvals.some((a) => a.eq(w)) )) ); - }, [allAccounts, multisig, threshold, type, who]); + }, [api, allAccounts, multisig, threshold, type, who]); // based on the type, multisig, others create the tx. This can be either an approval or final call useEffect((): void => { @@ -127,7 +126,7 @@ function MultisigApprove ({ className = '', onClose, ongoing, threshold, who }: try { assert(isHex(callHex), 'Hex call data required'); - const callData = registry.createType('Call', callHex); + const callData = api.createType('Call', callHex); setCallData( callData.hash.eq(hash) @@ -138,7 +137,7 @@ function MultisigApprove ({ className = '', onClose, ongoing, threshold, who }: setCallData(null); } }, - [hash] + [api, hash] ); const isAye = type === 'aye'; diff --git a/packages/page-accounts/src/modals/ProxyOverview.tsx b/packages/page-accounts/src/modals/ProxyOverview.tsx index 011776a62f..546d7c4549 100644 --- a/packages/page-accounts/src/modals/ProxyOverview.tsx +++ b/packages/page-accounts/src/modals/ProxyOverview.tsx @@ -9,7 +9,6 @@ import BN from 'bn.js'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; import styled from 'styled-components'; -import { registry } from '@polkadot/react-api'; import { Button, Dropdown, InputAddress, Modal, TxButton } from '@polkadot/react-components'; import { useApi } from '@polkadot/react-hooks'; import { isFunction } from '@polkadot/util'; @@ -169,14 +168,14 @@ function ProxyOverview ({ className, onClose, previousProxy, proxiedAccount }: P }, [api, batchStackPrevious, batchStackAdded]); const typeOpts = useMemo( - () => registry.createType('ProxyType').defKeys.map((text, value) => ({ text, value })), - [] + () => api.createType('ProxyType').defKeys.map((text, value) => ({ text, value })), + [api] ); const _addProxy = useCallback( () => { - const newAccount = registry.createType('AccountId', proxiedAccount); - const newType = registry.createType('ProxyType', 0); + const newAccount = api.createType('AccountId', proxiedAccount); + const newType = api.createType('ProxyType', 0); setAddedProxies((prevState) => { const newProxy: [AccountId, ProxyType] = [newAccount, newType]; @@ -209,7 +208,7 @@ function ProxyOverview ({ className, onClose, previousProxy, proxiedAccount }: P const _changeProxyAccount = useCallback( (index: number, address: string | null) => { - const accountId = registry.createType('AccountId', address); + const accountId = api.createType('AccountId', address); const oldType = addedProxies[index][1]; // update the UI with the new selected account @@ -235,7 +234,7 @@ function ProxyOverview ({ className, onClose, previousProxy, proxiedAccount }: P const _changeProxyType = useCallback( (index: number, newTypeNumber: number | undefined) => { - const newType = registry.createType('ProxyType', newTypeNumber); + const newType = api.createType('ProxyType', newTypeNumber); const oldAccount = addedProxies[index][0]; // update the UI with the new selected type diff --git a/packages/page-contracts/src/shared/CodeRow.tsx b/packages/page-contracts/src/shared/CodeRow.tsx index 8ff615ce8f..df052c794e 100644 --- a/packages/page-contracts/src/shared/CodeRow.tsx +++ b/packages/page-contracts/src/shared/CodeRow.tsx @@ -6,9 +6,9 @@ import type { CodeStored } from '../types'; import React, { useCallback, useEffect, useState } from 'react'; import styled from 'styled-components'; -import { registry } from '@polkadot/react-api'; import { Icon } from '@polkadot/react-components'; import Row from '@polkadot/react-components/Row'; +import { useApi } from '@polkadot/react-hooks'; import contracts from '../store'; @@ -25,6 +25,7 @@ const DEFAULT_HASH = '0x'; const DEFAULT_NAME = ''; function CodeRow ({ buttons, children, className, code: { json }, isInline, withTags }: Props): React.ReactElement { + const { api } = useApi(); const [name, setName] = useState(json.name || DEFAULT_NAME); const [tags, setTags] = useState(json.tags || []); const [codeHash, setCodeHash] = useState(json.codeHash || DEFAULT_HASH); @@ -40,20 +41,20 @@ function CodeRow ({ buttons, children, className, code: { json }, isInline, with const trimmedName = name.trim(); if (trimmedName && codeHash) { - contracts.saveCode(registry.createType('Hash', codeHash), { name }) + contracts.saveCode(api.createType('Hash', codeHash), { name }) .catch((e): void => console.error(e)); } }, - [codeHash, name] + [api, codeHash, name] ); const _onSaveTags = useCallback( (): void => { codeHash && contracts - .saveCode(registry.createType('Hash', codeHash), { tags }) + .saveCode(api.createType('Hash', codeHash), { tags }) .catch((e): void => console.error(e)); }, - [codeHash, tags] + [api, codeHash, tags] ); return ( diff --git a/packages/page-contracts/src/store.ts b/packages/page-contracts/src/store.ts index a0c00d627c..91b049210c 100644 --- a/packages/page-contracts/src/store.ts +++ b/packages/page-contracts/src/store.ts @@ -8,7 +8,7 @@ import EventEmitter from 'eventemitter3'; import store from 'store'; import { Abi } from '@polkadot/api-contract'; -import { api, registry } from '@polkadot/react-api'; +import { api } from '@polkadot/react-api'; const KEY_CODE = 'code:'; @@ -29,7 +29,7 @@ class Store extends EventEmitter { // eslint-disable-next-line @typescript-eslint/require-await public async saveCode (codeHash: string | Hash, partial: Partial): Promise { - const hex = (typeof codeHash === 'string' ? registry.createType('Hash', codeHash) : codeHash).toHex(); + const hex = (typeof codeHash === 'string' ? api.registry.createType('Hash', codeHash) : codeHash).toHex(); const existing = this.getCode(hex); const json = { ...(existing ? existing.json : {}), diff --git a/packages/page-settings/src/Developer.tsx b/packages/page-settings/src/Developer.tsx index 4a73b66caa..24ffe38456 100644 --- a/packages/page-settings/src/Developer.tsx +++ b/packages/page-settings/src/Developer.tsx @@ -8,9 +8,9 @@ import { Trans } from 'react-i18next'; import store from 'store'; import styled from 'styled-components'; -import { registry } from '@polkadot/react-api'; import { decodeUrlTypes, encodeUrlTypes } from '@polkadot/react-api/urlTypes'; import { Button, CopyButton, Editor, InputFile } from '@polkadot/react-components'; +import { useApi } from '@polkadot/react-hooks'; import { isJsonObject, stringToU8a, u8aToString } from '@polkadot/util'; import { useTranslation } from './translate'; @@ -33,6 +33,7 @@ interface Props { function Developer ({ className = '', onStatusChange }: Props): React.ReactElement { const { t } = useTranslation(); + const { api } = useApi(); const [code, setCode] = useState(EMPTY_CODE); const [isJsonValid, setIsJsonValid] = useState(true); const [isTypesValid, setIsTypesValid] = useState(true); @@ -131,7 +132,7 @@ function Developer ({ className = '', onStatusChange }: Props): React.ReactEleme let url = null; try { - registry.register(types); + api.registerTypes(types); store.set('types', types); setIsTypesValid(true); onStatusChange({ @@ -155,7 +156,7 @@ function Developer ({ className = '', onStatusChange }: Props): React.ReactEleme setSharedUrl(url); }, - [onStatusChange, t, types] + [api, onStatusChange, t, types] ); const typesHasNoEntries = Object.keys(types).length === 0; diff --git a/packages/page-settings/src/Metadata/NetworkSpecs.tsx b/packages/page-settings/src/Metadata/NetworkSpecs.tsx index 36147d9752..8d9cc91e2a 100644 --- a/packages/page-settings/src/Metadata/NetworkSpecs.tsx +++ b/packages/page-settings/src/Metadata/NetworkSpecs.tsx @@ -146,10 +146,12 @@ function NetworkSpecs ({ chainInfo, className }: Props): React.ReactElement - + {qrData.genesisHash && ( + + )} ); diff --git a/packages/page-settings/src/useChainInfo.ts b/packages/page-settings/src/useChainInfo.ts index 9425219e39..505dc92e6e 100644 --- a/packages/page-settings/src/useChainInfo.ts +++ b/packages/page-settings/src/useChainInfo.ts @@ -1,33 +1,38 @@ // Copyright 2017-2020 @polkadot/app-settings authors & contributors // SPDX-License-Identifier: Apache-2.0 +import type { ApiPromise } from '@polkadot/api'; import type { ChainInfo } from './types'; import { useMemo } from 'react'; import { getSystemChainColor, getSystemIcon } from '@polkadot/apps-config'; -import { DEFAULT_DECIMALS, DEFAULT_SS58, registry } from '@polkadot/react-api'; +import { DEFAULT_DECIMALS, DEFAULT_SS58 } from '@polkadot/react-api'; import { useApi } from '@polkadot/react-hooks'; import { getSpecTypes } from '@polkadot/types-known'; import { isNumber } from '@polkadot/util'; +function createInfo (api: ApiPromise, systemChain: string, systemName: string): ChainInfo { + return { + chain: systemChain, + color: getSystemChainColor(systemChain, systemName), + genesisHash: api.genesisHash.toHex(), + icon: getSystemIcon(systemName), + metaCalls: Buffer.from(api.runtimeMetadata.asCallsOnly.toU8a()).toString('base64'), + specVersion: api.runtimeVersion.specVersion.toNumber(), + ss58Format: isNumber(api.registry.chainSS58) ? api.registry.chainSS58 : DEFAULT_SS58.toNumber(), + tokenDecimals: isNumber(api.registry.chainDecimals) ? api.registry.chainDecimals : DEFAULT_DECIMALS.toNumber(), + tokenSymbol: api.registry.chainToken || 'Unit', + types: getSpecTypes(api.registry, systemChain, api.runtimeVersion.specName, api.runtimeVersion.specVersion) as unknown as Record + }; +} + export default function useChainInfo (): ChainInfo | null { const { api, isApiReady, systemChain, systemName } = useApi(); return useMemo( () => isApiReady - ? { - chain: systemChain, - color: getSystemChainColor(systemChain, systemName), - genesisHash: api.genesisHash.toHex(), - icon: getSystemIcon(systemName), - metaCalls: Buffer.from(api.runtimeMetadata.asCallsOnly.toU8a()).toString('base64'), - specVersion: api.runtimeVersion.specVersion.toNumber(), - ss58Format: isNumber(api.registry.chainSS58) ? api.registry.chainSS58 : DEFAULT_SS58.toNumber(), - tokenDecimals: isNumber(api.registry.chainDecimals) ? api.registry.chainDecimals : DEFAULT_DECIMALS.toNumber(), - tokenSymbol: api.registry.chainToken || 'Unit', - types: getSpecTypes(registry, systemChain, api.runtimeVersion.specName, api.runtimeVersion.specVersion) as unknown as Record - } + ? createInfo(api, systemChain, systemName) : null, [api, isApiReady, systemChain, systemName] ); diff --git a/packages/page-settings/src/useExtensions.ts b/packages/page-settings/src/useExtensions.ts index eb72076c2e..8cd3b62e58 100644 --- a/packages/page-settings/src/useExtensions.ts +++ b/packages/page-settings/src/useExtensions.ts @@ -1,13 +1,12 @@ // Copyright 2017-2020 @polkadot/app-settings authors & contributors // SPDX-License-Identifier: Apache-2.0 +import type { ApiPromise } from '@polkadot/api'; import type { InjectedExtension, InjectedMetadataKnown, MetadataDef } from '@polkadot/extension-inject/types'; import { useEffect, useMemo, useState } from 'react'; import store from 'store'; -import { ApiPromise } from '@polkadot/api'; -import { registry } from '@polkadot/react-api'; import { useApi } from '@polkadot/react-hooks'; interface ExtensionKnown { @@ -52,9 +51,9 @@ function saveProperties (api: ApiPromise, { name, version }: InjectedExtension): allProperties[name] = { extensionVersion: version, - ss58Format: registry.chainSS58, - tokenDecimals: registry.chainDecimals, - tokenSymbol: registry.chainToken + ss58Format: api.registry.chainSS58, + tokenDecimals: api.registry.chainDecimals, + tokenSymbol: api.registry.chainToken }; store.set(storeKey, allProperties); @@ -73,9 +72,9 @@ function hasCurrentProperties (api: ApiPromise, { extension }: ExtensionKnown): const { ss58Format, tokenDecimals, tokenSymbol } = allProperties[extension.name]; - return ss58Format === registry.chainSS58 && - tokenDecimals === registry.chainDecimals && - tokenSymbol === registry.chainToken; + return ss58Format === api.registry.chainSS58 && + tokenDecimals === api.registry.chainDecimals && + tokenSymbol === api.registry.chainToken; } // filter extensions based on the properties we have available diff --git a/packages/page-staking/src/useSortedTargets.ts b/packages/page-staking/src/useSortedTargets.ts index 289df9c69e..7d57230c0a 100644 --- a/packages/page-staking/src/useSortedTargets.ts +++ b/packages/page-staking/src/useSortedTargets.ts @@ -8,7 +8,6 @@ import type { SortedTargets, TargetSortBy, ValidatorInfo } from './types'; import BN from 'bn.js'; import { useMemo } from 'react'; -import { registry } from '@polkadot/react-api'; import { calcInflation, useAccounts, useApi, useCall } from '@polkadot/react-hooks'; import { BN_ONE, BN_ZERO } from '@polkadot/util'; @@ -78,9 +77,9 @@ function sortValidators (list: ValidatorInfo[]): ValidatorInfo[] { ); } -function extractSingle (allAccounts: string[], derive: DeriveStakingElected | DeriveStakingWaiting, favorites: string[], { activeEra, eraLength, lastEra, sessionLength }: LastEra, historyDepth?: BN): [ValidatorInfo[], string[]] { +function extractSingle (api: ApiPromise, allAccounts: string[], derive: DeriveStakingElected | DeriveStakingWaiting, favorites: string[], { activeEra, eraLength, lastEra, sessionLength }: LastEra, historyDepth?: BN): [ValidatorInfo[], string[]] { const nominators: Record = {}; - const emptyExposure = registry.createType('Exposure'); + const emptyExposure = api.createType('Exposure'); const earliestEra = historyDepth && lastEra.sub(historyDepth).addn(1); const list = derive.info.map(({ accountId, exposure = emptyExposure, stakingLedger, validatorPrefs }): ValidatorInfo => { // some overrides (e.g. Darwinia Crab) does not have the own field in Exposure @@ -149,8 +148,8 @@ function extractSingle (allAccounts: string[], derive: DeriveStakingElected | De } function extractInfo (api: ApiPromise, allAccounts: string[], electedDerive: DeriveStakingElected, waitingDerive: DeriveStakingWaiting, favorites: string[], totalIssuance: BN, lastEraInfo: LastEra, historyDepth?: BN): Partial { - const [elected, nominators] = extractSingle(allAccounts, electedDerive, favorites, lastEraInfo, historyDepth); - const [waiting] = extractSingle(allAccounts, waitingDerive, favorites, lastEraInfo); + const [elected, nominators] = extractSingle(api, allAccounts, electedDerive, favorites, lastEraInfo, historyDepth); + const [waiting] = extractSingle(api, allAccounts, waitingDerive, favorites, lastEraInfo); const activeTotals = elected .filter(({ isActive }) => isActive) .map(({ bondTotal }) => bondTotal) diff --git a/packages/react-api/src/Api.tsx b/packages/react-api/src/Api.tsx index 9d5fa694d4..029bc2d1d7 100644 --- a/packages/react-api/src/Api.tsx +++ b/packages/react-api/src/Api.tsx @@ -192,7 +192,7 @@ function Api ({ children, store, url }: Props): React.ReactElement | null // initial initialization useEffect((): void => { const provider = new WsProvider(url); - const signer = new ApiSigner(queuePayload, queueSetTxStatus); + const signer = new ApiSigner(registry, queuePayload, queueSetTxStatus); const types = getDevTypes(); api = new ApiPromise({ provider, registry, signer, types, typesBundle, typesChain, typesSpec }); diff --git a/packages/react-api/src/index.ts b/packages/react-api/src/index.ts index 87e3d68eb7..63dfca77d8 100644 --- a/packages/react-api/src/index.ts +++ b/packages/react-api/src/index.ts @@ -5,7 +5,6 @@ import Api, { api, DEFAULT_DECIMALS, DEFAULT_SS58 } from './Api'; import ApiContext from './ApiContext'; import { withApi, withCallDiv, withCalls, withMulti, withObservable } from './hoc'; import { clearLedger, getLedger, isLedger, isLedgerCapable } from './ledger'; -import registry from './typeRegistry'; export { api, @@ -13,7 +12,6 @@ export { ApiContext, DEFAULT_DECIMALS, DEFAULT_SS58, - registry, withApi, withCalls, withCallDiv, diff --git a/packages/react-components/src/InputNumber.tsx b/packages/react-components/src/InputNumber.tsx index f5065c2ede..b1322a159b 100644 --- a/packages/react-components/src/InputNumber.tsx +++ b/packages/react-components/src/InputNumber.tsx @@ -1,6 +1,7 @@ // Copyright 2017-2020 @polkadot/react-components authors & contributors // SPDX-License-Identifier: Apache-2.0 +import type { ApiPromise } from '@polkadot/api'; import type { SiDef } from '@polkadot/util/types'; import type { BitLength } from './types'; @@ -8,7 +9,7 @@ import BN from 'bn.js'; import React, { useCallback, useEffect, useState } from 'react'; import styled from 'styled-components'; -import { registry } from '@polkadot/react-api'; +import { useApi } from '@polkadot/react-hooks'; import { BN_TEN, BN_ZERO, formatBalance, isBn } from '@polkadot/util'; import { BitLengthOption } from './constants'; @@ -106,7 +107,7 @@ function isValidNumber (bn: BN, bitLength: BitLength, isZeroable: boolean, maxVa return true; } -function inputToBn (input: string, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [BN, boolean] { +function inputToBn (api: ApiPromise, input: string, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [BN, boolean] { const [siPower, basePower, siUnitPower] = getSiPowers(si); // eslint-disable-next-line @typescript-eslint/prefer-regexp-exec @@ -120,7 +121,7 @@ function inputToBn (input: string, si: SiDef | null, bitLength: BitLength, isZer } const div = new BN(input.replace(/\.\d*$/, '')); - const modString = input.replace(/^\d+\./, '').substr(0, registry.chainDecimals); + const modString = input.replace(/^\d+\./, '').substr(0, api.registry.chainDecimals); const mod = new BN(modString); result = div @@ -137,8 +138,8 @@ function inputToBn (input: string, si: SiDef | null, bitLength: BitLength, isZer ]; } -function getValuesFromString (value: string, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [string, BN, boolean] { - const [valueBn, isValid] = inputToBn(value, si, bitLength, isZeroable, maxValue); +function getValuesFromString (api: ApiPromise, value: string, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [string, BN, boolean] { + const [valueBn, isValid] = inputToBn(api, value, si, bitLength, isZeroable, maxValue); return [ value, @@ -159,18 +160,19 @@ function getValuesFromBn (valueBn: BN, si: SiDef | null): [string, BN, boolean] ]; } -function getValues (value: BN | string = BN_ZERO, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [string, BN, boolean] { +function getValues (api: ApiPromise, 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); + : getValuesFromString(api, value, si, bitLength, isZeroable, maxValue); } function InputNumber ({ autoFocus, bitLength = DEFAULT_BITLENGTH, children, className = '', defaultValue, help, isDecimal, isFull, isSi, isDisabled, isError = false, isWarning, isZeroable = true, label, labelExtra, maxLength, maxValue, onChange, onEnter, onEscape, placeholder, value: propsValue }: Props): React.ReactElement { const { t } = useTranslation(); + const { api } = useApi(); const [si, setSi] = useState(isSi ? formatBalance.findSi('-') : null); const [isPreKeyDown, setIsPreKeyDown] = useState(false); const [[value, valueBn, isValid], setValues] = useState<[string, BN, boolean]>( - getValues(propsValue || defaultValue, si, bitLength, isZeroable, maxValue) + getValues(api, propsValue || defaultValue, si, bitLength, isZeroable, maxValue) ); useEffect((): void => { @@ -179,9 +181,9 @@ function InputNumber ({ autoFocus, bitLength = DEFAULT_BITLENGTH, children, clas const _onChangeWithSi = useCallback( (input: string, si: SiDef | null) => setValues( - getValuesFromString(input, si, bitLength, isZeroable, maxValue) + getValuesFromString(api, input, si, bitLength, isZeroable, maxValue) ), - [bitLength, isZeroable, maxValue] + [api, bitLength, isZeroable, maxValue] ); const _onChange = useCallback( diff --git a/packages/react-components/src/Params/Proposal.tsx b/packages/react-components/src/Params/Proposal.tsx index 240720fb81..24066c4986 100644 --- a/packages/react-components/src/Params/Proposal.tsx +++ b/packages/react-components/src/Params/Proposal.tsx @@ -5,20 +5,19 @@ import type { Props, RawParam } from '@polkadot/react-params/types'; import React, { useCallback } from 'react'; -import { registry } from '@polkadot/react-api'; import { useApi } from '@polkadot/react-hooks'; import ExtrinsicDisplay from './Extrinsic'; function ProposalDisplay ({ className = '', isDisabled, isError, label, onChange, onEnter, onEscape, withLabel }: Props): React.ReactElement { - const { apiDefaultTxSudo } = useApi(); + const { api, apiDefaultTxSudo } = useApi(); const _onChange = useCallback( ({ isValid, value }: RawParam): void => { let proposal = null; if (isValid && value) { - proposal = registry.createType('Proposal', value); + proposal = api.createType('Proposal', value); } onChange && onChange({ @@ -26,7 +25,7 @@ function ProposalDisplay ({ className = '', isDisabled, isError, label, onChange value: proposal }); }, - [onChange] + [api, onChange] ); return ( diff --git a/packages/react-components/src/Status/Queue.tsx b/packages/react-components/src/Status/Queue.tsx index 0bb6584a1b..e6d511da2b 100644 --- a/packages/react-components/src/Status/Queue.tsx +++ b/packages/react-components/src/Status/Queue.tsx @@ -10,7 +10,7 @@ import type { ActionStatus, ActionStatusPartial, PartialQueueTxExtrinsic, Partia import React, { useCallback, useRef, useState } from 'react'; import { SubmittableResult } from '@polkadot/api'; -import { registry } from '@polkadot/react-api'; +import { useApi } from '@polkadot/react-hooks'; import jsonrpc from '@polkadot/types/interfaces/jsonrpc'; import { getContractAbi } from '../util'; @@ -145,6 +145,7 @@ function extractEvents (result?: SubmittableResult): ActionStatus[] { } function Queue ({ children }: Props): React.ReactElement { + const { api } = useApi(); const [stqueue, _setStQueue] = useState([]); const [txqueue, _setTxQueue] = useState([]); const stRef = useRef(stqueue); @@ -218,14 +219,14 @@ function Queue ({ children }: Props): React.ReactElement { addToTxQueue({ accountId: payload.address, // this is not great, but the Extrinsic we don't need a submittable - extrinsic: registry.createType('Extrinsic', - { method: registry.createType('Call', payload.method) }, + extrinsic: api.createType('Extrinsic', + { method: api.createType('Call', payload.method) }, { version: payload.version } ) as unknown as SubmittableExtrinsic, payload, signerCb }), - [addToTxQueue] + [api, addToTxQueue] ); const queueRpc = useCallback( (value: PartialQueueTxRpc): void => diff --git a/packages/react-hooks/src/useOwnEraRewards.ts b/packages/react-hooks/src/useOwnEraRewards.ts index 18b6a3dad9..aa9deda903 100644 --- a/packages/react-hooks/src/useOwnEraRewards.ts +++ b/packages/react-hooks/src/useOwnEraRewards.ts @@ -1,13 +1,13 @@ // Copyright 2017-2020 @polkadot/react-hooks authors & contributors // SPDX-License-Identifier: Apache-2.0 +import type { ApiPromise } from '@polkadot/api'; import type { DeriveEraPoints, DeriveEraRewards, DeriveStakerReward } from '@polkadot/api-derive/types'; import type { EraIndex } from '@polkadot/types/interfaces'; import type { StakerState } from './types'; import { useEffect, useState } from 'react'; -import { registry } from '@polkadot/react-api'; import { BN_ZERO } from '@polkadot/util'; import { useApi } from './useApi'; @@ -45,7 +45,7 @@ function getRewards ([[stashIds], available]: [[string[]], DeriveStakerReward[][ }; } -function getValRewards (validatorEras: ValidatorWithEras[], erasPoints: DeriveEraPoints[], erasRewards: DeriveEraRewards[]): State { +function getValRewards (api: ApiPromise, validatorEras: ValidatorWithEras[], erasPoints: DeriveEraPoints[], erasRewards: DeriveEraRewards[]): State { const allRewards: Record = {}; validatorEras.forEach(({ eras, stashId }): void => { @@ -57,7 +57,7 @@ function getValRewards (validatorEras: ValidatorWithEras[], erasPoints: DeriveEr const reward = eraPoints.validators[stashId].mul(eraRewards.eraReward).div(eraPoints.eraPoints); if (!reward.isZero()) { - const total = registry.createType('Balance', reward); + const total = api.createType('Balance', reward); if (!allRewards[stashId]) { allRewards[stashId] = []; @@ -141,9 +141,9 @@ export function useOwnEraRewards (maxEras?: number, ownValidators?: StakerState[ useEffect((): void => { mountedRef && erasPoints && erasRewards && ownValidators && setState( - getValRewards(validatorEras, erasPoints, erasRewards) + getValRewards(api, validatorEras, erasPoints, erasRewards) ); - }, [erasPoints, erasRewards, mountedRef, ownValidators, validatorEras]); + }, [api, erasPoints, erasRewards, mountedRef, ownValidators, validatorEras]); return state; } diff --git a/packages/react-params/src/index.tsx b/packages/react-params/src/index.tsx index 4e47c4e18a..025ae9ecfd 100644 --- a/packages/react-params/src/index.tsx +++ b/packages/react-params/src/index.tsx @@ -7,7 +7,7 @@ import type { ComponentMap, ParamDef, RawParam, RawParamOnChangeValue, RawParams import React from 'react'; -import { registry as defaultRegistry } from '@polkadot/react-api'; +import { api } from '@polkadot/react-api'; import { ErrorBoundary } from '@polkadot/react-components'; import Holder from './Holder'; @@ -41,7 +41,7 @@ class Params extends React.PureComponent { params: null }; - public static getDerivedStateFromProps ({ isDisabled, params, registry = defaultRegistry, values }: Props, prevState: State): Pick | null { + public static getDerivedStateFromProps ({ isDisabled, params, registry = api.registry, values }: Props, prevState: State): Pick | null { const isSame = JSON.stringify(prevState.params) === JSON.stringify(params); if (isDisabled || isSame) { @@ -79,7 +79,7 @@ class Params extends React.PureComponent { } public render (): React.ReactNode { - const { children, className = '', isDisabled, onEnter, onEscape, overrides, params, registry = defaultRegistry, withBorder = true } = this.props; + const { children, className = '', isDisabled, onEnter, onEscape, overrides, params, registry = api.registry, withBorder = true } = this.props; const { values = this.props.values } = this.state; if (!values || !values.length) { diff --git a/packages/react-signer/src/TxSigned.tsx b/packages/react-signer/src/TxSigned.tsx index e89b1db223..b4291f1770 100644 --- a/packages/react-signer/src/TxSigned.tsx +++ b/packages/react-signer/src/TxSigned.tsx @@ -14,7 +14,6 @@ import styled from 'styled-components'; import { ApiPromise } from '@polkadot/api'; import { web3FromSource } from '@polkadot/extension-dapp'; -import { registry } from '@polkadot/react-api'; import { Button, ErrorBoundary, Modal, Output, StatusContext, Toggle } from '@polkadot/react-components'; import { useApi, useToggle } from '@polkadot/react-hooks'; import keyring from '@polkadot/ui-keyring'; @@ -138,14 +137,14 @@ async function wrapTx (api: ApiPromise, currentItem: QueueTx, { isMultiCall, mul return tx; } -async function extractParams (address: string, options: Partial, setQrState: (state: QrState) => void): Promise<['qr' | 'signing', string, Partial]> { +async function extractParams (api: ApiPromise, address: string, options: Partial, setQrState: (state: QrState) => void): Promise<['qr' | 'signing', string, Partial]> { const pair = keyring.getPair(address); const { meta: { accountOffset, addressOffset, isExternal, isHardware, isInjected, source } } = pair; if (isHardware) { - return ['signing', address, { ...options, signer: new LedgerSigner(accountOffset as number || 0, addressOffset as number || 0) }]; + return ['signing', address, { ...options, signer: new LedgerSigner(api.registry, accountOffset as number || 0, addressOffset as number || 0) }]; } else if (isExternal) { - return ['qr', address, { ...options, signer: new QrSigner(setQrState) }]; + return ['qr', address, { ...options, signer: new QrSigner(api.registry, setQrState) }]; } else if (isInjected) { const injected = await web3FromSource(source as string); @@ -154,7 +153,7 @@ async function extractParams (address: string, options: Partial, return ['signing', address, { ...options, signer: injected.signer }]; } - return ['signing', pair.address, { ...options, signer: new AccountSigner(pair) }]; + return ['signing', pair.address, { ...options, signer: new AccountSigner(api.registry, pair) }]; } function TxSigned ({ className, currentItem, requestAddress }: Props): React.ReactElement | null { @@ -227,13 +226,13 @@ function TxSigned ({ className, currentItem, requestAddress }: Props): React.Rea if (senderInfo.signAddress && currentItem.payload) { const { id, payload, signerCb = NOOP } = currentItem; const pair = keyring.getPair(senderInfo.signAddress); - const result = registry.createType('ExtrinsicPayload', payload, { version: payload.version }).sign(pair); + const result = api.createType('ExtrinsicPayload', payload, { version: payload.version }).sign(pair); signerCb(id, { id, ...result }); queueSetTxStatus(id, 'completed'); } }, - [] + [api] ); const _onSend = useCallback( @@ -241,7 +240,7 @@ function TxSigned ({ className, currentItem, requestAddress }: Props): React.Rea if (senderInfo.signAddress) { const [tx, [status, pairOrAddress, options]] = await Promise.all([ wrapTx(api, currentItem, senderInfo), - extractParams(senderInfo.signAddress, { nonce: -1, tip }, setQrState) + extractParams(api, senderInfo.signAddress, { nonce: -1, tip }, setQrState) ]); queueSetTxStatus(currentItem.id, status); @@ -257,7 +256,7 @@ function TxSigned ({ className, currentItem, requestAddress }: Props): React.Rea if (senderInfo.signAddress) { const [tx, [, pairOrAddress, options]] = await Promise.all([ wrapTx(api, currentItem, senderInfo), - extractParams(senderInfo.signAddress, { ...signedOptions, tip }, setQrState) + extractParams(api, senderInfo.signAddress, { ...signedOptions, tip }, setQrState) ]); setSignedTx(await signAsync(queueSetTxStatus, currentItem, tx, pairOrAddress, options)); diff --git a/packages/react-signer/src/signers/AccountSigner.ts b/packages/react-signer/src/signers/AccountSigner.ts index 3beecd5d24..b0ba8dd8d6 100644 --- a/packages/react-signer/src/signers/AccountSigner.ts +++ b/packages/react-signer/src/signers/AccountSigner.ts @@ -3,9 +3,7 @@ import type { Signer, SignerResult } from '@polkadot/api/types'; import type { KeyringPair } from '@polkadot/keyring/types'; -import type { SignerPayloadJSON } from '@polkadot/types/types'; - -import { registry } from '@polkadot/react-api'; +import type { Registry, SignerPayloadJSON } from '@polkadot/types/types'; import { lockAccount } from '../util'; @@ -13,14 +11,16 @@ let id = 0; export default class AccountSigner implements Signer { readonly #keyringPair: KeyringPair; + readonly #registry: Registry; - constructor (keyringPair: KeyringPair) { + constructor (registry: Registry, keyringPair: KeyringPair) { this.#keyringPair = keyringPair; + this.#registry = registry; } public async signPayload (payload: SignerPayloadJSON): Promise { return new Promise((resolve): void => { - const signed = registry.createType('ExtrinsicPayload', payload, { version: payload.version }).sign(this.#keyringPair); + const signed = this.#registry.createType('ExtrinsicPayload', payload, { version: payload.version }).sign(this.#keyringPair); lockAccount(this.#keyringPair); resolve({ id: ++id, ...signed }); diff --git a/packages/react-signer/src/signers/ApiSigner.ts b/packages/react-signer/src/signers/ApiSigner.ts index 1def58cec7..e062d49b9d 100644 --- a/packages/react-signer/src/signers/ApiSigner.ts +++ b/packages/react-signer/src/signers/ApiSigner.ts @@ -5,19 +5,19 @@ import type { SubmittableResult } from '@polkadot/api'; import type { Signer, SignerResult } from '@polkadot/api/types'; import type { QueueTxMessageSetStatus, QueueTxPayloadAdd, QueueTxStatus } from '@polkadot/react-components/Status/types'; import type { Hash } from '@polkadot/types/interfaces'; -import type { SignerPayloadJSON } from '@polkadot/types/types'; +import type { Registry, SignerPayloadJSON } from '@polkadot/types/types'; -import { registry } from '@polkadot/react-api'; import { ClassOf } from '@polkadot/types/create'; export default class ApiSigner implements Signer { readonly #queuePayload: QueueTxPayloadAdd; - readonly #queueSetTxStatus: QueueTxMessageSetStatus; + readonly #registry: Registry; - constructor (queuePayload: QueueTxPayloadAdd, queueSetTxStatus: QueueTxMessageSetStatus) { + constructor (registry: Registry, queuePayload: QueueTxPayloadAdd, queueSetTxStatus: QueueTxMessageSetStatus) { this.#queuePayload = queuePayload; this.#queueSetTxStatus = queueSetTxStatus; + this.#registry = registry; } public async signPayload (payload: SignerPayloadJSON): Promise { @@ -33,7 +33,7 @@ export default class ApiSigner implements Signer { } public update (id: number, result: Hash | SubmittableResult): void { - if (result instanceof ClassOf(registry, 'Hash')) { + if (result instanceof ClassOf(this.#registry, 'Hash')) { this.#queueSetTxStatus(id, 'sent', result.toHex()); } else { this.#queueSetTxStatus(id, result.status.type.toLowerCase() as QueueTxStatus, status); diff --git a/packages/react-signer/src/signers/LedgerSigner.ts b/packages/react-signer/src/signers/LedgerSigner.ts index ad791eba08..c7bbe76812 100644 --- a/packages/react-signer/src/signers/LedgerSigner.ts +++ b/packages/react-signer/src/signers/LedgerSigner.ts @@ -2,23 +2,25 @@ // SPDX-License-Identifier: Apache-2.0 import type { Signer, SignerResult } from '@polkadot/api/types'; -import type { SignerPayloadJSON } from '@polkadot/types/types'; +import type { Registry, SignerPayloadJSON } from '@polkadot/types/types'; -import { getLedger, registry } from '@polkadot/react-api'; +import { getLedger } from '@polkadot/react-api'; let id = 0; export default class LedgerSigner implements Signer { - #accountOffset: number; - #addressOffset: number; + readonly #accountOffset: number; + readonly #addressOffset: number; + readonly #registry: Registry; - constructor (accountOffset: number, addressOffset: number) { + constructor (registry: Registry, accountOffset: number, addressOffset: number) { this.#accountOffset = accountOffset; this.#addressOffset = addressOffset; + this.#registry = registry; } public async signPayload (payload: SignerPayloadJSON): Promise { - const raw = registry.createType('ExtrinsicPayload', payload, { version: payload.version }); + const raw = this.#registry.createType('ExtrinsicPayload', payload, { version: payload.version }); const { signature } = await getLedger().sign(raw.toU8a(true), this.#accountOffset, this.#addressOffset); return { id: ++id, signature }; diff --git a/packages/react-signer/src/signers/QrSigner.ts b/packages/react-signer/src/signers/QrSigner.ts index b3cff3ed10..ea94603a86 100644 --- a/packages/react-signer/src/signers/QrSigner.ts +++ b/packages/react-signer/src/signers/QrSigner.ts @@ -2,16 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import type { Signer, SignerResult } from '@polkadot/api/types'; -import type { SignerPayloadJSON } from '@polkadot/types/types'; +import type { Registry, SignerPayloadJSON } from '@polkadot/types/types'; import type { QrState } from '../types'; -import { registry } from '@polkadot/react-api'; import { blake2AsU8a } from '@polkadot/util-crypto'; export default class QrSigner implements Signer { + readonly #registry: Registry; readonly #setState: (state: QrState) => void; - constructor (setState: (state: QrState) => void) { + constructor (registry: Registry, setState: (state: QrState) => void) { + this.#registry = registry; this.#setState = setState; } @@ -19,7 +20,7 @@ export default class QrSigner implements Signer { return new Promise((resolve, reject): void => { // limit size of the transaction const isQrHashed = (payload.method.length > 5000); - const wrapper = registry.createType('ExtrinsicPayload', payload, { version: payload.version }); + const wrapper = this.#registry.createType('ExtrinsicPayload', payload, { version: payload.version }); const qrPayload = isQrHashed ? blake2AsU8a(wrapper.toU8a(true)) : wrapper.toU8a();