From c16722784508ca8b6084f8c3a99b45f8c4d3ed29 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Fri, 15 Nov 2019 10:51:12 +0100 Subject: [PATCH] Add useApiContext (#1890) * Add useApiContext * Add missing withApiContext import * useCacheKey, rename headers * Adjustment on sessionRewards naming * Renames based on defacto standards --- packages/app-123code/src/SummaryBar.tsx | 7 ++- packages/app-accounts/src/modals/Create.tsx | 6 +- packages/app-accounts/src/modals/Transfer.tsx | 6 +- packages/app-claims/src/Claim.tsx | 6 +- packages/app-explorer/src/Forks.tsx | 6 +- packages/app-explorer/src/NodeInfo/index.tsx | 6 +- packages/app-explorer/src/index.tsx | 4 +- packages/app-generic-asset/src/Transfer.tsx | 7 ++- packages/app-js/src/Playground.tsx | 6 +- .../src/Actions/Account/SetSessionKey.tsx | 6 +- packages/app-staking/src/Overview/Address.tsx | 7 ++- .../app-staking/src/Overview/CurrentList.tsx | 7 +-- packages/app-staking/src/Overview/index.tsx | 4 +- packages/app-staking/src/Query/Validator.tsx | 15 ++--- packages/app-staking/src/Query/index.tsx | 4 +- packages/app-staking/src/index.tsx | 12 ++-- packages/app-staking/src/types.ts | 2 +- packages/app-storage/src/Selection/Consts.tsx | 6 +- .../app-storage/src/Selection/Modules.tsx | 6 +- packages/app-storage/src/Selection/index.tsx | 6 +- packages/apps/src/Content/index.tsx | 4 +- packages/apps/src/SideBar/Item.tsx | 7 ++- packages/apps/src/SideBar/NodeInfo.tsx | 6 +- packages/apps/src/SideBar/index.tsx | 6 +- packages/apps/src/overlays/Connecting.tsx | 6 +- packages/react-components/src/ChainImg.tsx | 6 +- packages/react-components/src/ChainLock.tsx | 6 +- .../react-components/src/IdentityIcon.tsx | 5 +- .../src/InputConsts/index.tsx | 6 +- .../src/InputExtrinsic/index.tsx | 6 +- .../react-components/src/InputRpc/index.tsx | 6 +- .../src/InputStorage/SelectKey.tsx | 6 +- .../src/InputStorage/index.tsx | 6 +- .../react-components/src/LinkPolkascan.tsx | 6 +- packages/react-components/src/Params/Call.tsx | 6 +- .../react-components/src/Params/Proposal.tsx | 6 +- .../react-components/src/TreasuryProposal.tsx | 6 +- packages/react-hooks/src/index.ts | 9 +-- packages/react-hooks/src/useApiContext.tsx | 12 ++++ packages/react-hooks/src/useCacheKey.ts | 17 +++++ .../src/{debounce.tsx => useDebounce.tsx} | 2 +- .../src/{favorites.tsx => useFavorites.tsx} | 15 +++-- ...ssionSlashes.tsx => useSessionRewards.tsx} | 63 ++++++++----------- packages/react-query/src/BlockAuthors.tsx | 6 +- packages/react-query/src/Chain.tsx | 6 +- packages/react-query/src/Events.tsx | 6 +- packages/react-query/src/NodeName.tsx | 6 +- packages/react-query/src/NodeVersion.tsx | 6 +- packages/react-signer/src/Checks/index.tsx | 7 ++- 49 files changed, 205 insertions(+), 179 deletions(-) create mode 100644 packages/react-hooks/src/useApiContext.tsx create mode 100644 packages/react-hooks/src/useCacheKey.ts rename packages/react-hooks/src/{debounce.tsx => useDebounce.tsx} (89%) rename packages/react-hooks/src/{favorites.tsx => useFavorites.tsx} (58%) rename packages/react-hooks/src/{sessionSlashes.tsx => useSessionRewards.tsx} (74%) diff --git a/packages/app-123code/src/SummaryBar.tsx b/packages/app-123code/src/SummaryBar.tsx index 9242644597..1dcd41fe80 100644 --- a/packages/app-123code/src/SummaryBar.tsx +++ b/packages/app-123code/src/SummaryBar.tsx @@ -7,9 +7,10 @@ import { AccountId } from '@polkadot/types/interfaces'; import { BareProps, I18nProps } from '@polkadot/react-components/types'; import BN from 'bn.js'; -import React, { useContext } from 'react'; -import { ApiContext, withCalls } from '@polkadot/react-api'; +import React from 'react'; +import { withCalls } from '@polkadot/react-api'; import { Bubble, IdentityIcon } from '@polkadot/react-components'; +import { useApiContext } from '@polkadot/react-hooks'; import { formatBalance, formatNumber } from '@polkadot/util'; import translate from './translate'; @@ -22,7 +23,7 @@ interface Props extends BareProps, I18nProps { } function SummaryBar ({ balances_totalIssuance, chain_bestNumber, chain_bestNumberLag, staking_validators }: Props): React.ReactElement { - const { api, systemChain, systemName, systemVersion } = useContext(ApiContext); + const { api, systemChain, systemName, systemVersion } = useApiContext(); return ( diff --git a/packages/app-accounts/src/modals/Create.tsx b/packages/app-accounts/src/modals/Create.tsx index d8239e5127..8838b0fbde 100644 --- a/packages/app-accounts/src/modals/Create.tsx +++ b/packages/app-accounts/src/modals/Create.tsx @@ -9,11 +9,11 @@ import { KeypairType } from '@polkadot/util-crypto/types'; import { ModalProps } from '../types'; import FileSaver from 'file-saver'; -import React, { useContext, useState } from 'react'; +import React, { useState } from 'react'; import styled from 'styled-components'; import { DEV_PHRASE } from '@polkadot/keyring/defaults'; -import { ApiContext } from '@polkadot/react-api'; import { AddressRow, Button, Dropdown, Input, InputAddress, Modal, Password } from '@polkadot/react-components'; +import { useApiContext } from '@polkadot/react-hooks'; import keyring from '@polkadot/ui-keyring'; import uiSettings from '@polkadot/ui-settings'; import { isHex, u8aToHex } from '@polkadot/util'; @@ -151,7 +151,7 @@ function createAccount (suri: string, pairType: KeypairType, name: string, passw } function Create ({ className, onClose, onStatusChange, seed: propsSeed, t, type: propsType }: Props): React.ReactElement { - const { isDevelopment } = useContext(ApiContext); + const { isDevelopment } = useApiContext(); const [{ address, deriveError, derivePath, isSeedValid, pairType, seed, seedType }, setAddress] = useState(generateSeed(propsSeed, '', propsSeed ? 'raw' : 'bip', propsType)); const [isConfirmationOpen, setIsConfirmationOpen] = useState(false); const [{ isNameValid, name }, setName] = useState({ isNameValid: false, name: '' }); diff --git a/packages/app-accounts/src/modals/Transfer.tsx b/packages/app-accounts/src/modals/Transfer.tsx index 3ce8f8bc61..6b9b05d953 100644 --- a/packages/app-accounts/src/modals/Transfer.tsx +++ b/packages/app-accounts/src/modals/Transfer.tsx @@ -8,12 +8,12 @@ import { DerivedFees } from '@polkadot/api-derive/types'; import { I18nProps } from '@polkadot/react-components/types'; import BN from 'bn.js'; -import React, { useContext, useEffect, useState } from 'react'; +import React, { useEffect, useState } from 'react'; import styled from 'styled-components'; import { Button, InputAddress, InputBalance, Modal, TxButton } from '@polkadot/react-components'; +import { useApiContext } from '@polkadot/react-hooks'; import { Available } from '@polkadot/react-query'; import Checks from '@polkadot/react-signer/Checks'; -import { ApiContext } from '@polkadot/react-api'; import translate from '../translate'; @@ -65,7 +65,7 @@ const ZERO = new BN(0); // } function Transfer ({ className, onClose, recipientId: propRecipientId, senderId: propSenderId, t }: Props): React.ReactElement { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [amount, setAmount] = useState(new BN(0)); const [extrinsic, setExtrinsic] = useState(null); const [hasAvailable, setHasAvailable] = useState(true); diff --git a/packages/app-claims/src/Claim.tsx b/packages/app-claims/src/Claim.tsx index f598d3425b..d5d9e7b71a 100644 --- a/packages/app-claims/src/Claim.tsx +++ b/packages/app-claims/src/Claim.tsx @@ -6,10 +6,10 @@ import { Option } from '@polkadot/types'; import { BalanceOf, EthereumAddress } from '@polkadot/types/interfaces'; import { I18nProps } from '@polkadot/react-components/types'; -import React, { useContext, useEffect, useState } from 'react'; +import React, { useEffect, useState } from 'react'; import styled from 'styled-components'; -import { ApiContext } from '@polkadot/react-api'; import { Button, Card } from '@polkadot/react-components'; +import { useApiContext } from '@polkadot/react-hooks'; import { FormatBalance } from '@polkadot/react-query'; import translate from './translate'; @@ -21,7 +21,7 @@ interface Props extends I18nProps { } function Claim ({ button, className, ethereumAddress, t }: Props): React.ReactElement | null { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [claimValue, setClaimValue] = useState(null); const [claimAddress, setClaimAddress] = useState(null); const [isBusy, setIsBusy] = useState(false); diff --git a/packages/app-explorer/src/Forks.tsx b/packages/app-explorer/src/Forks.tsx index c1ecce814c..cc1cf77a63 100644 --- a/packages/app-explorer/src/Forks.tsx +++ b/packages/app-explorer/src/Forks.tsx @@ -7,10 +7,10 @@ import { ApiProps } from '@polkadot/react-api/types'; import { I18nProps } from '@polkadot/react-components/types'; import { Header } from '@polkadot/types/interfaces'; -import React, { useContext, useEffect, useRef, useState } from 'react'; +import React, { useEffect, useRef, useState } from 'react'; import styled from 'styled-components'; -import { ApiContext } from '@polkadot/react-api'; import { CardSummary, IdentityIcon, SummaryBox } from '@polkadot/react-components'; +import { useApiContext } from '@polkadot/react-hooks'; import { formatNumber } from '@polkadot/util'; import translate from './translate'; @@ -204,7 +204,7 @@ function renderRows (rows: Row[]): React.ReactNode[] { } function Forks ({ className, t }: Props): React.ReactElement | null { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [tree, setTree] = useState(null); const childrenRef = useRef>(new Map([['root', []]])); const countRef = useRef({ numBlocks: 0, numForks: 0 }); diff --git a/packages/app-explorer/src/NodeInfo/index.tsx b/packages/app-explorer/src/NodeInfo/index.tsx index 4ee86b19e7..4e9d3ac256 100644 --- a/packages/app-explorer/src/NodeInfo/index.tsx +++ b/packages/app-explorer/src/NodeInfo/index.tsx @@ -5,9 +5,9 @@ import { I18nProps as Props } from '@polkadot/react-components/types'; import { Info } from './types'; -import React, { useContext, useEffect, useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { ApiPromise } from '@polkadot/api'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import Extrinsics from '../BlockInfo/Extrinsics'; import Peers from './Peers'; @@ -32,7 +32,7 @@ async function retrieveInfo (api: ApiPromise): Promise> { } function NodeInfo ({ t }: Props): React.ReactElement { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [info, setInfo] = useState>({}); const [nextRefresh, setNextRefresh] = useState(Date.now()); diff --git a/packages/app-explorer/src/index.tsx b/packages/app-explorer/src/index.tsx index abe7755143..8bf6028456 100644 --- a/packages/app-explorer/src/index.tsx +++ b/packages/app-explorer/src/index.tsx @@ -8,8 +8,8 @@ import { KeyedEvent } from './types'; import React, { useContext } from 'react'; import { Route, Switch } from 'react-router'; import styled from 'styled-components'; -import { ApiContext } from '@polkadot/react-api'; import Tabs from '@polkadot/react-components/Tabs'; +import { useApiContext } from '@polkadot/react-hooks'; import { BlockAuthorsContext, EventsContext } from '@polkadot/react-query'; import uiSettings from '@polkadot/ui-settings'; @@ -24,7 +24,7 @@ interface Props extends AppProps, BareProps, I18nProps { } function ExplorerApp ({ basePath, className, t }: Props): React.ReactElement { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const { lastHeaders } = useContext(BlockAuthorsContext); const events = useContext(EventsContext); diff --git a/packages/app-generic-asset/src/Transfer.tsx b/packages/app-generic-asset/src/Transfer.tsx index 5c171d90a2..0ee6abd332 100644 --- a/packages/app-generic-asset/src/Transfer.tsx +++ b/packages/app-generic-asset/src/Transfer.tsx @@ -6,12 +6,13 @@ import { SubmittableExtrinsic } from '@polkadot/api/promise/types'; import { I18nProps } from '@polkadot/react-components/types'; import BN from 'bn.js'; -import React, { useContext, useEffect, useState } from 'react'; +import React, { useEffect, useState } from 'react'; import styled from 'styled-components'; import { Button, InputAddress, InputBalance, TxButton, Dropdown } from '@polkadot/react-components'; +import { useApiContext } from '@polkadot/react-hooks'; import { Available } from '@polkadot/react-query'; import Checks from '@polkadot/react-signer/Checks'; -import { ApiContext, withMulti, withObservable } from '@polkadot/react-api'; +import { withMulti, withObservable } from '@polkadot/react-api'; import assetRegistry, { AssetsSubjectInfo } from './assetsRegistry'; import translate from './translate'; @@ -30,7 +31,7 @@ interface Option { } function Transfer ({ assets, className, onClose, recipientId: propRecipientId, senderId: propSenderId, t }: Props): React.ReactElement { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [assetId, setAssetId] = useState('0'); const [amount, setAmount] = useState(new BN(0)); const [extrinsic, setExtrinsic] = useState(null); diff --git a/packages/app-js/src/Playground.tsx b/packages/app-js/src/Playground.tsx index 6eafb0eaa4..427297dc7a 100644 --- a/packages/app-js/src/Playground.tsx +++ b/packages/app-js/src/Playground.tsx @@ -7,13 +7,13 @@ import { KeyringInstance } from '@polkadot/keyring/types'; import { AppProps, I18nProps } from '@polkadot/react-components/types'; import { Log, LogType, Snippet } from './types'; -import React, { useContext, useRef, useState, useEffect } from 'react'; +import React, { useRef, useState, useEffect } from 'react'; import { withRouter, RouteComponentProps } from 'react-router'; import { Transition } from 'semantic-ui-react'; import snappy from 'snappyjs'; import styled from 'styled-components'; -import { ApiContext } from '@polkadot/react-api'; import { Button, Dropdown, Editor } from '@polkadot/react-components'; +import { useApiContext } from '@polkadot/react-hooks'; import uiKeyring from '@polkadot/ui-keyring'; import * as types from '@polkadot/types'; import * as util from '@polkadot/util'; @@ -90,7 +90,7 @@ function decodeBase64 (base64: string): Snippet { // FIXME This... ladies & gentlemen, is a mess that should be untangled function Playground ({ className, history, match: { params: { base64 } }, t }: Props): React.ReactElement { - const { api, isDevelopment } = useContext(ApiContext); + const { api, isDevelopment } = useApiContext(); const injectedRef = useRef(null); const [code, setCode] = useState(''); const [isAnimated, setIsAnimated] = useState(true); diff --git a/packages/app-staking/src/Actions/Account/SetSessionKey.tsx b/packages/app-staking/src/Actions/Account/SetSessionKey.tsx index 365be7bb9e..39673f1c23 100644 --- a/packages/app-staking/src/Actions/Account/SetSessionKey.tsx +++ b/packages/app-staking/src/Actions/Account/SetSessionKey.tsx @@ -4,9 +4,9 @@ import { I18nProps } from '@polkadot/react-components/types'; -import React, { useContext, useState } from 'react'; +import React, { useState } from 'react'; import { Button, InputAddress, Input, Modal, TxButton } from '@polkadot/react-components'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import ValidationSessionKey from './InputValidationSessionKey'; import translate from '../../translate'; @@ -22,7 +22,7 @@ interface Props extends I18nProps { const EMPTY_PROOF = new Uint8Array(); function SetSessionKey ({ controllerId, isOpen, onClose, sessionIds, stashId, t }: Props): React.ReactElement | null { - const { isSubstrateV2 } = useContext(ApiContext); + const { isSubstrateV2 } = useApiContext(); const [keysError, setKeysError] = useState(null); const [keys, setKeys] = useState( isSubstrateV2 diff --git a/packages/app-staking/src/Overview/Address.tsx b/packages/app-staking/src/Overview/Address.tsx index 95a607e9cb..eda08efea2 100644 --- a/packages/app-staking/src/Overview/Address.tsx +++ b/packages/app-staking/src/Overview/Address.tsx @@ -8,11 +8,12 @@ import { I18nProps } from '@polkadot/react-components/types'; import { ValidatorFilter } from '../types'; import BN from 'bn.js'; -import React, { useContext, useEffect, useState } from 'react'; +import React, { useEffect, useState } from 'react'; import styled from 'styled-components'; -import { ApiContext, withCalls, withMulti } from '@polkadot/react-api'; +import { withCalls, withMulti } from '@polkadot/react-api'; import { AddressCard, AddressMini, Badge, Expander, Icon } from '@polkadot/react-components'; import { classes } from '@polkadot/react-components/util'; +import { useApiContext } from '@polkadot/react-hooks'; import { formatNumber } from '@polkadot/util'; import translate from '../translate'; @@ -47,7 +48,7 @@ interface StakingState { const WITH_VALIDATOR_PREFS = { validatorPayment: true }; function Address ({ address, authorsMap, className, defaultName, filter, isElected, isFavorite, lastAuthors, myAccounts, points, recentlyOnline, stakingInfo, t, toggleFavorite, withNominations = true }: Props): React.ReactElement | null { - const { api, isSubstrateV2 } = useContext(ApiContext); + const { api, isSubstrateV2 } = useApiContext(); const [extraInfo, setExtraInfo] = useState<[React.ReactNode, React.ReactNode][] | undefined>(); const [hasActivity, setHasActivity] = useState(true); const [{ balanceOpts, controllerId, hasNominators, isNominatorMe, nominators, sessionId, stashId }, setStakingState] = useState({ diff --git a/packages/app-staking/src/Overview/CurrentList.tsx b/packages/app-staking/src/Overview/CurrentList.tsx index c6ba651c3c..44e6a8216e 100644 --- a/packages/app-staking/src/Overview/CurrentList.tsx +++ b/packages/app-staking/src/Overview/CurrentList.tsx @@ -7,10 +7,9 @@ import { I18nProps } from '@polkadot/react-components/types'; import { AccountId, EraPoints, Points } from '@polkadot/types/interfaces'; import { ValidatorFilter } from '../types'; -import React, { useContext, useEffect, useState } from 'react'; -import { ApiContext } from '@polkadot/react-api'; +import React, { useEffect, useState } from 'react'; import { Columar, Column, Dropdown, FilterOverlay } from '@polkadot/react-components'; -import { useFavorites } from '@polkadot/react-hooks'; +import { useApiContext, useFavorites } from '@polkadot/react-hooks'; import keyring from '@polkadot/ui-keyring'; import { STORE_FAVS_BASE } from '../constants'; @@ -57,7 +56,7 @@ function accountsToString (accounts: AccountId[]): string[] { } function CurrentList ({ authorsMap, lastAuthors, next, recentlyOnline, stakingOverview, t }: Props): React.ReactElement { - const { isSubstrateV2 } = useContext(ApiContext); + const { isSubstrateV2 } = useApiContext(); const [favorites, toggleFavorite] = useFavorites(STORE_FAVS_BASE); const [filter, setFilter] = useState('all'); const [myAccounts] = useState(keyring.getAccounts().map(({ address }): string => address)); diff --git a/packages/app-staking/src/Overview/index.tsx b/packages/app-staking/src/Overview/index.tsx index a488b429b9..b7efc4f5a6 100644 --- a/packages/app-staking/src/Overview/index.tsx +++ b/packages/app-staking/src/Overview/index.tsx @@ -6,7 +6,7 @@ import { BareProps } from '@polkadot/react-components/types'; import { ComponentProps } from '../types'; import React, { useContext, useEffect, useState } from 'react'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import { BlockAuthorsContext } from '@polkadot/react-query'; import CurrentList from './CurrentList'; @@ -15,7 +15,7 @@ import Summary from './Summary'; interface Props extends BareProps, ComponentProps {} export default function Overview ({ allControllers, allStashes, className, recentlyOnline, stakingOverview }: Props): React.ReactElement { - const { isSubstrateV2 } = useContext(ApiContext); + const { isSubstrateV2 } = useApiContext(); const { byAuthor, lastBlockAuthors, lastBlockNumber } = useContext(BlockAuthorsContext); const [next, setNext] = useState([]); const validators = stakingOverview && stakingOverview.validators; diff --git a/packages/app-staking/src/Query/Validator.tsx b/packages/app-staking/src/Query/Validator.tsx index e59d9014ab..0cc2f695e2 100644 --- a/packages/app-staking/src/Query/Validator.tsx +++ b/packages/app-staking/src/Query/Validator.tsx @@ -7,11 +7,12 @@ import { Balance, BlockNumber, Hash, Exposure, SessionIndex } from '@polkadot/ty import { SessionRewards, Slash } from '@polkadot/react-hooks/types'; import BN from 'bn.js'; -import React, { useContext, useEffect, useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { Chart, Columar, Column } from '@polkadot/react-components'; import { toShortAddress } from '@polkadot/react-components/util'; -import { ApiContext, withCalls } from '@polkadot/react-api'; +import { withCalls } from '@polkadot/react-api'; import { getHistoric } from '@polkadot/react-api/util'; +import { useApiContext } from '@polkadot/react-hooks'; import { formatBalance, formatNumber } from '@polkadot/util'; import { MAX_SESSIONS } from '../constants'; @@ -21,7 +22,7 @@ interface Props extends I18nProps { blockCounts?: BN[]; className?: string; currentIndex: SessionIndex; - stakingRewards: SessionRewards[]; + sessionRewards: SessionRewards[]; startNumber: BlockNumber; validatorId: string; } @@ -95,8 +96,8 @@ function extractEraSlash (validatorId: string, slashes: Slash[]): BN { }, new BN(0)); } -function Validator ({ blockCounts, className, currentIndex, stakingRewards, startNumber, t, validatorId }: Props): React.ReactElement { - const { api } = useContext(ApiContext); +function Validator ({ blockCounts, className, currentIndex, sessionRewards, startNumber, t, validatorId }: Props): React.ReactElement { + const { api } = useApiContext(); const [blocksLabels, setBlocksLabels] = useState([]); const [blocksChart, setBlocksChart] = useState(null); const [{ rewardsChart, rewardsLabels }, setRewardsInfo] = useState<{ rewardsChart: LineData | null; rewardsLabels: string[] }>({ rewardsChart: null, rewardsLabels: [] }); @@ -124,7 +125,7 @@ function Validator ({ blockCounts, className, currentIndex, stakingRewards, star const rewardsLabels: string[] = []; const rewardsChart: LineData = [[]]; - stakingRewards.forEach(({ sessionIndex, slashes }): void => { + sessionRewards.forEach(({ sessionIndex, slashes }): void => { // this shows the start of the new era, however rewards are for previous rewardsLabels.push(formatNumber(sessionIndex.subn(1))); @@ -135,7 +136,7 @@ function Validator ({ blockCounts, className, currentIndex, stakingRewards, star }); setRewardsInfo({ rewardsChart, rewardsLabels }); - }, [stakingRewards, validatorId]); + }, [sessionRewards, validatorId]); useEffect((): void => { setBlocksLabels( diff --git a/packages/app-staking/src/Query/index.tsx b/packages/app-staking/src/Query/index.tsx index 743823a962..12c410d9af 100644 --- a/packages/app-staking/src/Query/index.tsx +++ b/packages/app-staking/src/Query/index.tsx @@ -47,7 +47,7 @@ interface Props extends I18nProps, ComponentProps, RouteComponentProps<{}> { // /> // -function Query ({ bestNumber, className, stakingRewards, stakingOverview, match: { params: { value } }, t }: Props): React.ReactElement { +function Query ({ bestNumber, className, sessionRewards, stakingOverview, match: { params: { value } }, t }: Props): React.ReactElement { const [startNumber, setStartNumber] = useState(); const [validatorId, setValidatorId] = useState(value || null); @@ -82,7 +82,7 @@ function Query ({ bestNumber, className, stakingRewards, stakingOverview, match: {value && startNumber && stakingOverview && ( diff --git a/packages/app-staking/src/index.tsx b/packages/app-staking/src/index.tsx index eb8880203e..c43758e69f 100644 --- a/packages/app-staking/src/index.tsx +++ b/packages/app-staking/src/index.tsx @@ -9,15 +9,15 @@ import { AccountId, BlockNumber } from '@polkadot/types/interfaces'; import { SubjectInfo } from '@polkadot/ui-keyring/observable/types'; import { ComponentProps } from './types'; -import React, { useContext } from 'react'; +import React from 'react'; import { Route, Switch } from 'react-router'; import { useRouteMatch } from 'react-router-dom'; import styled from 'styled-components'; import { Option } from '@polkadot/types'; import { HelpOverlay } from '@polkadot/react-components'; import Tabs from '@polkadot/react-components/Tabs'; -import { ApiContext, withCalls, withMulti, withObservable } from '@polkadot/react-api'; -import { useSessionSlashes } from '@polkadot/react-hooks'; +import { withCalls, withMulti, withObservable } from '@polkadot/react-api'; +import { useApiContext, useSessionRewards } from '@polkadot/react-hooks'; import accountObservable from '@polkadot/ui-keyring/observable/accounts'; import Accounts from './Actions/Accounts'; @@ -39,8 +39,8 @@ const EMPY_ACCOUNTS: string[] = []; const EMPTY_ALL: [string[], string[]] = [EMPY_ACCOUNTS, EMPY_ACCOUNTS]; function App ({ allAccounts, allStashesAndControllers: [allStashes, allControllers] = EMPTY_ALL, basePath, bestNumber, className, recentlyOnline, stakingOverview, t }: Props): React.ReactElement { - const { api } = useContext(ApiContext); - const stakingRewards = useSessionSlashes(MAX_SESSIONS); + const { api } = useApiContext(); + const sessionRewards = useSessionRewards(MAX_SESSIONS); const routeMatch = useRouteMatch({ path: basePath, strict: true }); const _renderComponent = (Component: React.ComponentType, className?: string): () => React.ReactNode => { // eslint-disable-next-line react/display-name @@ -57,7 +57,7 @@ function App ({ allAccounts, allStashesAndControllers: [allStashes, allControlle bestNumber={bestNumber} className={className} recentlyOnline={recentlyOnline} - stakingRewards={stakingRewards} + sessionRewards={sessionRewards} stakingOverview={stakingOverview} /> ); diff --git a/packages/app-staking/src/types.ts b/packages/app-staking/src/types.ts index a8c1f15812..17700b8d98 100644 --- a/packages/app-staking/src/types.ts +++ b/packages/app-staking/src/types.ts @@ -16,7 +16,7 @@ export interface ComponentProps { bestNumber?: BlockNumber; className?: string; recentlyOnline?: DerivedHeartbeats; - stakingRewards: SessionRewards[]; + sessionRewards: SessionRewards[]; stakingOverview?: DerivedStakingOverview; } diff --git a/packages/app-storage/src/Selection/Consts.tsx b/packages/app-storage/src/Selection/Consts.tsx index 3195e5421e..883f60721f 100644 --- a/packages/app-storage/src/Selection/Consts.tsx +++ b/packages/app-storage/src/Selection/Consts.tsx @@ -7,16 +7,16 @@ import { I18nProps } from '@polkadot/react-components/types'; import { ConstValue } from '@polkadot/react-components/InputConsts/types'; import { ComponentProps } from '../types'; -import React, { useContext, useState } from 'react'; -import { ApiContext } from '@polkadot/react-api'; +import React, { useState } from 'react'; import { Button, InputConsts } from '@polkadot/react-components'; +import { useApiContext } from '@polkadot/react-hooks'; import translate from '../translate'; interface Props extends ComponentProps, I18nProps {} function Consts ({ onAdd, t }: Props): React.ReactElement { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [defaultValue] = useState((): ConstValue => { const section = Object.keys(api.consts)[0]; const method = Object.keys(api.consts[section])[0]; diff --git a/packages/app-storage/src/Selection/Modules.tsx b/packages/app-storage/src/Selection/Modules.tsx index f1ae9487db..ca2c20dc51 100644 --- a/packages/app-storage/src/Selection/Modules.tsx +++ b/packages/app-storage/src/Selection/Modules.tsx @@ -7,11 +7,11 @@ import { I18nProps } from '@polkadot/react-components/types'; import { RawParams } from '@polkadot/react-params/types'; import { ComponentProps, StorageEntryPromise } from '../types'; -import React, { useContext, useState } from 'react'; +import React, { useState } from 'react'; import { getTypeDef } from '@polkadot/types'; import { Button, InputStorage } from '@polkadot/react-components'; import Params from '@polkadot/react-params'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import { isNull, isUndefined } from '@polkadot/util'; import translate from '../translate'; @@ -32,7 +32,7 @@ function areParamsValid (values: RawParams): boolean { } function Modules ({ onAdd, t }: Props): React.ReactElement { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [{ defaultValues, isLinked, key, params }, setKey] = useState<{ defaultValues: RawParams | undefined | null; isLinked: boolean; key: StorageEntryPromise; params: ParamsType }>({ defaultValues: undefined, isLinked: false, key: api.query.timestamp.now, params: [] }); const [{ isValid, values }, setValues] = useState<{ isValid: boolean; values: RawParams }>({ isValid: true, values: [] }); diff --git a/packages/app-storage/src/Selection/index.tsx b/packages/app-storage/src/Selection/index.tsx index 272a20a318..9b7eaaa637 100644 --- a/packages/app-storage/src/Selection/index.tsx +++ b/packages/app-storage/src/Selection/index.tsx @@ -5,10 +5,10 @@ import { I18nProps } from '@polkadot/react-components/types'; import { ComponentProps, QueryTypes, ParitalQueryTypes } from '../types'; -import React, { useContext } from 'react'; +import React from 'react'; import { Route, Switch } from 'react-router'; -import { ApiContext } from '@polkadot/react-api'; import { Tabs } from '@polkadot/react-components'; +import { useApiContext } from '@polkadot/react-hooks'; import Consts from './Consts'; import Modules from './Modules'; @@ -23,7 +23,7 @@ interface Props extends I18nProps { let id = -1; function Selection ({ basePath, onAdd, t }: Props): React.ReactElement { - const { isSubstrateV2 } = useContext(ApiContext); + const { isSubstrateV2 } = useApiContext(); const _onAdd = (query: ParitalQueryTypes): void => onAdd({ ...query, id: ++id }); const _renderComponent = (Component: React.ComponentType): () => React.ReactNode => // eslint-disable-next-line react/display-name diff --git a/packages/apps/src/Content/index.tsx b/packages/apps/src/Content/index.tsx index 0e2057f728..8200ea142a 100644 --- a/packages/apps/src/Content/index.tsx +++ b/packages/apps/src/Content/index.tsx @@ -8,8 +8,8 @@ import React, { useContext } from 'react'; import { withRouter, RouteComponentProps } from 'react-router'; import styled from 'styled-components'; import routing from '@polkadot/apps-routing'; -import { ApiContext } from '@polkadot/react-api'; import { StatusContext } from '@polkadot/react-components'; +import { useApiContext } from '@polkadot/react-hooks'; import Status from './Status'; import translate from '../translate'; @@ -26,7 +26,7 @@ const unknown = { }; function Content ({ className, location, t }: Props): React.ReactElement { - const { isApiConnected, isApiReady } = useContext(ApiContext); + const { isApiConnected, isApiReady } = useApiContext(); const { queueAction, stqueue, txqueue } = useContext(StatusContext); const app = location.pathname.slice(1) || ''; const { Component, display: { needsApi }, name } = routing.routes.find((route): boolean => diff --git a/packages/apps/src/SideBar/Item.tsx b/packages/apps/src/SideBar/Item.tsx index 2758538f25..7dd550ee4d 100644 --- a/packages/apps/src/SideBar/Item.tsx +++ b/packages/apps/src/SideBar/Item.tsx @@ -8,12 +8,13 @@ import { SubjectInfo } from '@polkadot/ui-keyring/observable/types'; import { Route } from '@polkadot/apps-routing/types'; import { AccountId } from '@polkadot/types/interfaces'; -import React, { useContext, useEffect, useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { NavLink } from 'react-router-dom'; import { ApiPromise } from '@polkadot/api'; import { Icon, Menu, Tooltip } from '@polkadot/react-components'; import accountObservable from '@polkadot/ui-keyring/observable/accounts'; -import { ApiContext, withCalls, withMulti, withObservable } from '@polkadot/react-api'; +import { withCalls, withMulti, withObservable } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import { isFunction } from '@polkadot/util'; import translate from '../translate'; @@ -77,7 +78,7 @@ function checkVisible (name: string, { api, isApiReady, isApiConnected }: ApiPro } function Item ({ allAccounts, route: { Modal, display, i18n, icon, name }, t, isCollapsed, onClick, sudoKey }: Props): React.ReactElement | null { - const apiProps = useContext(ApiContext); + const apiProps = useApiContext(); const [hasAccounts, setHasAccounts] = useState(false); const [hasSudo, setHasSudo] = useState(false); const [isVisible, setIsVisible] = useState(false); diff --git a/packages/apps/src/SideBar/NodeInfo.tsx b/packages/apps/src/SideBar/NodeInfo.tsx index 4ed6ea4c0f..a4295da4f2 100644 --- a/packages/apps/src/SideBar/NodeInfo.tsx +++ b/packages/apps/src/SideBar/NodeInfo.tsx @@ -4,9 +4,9 @@ import { BareProps as Props } from '@polkadot/react-components/types'; -import React, { useContext } from 'react'; +import React from 'react'; import styled from 'styled-components'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import { NodeName, NodeVersion } from '@polkadot/react-query'; // eslint-disable-next-line @typescript-eslint/no-var-requires @@ -15,7 +15,7 @@ const pkgJson = require('../../package.json'); const uiInfo = `apps v${pkgJson.version}`; function NodeInfo ({ className }: Props): React.ReactElement { - const { api, isApiReady } = useContext(ApiContext); + const { api, isApiReady } = useApiContext(); return (
diff --git a/packages/apps/src/SideBar/index.tsx b/packages/apps/src/SideBar/index.tsx index c78825930f..e5fb457e98 100644 --- a/packages/apps/src/SideBar/index.tsx +++ b/packages/apps/src/SideBar/index.tsx @@ -7,12 +7,12 @@ import { SIDEBAR_MENU_THRESHOLD } from '../constants'; import './SideBar.css'; -import React, { useContext, useState } from 'react'; +import React, { useState } from 'react'; import styled from 'styled-components'; import { Responsive } from 'semantic-ui-react'; import routing from '@polkadot/apps-routing'; -import { ApiContext } from '@polkadot/react-api'; import { Button, ChainImg, Icon, Menu, media } from '@polkadot/react-components'; +import { useApiContext } from '@polkadot/react-hooks'; import { classes } from '@polkadot/react-components/util'; import { BestNumber, Chain } from '@polkadot/react-query'; @@ -31,7 +31,7 @@ interface Props extends I18nProps { } function SideBar ({ className, collapse, handleResize, isCollapsed, toggleMenu, menuOpen }: Props): React.ReactElement { - const { api, isApiReady } = useContext(ApiContext); + const { api, isApiReady } = useApiContext(); const [modals, setModals] = useState>( routing.routes.reduce((result: Record, route): Record => { if (route && route.Modal) { diff --git a/packages/apps/src/overlays/Connecting.tsx b/packages/apps/src/overlays/Connecting.tsx index bf27e04846..cee9564fd8 100644 --- a/packages/apps/src/overlays/Connecting.tsx +++ b/packages/apps/src/overlays/Connecting.tsx @@ -5,9 +5,9 @@ import { ApiProps } from '@polkadot/react-api/types'; import { I18nProps as Props } from '@polkadot/react-components/types'; -import React, { useContext } from 'react'; +import React from 'react'; import styled from 'styled-components'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import settings from '@polkadot/ui-settings'; import translate from '../translate'; @@ -60,7 +60,7 @@ function ConnectOverlay ({ className, isApiConnected, t }: ApiProps & Props): Re } function Connecting (props: Props): React.ReactElement | null { - const api = useContext(ApiContext); + const api = useApiContext(); return ExtensionOverlay({ ...props, ...api }) || ConnectOverlay({ ...props, ...api }); } diff --git a/packages/react-components/src/ChainImg.tsx b/packages/react-components/src/ChainImg.tsx index d5237cec8c..b9fd24689a 100644 --- a/packages/react-components/src/ChainImg.tsx +++ b/packages/react-components/src/ChainImg.tsx @@ -2,9 +2,9 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import React, { useContext } from 'react'; +import React from 'react'; import styled from 'styled-components'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; // the imports here as a bit all-over, non-aphabetical - since we expect this to grow, // rather organise based on type, grouping chains and nodes as opposed to location @@ -54,7 +54,7 @@ interface Props { } function ChainImg ({ className, logo = '', onClick }: Props): React.ReactElement { - const { systemChain, systemName } = useContext(ApiContext); + const { systemChain, systemName } = useApiContext(); const img = LOGOS[logo] || CHAINS[systemChain] || NODES[systemName] || EMPTY; return ( diff --git a/packages/react-components/src/ChainLock.tsx b/packages/react-components/src/ChainLock.tsx index fbcdc5ed4b..bb44ca73ce 100644 --- a/packages/react-components/src/ChainLock.tsx +++ b/packages/react-components/src/ChainLock.tsx @@ -4,8 +4,8 @@ import { I18nProps } from '@polkadot/react-components/types'; -import React, { useContext } from 'react'; -import { ApiContext } from '@polkadot/react-api'; +import React from 'react'; +import { useApiContext } from '@polkadot/react-hooks'; import translate from './translate'; import Toggle from './Toggle'; @@ -17,7 +17,7 @@ interface Props extends I18nProps { } function ChainLock ({ genesisHash, onChange, t }: Props): React.ReactElement | null { - const { isDevelopment, api } = useContext(ApiContext); + const { isDevelopment, api } = useApiContext(); if (isDevelopment) { return null; diff --git a/packages/react-components/src/IdentityIcon.tsx b/packages/react-components/src/IdentityIcon.tsx index 616688250a..0b3dd0f79e 100644 --- a/packages/react-components/src/IdentityIcon.tsx +++ b/packages/react-components/src/IdentityIcon.tsx @@ -7,7 +7,8 @@ import { IdentityProps } from '@polkadot/react-identicon/types'; import { I18nProps } from './types'; import React, { useContext, useEffect, useState } from 'react'; -import { ApiContext, withCalls, withMulti } from '@polkadot/react-api'; +import { withCalls, withMulti } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import BaseIdentityIcon from '@polkadot/react-identicon'; import uiSettings from '@polkadot/ui-settings'; @@ -33,7 +34,7 @@ export function getIdentityTheme (systemName: string): 'empty' { } function IdentityIcon ({ className, onCopy, prefix, size, style, t, theme, validators, value }: Props): React.ReactElement { - const { systemName } = useContext(ApiContext); + const { systemName } = useApiContext(); const { queueAction } = useContext(StatusContext); const [address, setAddress] = useState(); const [isValidator, setIsValidator] = useState(false); diff --git a/packages/react-components/src/InputConsts/index.tsx b/packages/react-components/src/InputConsts/index.tsx index 31655ad4db..8b6bc8ff0f 100644 --- a/packages/react-components/src/InputConsts/index.tsx +++ b/packages/react-components/src/InputConsts/index.tsx @@ -9,9 +9,9 @@ import { ConstValue, ConstValueBase } from './types'; import '../InputExtrinsic/InputExtrinsic.css'; -import React, { useContext, useState } from 'react'; +import React, { useState } from 'react'; import { ApiPromise } from '@polkadot/api'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import Labelled from '../Labelled'; import translate from '../translate'; @@ -43,7 +43,7 @@ function getValue (api: ApiPromise, { method, section }: ConstValueBase): ConstV } function InputConsts ({ className, defaultValue, help, label, onChange, style, withLabel }: Props): React.ReactElement { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [optionsMethod, setOptionsMethod] = useState(keyOptions(api, defaultValue.section)); const [optionsSection] = useState(sectionOptions(api)); const [value, setValue] = useState(getValue(api, defaultValue)); diff --git a/packages/react-components/src/InputExtrinsic/index.tsx b/packages/react-components/src/InputExtrinsic/index.tsx index fe17e00cef..5da3de4d7c 100644 --- a/packages/react-components/src/InputExtrinsic/index.tsx +++ b/packages/react-components/src/InputExtrinsic/index.tsx @@ -8,8 +8,8 @@ import { DropdownOptions } from '../util/types'; import './InputExtrinsic.css'; -import React, { useContext, useState } from 'react'; -import { ApiContext } from '@polkadot/react-api'; +import React, { useState } from 'react'; +import { useApiContext } from '@polkadot/react-hooks'; import Labelled from '../Labelled'; import translate from '../translate'; @@ -30,7 +30,7 @@ interface Props extends I18nProps { } function InputExtrinsic ({ className, defaultValue, help, label, onChange, style, withLabel }: Props): React.ReactElement { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [optionsMethod, setOptionsMethod] = useState(methodOptions(api, defaultValue.section)); const [optionsSection] = useState(sectionOptions(api)); const [value, setValue] = useState((): CallFunction => defaultValue); diff --git a/packages/react-components/src/InputRpc/index.tsx b/packages/react-components/src/InputRpc/index.tsx index bbace3b9a0..1f1325748a 100644 --- a/packages/react-components/src/InputRpc/index.tsx +++ b/packages/react-components/src/InputRpc/index.tsx @@ -10,9 +10,9 @@ import { I18nProps } from '../types'; import '../InputExtrinsic/InputExtrinsic.css'; -import React, { useContext, useState } from 'react'; +import React, { useState } from 'react'; import map from '@polkadot/jsonrpc'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import Labelled from '../Labelled'; import translate from '../translate'; @@ -31,7 +31,7 @@ interface Props extends I18nProps { } function InputRpc ({ className, defaultValue, help, label, onChange, style, withLabel }: Props): React.ReactElement { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [optionsMethod, setOptionsMethod] = useState(methodOptions(api, defaultValue.section)); const [optionsSection] = useState(sectionOptions(api)); const [value, setValue] = useState((): RpcMethod => defaultValue); diff --git a/packages/react-components/src/InputStorage/SelectKey.tsx b/packages/react-components/src/InputStorage/SelectKey.tsx index 9cebedb87d..95130499cb 100644 --- a/packages/react-components/src/InputStorage/SelectKey.tsx +++ b/packages/react-components/src/InputStorage/SelectKey.tsx @@ -6,9 +6,9 @@ import { DropdownOptions } from '../util/types'; import { BareProps } from '../types'; import { StorageEntryPromise } from './types'; -import React, { useContext } from 'react'; +import React from 'react'; import { ApiPromise } from '@polkadot/api'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import Dropdown from '../Dropdown'; import { classes } from '../util'; @@ -29,7 +29,7 @@ function transform (api: ApiPromise, { value }: Props): (method: string) => Stor } export default function SelectKey (props: Props): React.ReactElement | null { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const { className, isError, onChange, options, style, value } = props; if (!options.length) { diff --git a/packages/react-components/src/InputStorage/index.tsx b/packages/react-components/src/InputStorage/index.tsx index 04bb2669f2..fde76b6a30 100644 --- a/packages/react-components/src/InputStorage/index.tsx +++ b/packages/react-components/src/InputStorage/index.tsx @@ -10,8 +10,8 @@ import { StorageEntryPromise } from './types'; import '../InputExtrinsic/InputExtrinsic.css'; -import React, { useContext, useState } from 'react'; -import { ApiContext } from '@polkadot/react-api'; +import React, { useState } from 'react'; +import { useApiContext } from '@polkadot/react-hooks'; import Labelled from '../Labelled'; import translate from '../translate'; @@ -30,7 +30,7 @@ interface Props extends I18nProps { } function InputStorage ({ className, defaultValue, help, label, onChange, style, withLabel }: Props): React.ReactElement { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [optionsMethod, setOptionsMethod] = useState(keyOptions(api, defaultValue.creator.section)); const [optionsSection] = useState(sectionOptions(api)); const [value, setValue] = useState((): StorageEntryPromise => defaultValue); diff --git a/packages/react-components/src/LinkPolkascan.tsx b/packages/react-components/src/LinkPolkascan.tsx index 51e645fd37..4cb8c655d9 100644 --- a/packages/react-components/src/LinkPolkascan.tsx +++ b/packages/react-components/src/LinkPolkascan.tsx @@ -4,9 +4,9 @@ import { I18nProps } from './types'; -import React, { useContext } from 'react'; +import React from 'react'; import styled from 'styled-components'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import translate from './translate'; @@ -34,7 +34,7 @@ const TYPES: Record = { }; function LinkPolkascan ({ className, data, t, type }: Props): React.ReactElement | null { - const { systemChain } = useContext(ApiContext); + const { systemChain } = useApiContext(); const extChain = CHAINS[systemChain]; const extType = TYPES[type]; diff --git a/packages/react-components/src/Params/Call.tsx b/packages/react-components/src/Params/Call.tsx index be3511fb5c..a3d8b412d9 100644 --- a/packages/react-components/src/Params/Call.tsx +++ b/packages/react-components/src/Params/Call.tsx @@ -5,13 +5,13 @@ import { SubmittableExtrinsicFunction } from '@polkadot/api/types'; import { Props } from '@polkadot/react-params/types'; -import React, { useContext } from 'react'; -import { ApiContext } from '@polkadot/react-api'; +import React from 'react'; +import { useApiContext } from '@polkadot/react-hooks'; import Extrinsic from './Extrinsic'; export default function Call ({ className, isDisabled, isError, label, onChange, onEnter, style, withLabel }: Props): React.ReactElement { - const { api, apiDefaultTx } = useContext(ApiContext); + const { api, apiDefaultTx } = useApiContext(); const defaultValue = ((): SubmittableExtrinsicFunction<'promise'> => { try { diff --git a/packages/react-components/src/Params/Proposal.tsx b/packages/react-components/src/Params/Proposal.tsx index 4e098295cc..5054d944e3 100644 --- a/packages/react-components/src/Params/Proposal.tsx +++ b/packages/react-components/src/Params/Proposal.tsx @@ -4,9 +4,9 @@ import { Props, RawParam } from '@polkadot/react-params/types'; -import React, { useContext } from 'react'; +import React from 'react'; import { createType } from '@polkadot/types'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import ExtrinsicDisplay from './Extrinsic'; @@ -26,7 +26,7 @@ function onChange ({ onChange }: Props): (_: RawParam) => void { } export default function ProposalDisplay (props: Props): React.ReactElement { - const { apiDefaultTxSudo } = useContext(ApiContext); + const { apiDefaultTxSudo } = useApiContext(); const { className, isDisabled, isError, label, onEnter, style, withLabel } = props; return ( diff --git a/packages/react-components/src/TreasuryProposal.tsx b/packages/react-components/src/TreasuryProposal.tsx index d917b2a619..0a36807d5b 100644 --- a/packages/react-components/src/TreasuryProposal.tsx +++ b/packages/react-components/src/TreasuryProposal.tsx @@ -5,9 +5,9 @@ import { TreasuryProposal as TreasuryProposalType } from '@polkadot/types/interfaces'; import { I18nProps } from '@polkadot/react-components/types'; -import React, { useContext, useEffect, useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { InputAddress, Labelled, Static } from '@polkadot/react-components'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import { Option } from '@polkadot/types'; import { FormatBalance } from '@polkadot/react-query'; @@ -26,7 +26,7 @@ interface Props extends I18nProps { function TreasuryProposal ({ className, asInset, insetProps, onClick, proposal, proposalId, t }: Props): React.ReactElement | null { const [stateProposal, setProposal] = useState(null); - const { api } = useContext(ApiContext); + const { api } = useApiContext(); useEffect((): void => { if (!proposal && proposalId) { diff --git a/packages/react-hooks/src/index.ts b/packages/react-hooks/src/index.ts index e42b45bc35..a9740861ea 100644 --- a/packages/react-hooks/src/index.ts +++ b/packages/react-hooks/src/index.ts @@ -1,7 +1,8 @@ -// Copyright 2017-2019 @polkadot/react-components authors & contributors +// Copyright 2017-2019 @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. -export { default as useDebounce } from './debounce'; -export { default as useFavorites } from './favorites'; -export { default as useSessionSlashes } from './sessionSlashes'; +export { default as useApiContext } from './useApiContext'; +export { default as useDebounce } from './useDebounce'; +export { default as useFavorites } from './useFavorites'; +export { default as useSessionRewards } from './useSessionRewards'; diff --git a/packages/react-hooks/src/useApiContext.tsx b/packages/react-hooks/src/useApiContext.tsx new file mode 100644 index 0000000000..7f131b9bab --- /dev/null +++ b/packages/react-hooks/src/useApiContext.tsx @@ -0,0 +1,12 @@ +// Copyright 2017-2019 @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 { ApiProps } from '@polkadot/react-api/types'; + +import { useContext } from 'react'; +import { ApiContext } from '@polkadot/react-api'; + +export default function useApiContext (): ApiProps { + return useContext(ApiContext); +} diff --git a/packages/react-hooks/src/useCacheKey.ts b/packages/react-hooks/src/useCacheKey.ts new file mode 100644 index 0000000000..ff36222728 --- /dev/null +++ b/packages/react-hooks/src/useCacheKey.ts @@ -0,0 +1,17 @@ +// Copyright 2017-2019 @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 store from 'store'; +import useApiContext from './useApiContext'; + +// create a chain-specific key for the local cache +export default function useCacheKey (storageKeyBase: string): [(defaultValue?: T) => T | undefined, (value: T) => T] { + const { api, isDevelopment } = useApiContext(); + const STORAGE_KEY = `${storageKeyBase}:${isDevelopment ? 'development' : api.genesisHash}`; + + return [ + (): T | undefined => store.get(STORAGE_KEY), + (value: T): T => store.set(STORAGE_KEY, value) + ]; +} diff --git a/packages/react-hooks/src/debounce.tsx b/packages/react-hooks/src/useDebounce.tsx similarity index 89% rename from packages/react-hooks/src/debounce.tsx rename to packages/react-hooks/src/useDebounce.tsx index cb48b4722d..ba5904f37d 100644 --- a/packages/react-hooks/src/debounce.tsx +++ b/packages/react-hooks/src/useDebounce.tsx @@ -1,4 +1,4 @@ -// Copyright 2017-2019 @polkadot/react-components authors & contributors +// Copyright 2017-2019 @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. diff --git a/packages/react-hooks/src/favorites.tsx b/packages/react-hooks/src/useFavorites.tsx similarity index 58% rename from packages/react-hooks/src/favorites.tsx rename to packages/react-hooks/src/useFavorites.tsx index cc74ff1cd2..df3de9ad9e 100644 --- a/packages/react-hooks/src/favorites.tsx +++ b/packages/react-hooks/src/useFavorites.tsx @@ -1,23 +1,22 @@ -// Copyright 2017-2019 @polkadot/react-components authors & contributors +// Copyright 2017-2019 @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 { useContext, useState } from 'react'; +import { useState } from 'react'; import store from 'store'; -import { ApiContext } from '@polkadot/react-api'; + +import useCacheKey from './useCacheKey'; // hook for favorites with local storage export default function useFavorites (storageKeyBase: string): [string[], (address: string) => void] { - const { api, isDevelopment } = useContext(ApiContext); - const keyName = `${storageKeyBase}:${isDevelopment ? 'development' : api.genesisHash}`; + const [getCache, setCache] = useCacheKey(storageKeyBase); // retrieve from the new style first, if not available, fallback to old-style - const [favorites, setFavorites] = useState(store.get(keyName) || store.get(storageKeyBase, [])); + const [favorites, setFavorites] = useState(getCache() || store.get(storageKeyBase, [])); const _toggleFavorite = (address: string): void => setFavorites( - store.set( - keyName, + setCache( favorites.includes(address) ? favorites.filter((accountId): boolean => address !== accountId) : [...favorites, address] diff --git a/packages/react-hooks/src/sessionSlashes.tsx b/packages/react-hooks/src/useSessionRewards.tsx similarity index 74% rename from packages/react-hooks/src/sessionSlashes.tsx rename to packages/react-hooks/src/useSessionRewards.tsx index ed422aabb3..571982e496 100644 --- a/packages/react-hooks/src/sessionSlashes.tsx +++ b/packages/react-hooks/src/useSessionRewards.tsx @@ -1,4 +1,4 @@ -// Copyright 2017-2019 @polkadot/react-components authors & contributors +// Copyright 2017-2019 @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. @@ -6,33 +6,29 @@ import { Balance, BlockNumber, EventRecord, Hash, Header } from '@polkadot/types import { Slash, SessionRewards } from './types'; import BN from 'bn.js'; -import { useContext, useEffect, useState } from 'react'; -import store from 'store'; +import { useEffect, useState } from 'react'; import { ApiPromise } from '@polkadot/api'; -import { ApiContext } from '@polkadot/react-api'; import { createType } from '@polkadot/types'; import { bnMax, u8aToU8a } from '@polkadot/util'; -interface SlashSer { +import useApiContext from './useApiContext'; +import useCacheKey from './useCacheKey'; + +interface SerializedSlash { accountId: string; amount: string; } -interface SessionResultSer { +interface Serialized { blockHash: string; blockNumber: string; isEventsEmpty: boolean; reward: string; sessionIndex: string; - slashes: SlashSer[]; + slashes: SerializedSlash[]; } -// assuming 4 hrs sessions, we grab results for 10 days -const MAX_SESSIONS = 10 * (24 / 4); - -function getStorage (storageKey: string): SessionRewards[] { - const sessions: SessionResultSer[] = store.get(storageKey, []); - +function fromJSON (sessions: Serialized[]): SessionRewards[] { return sessions.map(({ blockHash, blockNumber, isEventsEmpty, reward, sessionIndex, slashes }): SessionRewards => ({ blockHash: createType('Hash', blockHash), blockNumber: createType('BlockNumber', blockNumber), @@ -46,23 +42,18 @@ function getStorage (storageKey: string): SessionRewards[] { })); } -function setStorage (storageKey: string, sessions: SessionRewards[], maxSessions: number): SessionResultSer[] { - return store.set( - storageKey, - sessions - .map(({ blockHash, blockNumber, isEventsEmpty, reward, sessionIndex, slashes }): SessionResultSer => ({ - blockHash: blockHash.toHex(), - blockNumber: blockNumber.toHex(), - isEventsEmpty, - reward: reward.toHex(), - sessionIndex: sessionIndex.toHex(), - slashes: slashes.map(({ accountId, amount }): SlashSer => ({ - accountId: accountId.toString(), - amount: amount.toHex() - })) - })) - .slice(-maxSessions) - ); +function toJSON (sessions: SessionRewards[], maxSessions: number): Serialized[] { + return sessions.map(({ blockHash, blockNumber, isEventsEmpty, reward, sessionIndex, slashes }): Serialized => ({ + blockHash: blockHash.toHex(), + blockNumber: blockNumber.toHex(), + isEventsEmpty, + reward: reward.toHex(), + sessionIndex: sessionIndex.toHex(), + slashes: slashes.map(({ accountId, amount }): SerializedSlash => ({ + accountId: accountId.toString(), + amount: amount.toHex() + })) + })).slice(-maxSessions); } function mergeResults (sessions: SessionRewards[], newSessions: SessionRewards[]): SessionRewards[] { @@ -90,7 +81,7 @@ async function loadSome (api: ApiPromise, fromHash: Hash, toHash: Hash): Promise .then((records): EventRecord[] => records.filter(({ event: { section } }): boolean => section === 'staking') ) - .catch((): EventRecord[] => []) // undecodable may throw + .catch((): EventRecord[] => []) // may throw, update metadata for old ) ); const slashes: Slash[][] = events.map((info): Slash[] => @@ -117,10 +108,10 @@ async function loadSome (api: ApiPromise, fromHash: Hash, toHash: Hash): Promise })); } -export default function useSessionSlashes (maxSessions = MAX_SESSIONS): SessionRewards[] { - const { api } = useContext(ApiContext); - const STORAGE_KEY = `hooks:sessionSlashes:${api.genesisHash}`; - const [results, setResults] = useState(getStorage(STORAGE_KEY)); +export default function useSessionRewards (maxSessions: number): SessionRewards[] { + const { api } = useApiContext(); + const [getCache, setCache] = useCacheKey('hooks:sessionSlashes'); + const [results, setResults] = useState(fromJSON(getCache() || [])); const [filtered, setFiltered] = useState([]); useEffect((): void => { @@ -146,7 +137,7 @@ export default function useSessionSlashes (maxSessions = MAX_SESSIONS): SessionR toNumber = fromNumber; fromNumber = bnMax(toNumber.subn(count), new BN(1)); - setStorage(STORAGE_KEY, workQueue, maxSessionsStore); + setCache(toJSON(workQueue, maxSessionsStore)); setResults(workQueue); const lastNumber = workQueue[workQueue.length - 1]?.blockNumber; diff --git a/packages/react-query/src/BlockAuthors.tsx b/packages/react-query/src/BlockAuthors.tsx index e0c5babfb4..02acec95b0 100644 --- a/packages/react-query/src/BlockAuthors.tsx +++ b/packages/react-query/src/BlockAuthors.tsx @@ -2,9 +2,9 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import React, { useContext, useEffect, useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { HeaderExtended } from '@polkadot/api-derive'; -import { ApiContext } from '@polkadot/react-api'; +import { useApiContext } from '@polkadot/react-hooks'; import { formatNumber } from '@polkadot/util'; interface Authors { @@ -25,7 +25,7 @@ const byAuthor: Record = {}; const BlockAuthorsContext: React.Context = React.createContext({ byAuthor, lastHeaders: [] }); function BlockAuthors ({ children }: Props): React.ReactElement { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [state, setState] = useState({ byAuthor, lastHeaders: [] }); useEffect((): void => { diff --git a/packages/react-query/src/Chain.tsx b/packages/react-query/src/Chain.tsx index e36d270295..495e189da7 100644 --- a/packages/react-query/src/Chain.tsx +++ b/packages/react-query/src/Chain.tsx @@ -5,8 +5,8 @@ import { BareProps } from '@polkadot/react-api/types'; -import React, { useContext } from 'react'; -import { ApiContext } from '@polkadot/react-api'; +import React from 'react'; +import { useApiContext } from '@polkadot/react-hooks'; interface Props extends BareProps { children?: React.ReactNode; @@ -14,7 +14,7 @@ interface Props extends BareProps { } export default function Chain ({ children, className, label = '', style }: Props): React.ReactElement { - const { systemChain } = useContext(ApiContext); + const { systemChain } = useApiContext(); return (
= React.createContext([]); function Events ({ children }: Props): React.ReactElement { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [state, setState] = useState([]); useEffect((): void => { diff --git a/packages/react-query/src/NodeName.tsx b/packages/react-query/src/NodeName.tsx index d0e622d284..a44e3b942a 100644 --- a/packages/react-query/src/NodeName.tsx +++ b/packages/react-query/src/NodeName.tsx @@ -5,8 +5,8 @@ import { BareProps } from '@polkadot/react-api/types'; -import React, { useContext } from 'react'; -import { ApiContext } from '@polkadot/react-api'; +import React from 'react'; +import { useApiContext } from '@polkadot/react-hooks'; interface Props extends BareProps { children?: React.ReactNode; @@ -14,7 +14,7 @@ interface Props extends BareProps { } export default function NodeName ({ children, className, label = '', style }: Props): React.ReactElement { - const { systemName } = useContext(ApiContext); + const { systemName } = useApiContext(); return (
{ - const { systemVersion } = useContext(ApiContext); + const { systemVersion } = useApiContext(); return (
| null { - const { api } = useContext(ApiContext); + const { api } = useApiContext(); const [state, setState] = useState({ allFees: ZERO, allTotal: ZERO,