Remove global registry imports (only use on api) (#4218)

* Remove global registry imports (only use on api)

* Additional

* QR only displayed when valid

* ApiSigner
This commit is contained in:
Jaco Greeff 2020-12-17 11:18:34 +01:00 committed by GitHub
parent 240d159ffb
commit 7d071d147d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 119 additions and 112 deletions

View File

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

View File

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

View File

@ -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 = '<unknown>';
function CodeRow ({ buttons, children, className, code: { json }, isInline, withTags }: Props): React.ReactElement<Props> {
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 (

View File

@ -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<CodeJson>): Promise<void> {
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 : {}),

View File

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

View File

@ -146,10 +146,12 @@ function NetworkSpecs ({ chainInfo, className }: Props): React.ReactElement<Prop
/>
</Column>
<Column>
<QrNetworkSpecs
className='settings--networkSpecs-qr'
networkSpecs={debouncedQrData}
/>
{qrData.genesisHash && (
<QrNetworkSpecs
className='settings--networkSpecs-qr'
networkSpecs={debouncedQrData}
/>
)}
</Column>
</Columar>
);

View File

@ -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<string, string>
};
}
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<string, string>
}
? createInfo(api, systemChain, systemName)
: null,
[api, isApiReady, systemChain, systemName]
);

View File

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

View File

@ -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<string, boolean> = {};
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<SortedTargets> {
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)

View File

@ -192,7 +192,7 @@ function Api ({ children, store, url }: Props): React.ReactElement<Props> | 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 });

View File

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

View File

@ -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<Props> {
const { t } = useTranslation();
const { api } = useApi();
const [si, setSi] = useState<SiDef | null>(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(

View File

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

View File

@ -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<Props> {
const { api } = useApi();
const [stqueue, _setStQueue] = useState<QueueStatus[]>([]);
const [txqueue, _setTxQueue] = useState<QueueTx[]>([]);
const stRef = useRef(stqueue);
@ -218,14 +219,14 @@ function Queue ({ children }: Props): React.ReactElement<Props> {
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 =>

View File

@ -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<string, DeriveStakerReward[]> = {};
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;
}

View File

@ -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<Props, State> {
params: null
};
public static getDerivedStateFromProps ({ isDisabled, params, registry = defaultRegistry, values }: Props, prevState: State): Pick<State, never> | null {
public static getDerivedStateFromProps ({ isDisabled, params, registry = api.registry, values }: Props, prevState: State): Pick<State, never> | null {
const isSame = JSON.stringify(prevState.params) === JSON.stringify(params);
if (isDisabled || isSame) {
@ -79,7 +79,7 @@ class Params extends React.PureComponent<Props, State> {
}
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) {

View File

@ -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<SignerOptions>, setQrState: (state: QrState) => void): Promise<['qr' | 'signing', string, Partial<SignerOptions>]> {
async function extractParams (api: ApiPromise, address: string, options: Partial<SignerOptions>, setQrState: (state: QrState) => void): Promise<['qr' | 'signing', string, Partial<SignerOptions>]> {
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<SignerOptions>,
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<Props> | 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));

View File

@ -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<SignerResult> {
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 });

View File

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

View File

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

View File

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