Skip to content

Commit

Permalink
Refactor api context and fix network switching issue (#309)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tbaut authored Aug 18, 2023
1 parent fa07f5c commit 008478f
Show file tree
Hide file tree
Showing 17 changed files with 64 additions and 83 deletions.
8 changes: 2 additions & 6 deletions packages/ui/src/components/AccountDisplay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const AccountDisplay = ({
const { balanceFormatted } = useGetBalance({ address })
const localName = useMemo(() => getNamesWithExtension(address), [address, getNamesWithExtension])
const [identity, setIdentity] = useState<DeriveAccountRegistration | null>(null)
const { api, isApiReady, chainInfo } = useApi()
const { api, chainInfo } = useApi()
const [mainDisplay, setMainDisplay] = useState<string>('')
const [sub, setSub] = useState<string | null>(null)
const [encodedAddress, setEncodedAddress] = useState('')
Expand All @@ -54,10 +54,6 @@ const AccountDisplay = ({
return
}

if (!isApiReady) {
return
}

let unsubscribe: () => void

api.derive.accounts
Expand All @@ -83,7 +79,7 @@ const AccountDisplay = ({
.catch((e) => console.error(e))

return () => unsubscribe && unsubscribe()
}, [address, api, isApiReady])
}, [address, api])

return (
<div className={className}>
Expand Down
6 changes: 3 additions & 3 deletions packages/ui/src/components/EasySetup/BalancesTransfer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ interface Props {
const BalancesTransfer = ({ className, onSetExtrinsic, onSetErrorMessage, from }: Props) => {
const accountBase = useAccountBaseFromAccountList()
const [selected, setSelected] = useState<AccountBaseInfo | undefined>()
const { api, isApiReady, chainInfo } = useApi()
const { api, chainInfo } = useApi()
const [amountString, setAmountString] = useState('')
const [amount, setAmount] = useState<BN | undefined>()
const [amountError, setAmountError] = useState('')
Expand All @@ -42,7 +42,7 @@ const BalancesTransfer = ({ className, onSetExtrinsic, onSetErrorMessage, from }
}, [amount, amountError, hasEnoughFreeBalance, onSetErrorMessage])

useEffect(() => {
if (!isApiReady || !api) {
if (!api) {
onSetExtrinsic(undefined)
return
}
Expand All @@ -53,7 +53,7 @@ const BalancesTransfer = ({ className, onSetExtrinsic, onSetErrorMessage, from }
}

onSetExtrinsic(api.tx.balances.transferKeepAlive(toAddress, amount.toString()))
}, [amount, api, chainInfo, isApiReady, onSetExtrinsic, toAddress])
}, [amount, api, chainInfo, onSetExtrinsic, toAddress])

const onAddressDestChange = useCallback((account: AccountBaseInfo) => {
setSelected(account)
Expand Down
10 changes: 5 additions & 5 deletions packages/ui/src/components/EasySetup/FromCallData.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ interface Props {
}

const FromCallData = ({ className, onSetExtrinsic, isProxySelected, onSetErrorMessage }: Props) => {
const { api, isApiReady } = useApi()
const { api } = useApi()
const [pastedCallData, setPastedCallData] = useState<HexString | undefined>(undefined)
const [callDataError, setCallDataError] = useState('')
const [isProxyProxyRemoved, setIsProxyProxyRemoved] = useState(false)

const removeProxyProxyCall = useCallback(
(call: HexString) => {
setIsProxyProxyRemoved(false)
if (!api || !isApiReady) return call
if (!api) return call

if (!isProxySelected) return call

Expand All @@ -46,7 +46,7 @@ const FromCallData = ({ className, onSetExtrinsic, isProxySelected, onSetErrorMe
setIsProxyProxyRemoved(true)
return `0x${call.substring(74)}` as HexString
},
[api, isApiReady, isProxySelected]
[api, isProxySelected]
)

// users may erroneously paste callData from the multisig calldata
Expand All @@ -61,7 +61,7 @@ const FromCallData = ({ className, onSetExtrinsic, isProxySelected, onSetErrorMe
const { extrinsicUrl } = usePjsLinks()

useEffect(() => {
if (!isApiReady || !api) {
if (!api) {
return
}

Expand All @@ -70,7 +70,7 @@ const FromCallData = ({ className, onSetExtrinsic, isProxySelected, onSetErrorMe
}

onSetExtrinsic(api.tx(callInfo.call))
}, [api, pastedCallData, callInfo, isApiReady, onSetExtrinsic])
}, [api, pastedCallData, callInfo, onSetExtrinsic])

const onCallDataChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
setCallDataError('')
Expand Down
5 changes: 2 additions & 3 deletions packages/ui/src/components/EasySetup/ManualExtrinsic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ const ManualExtrinsic = ({
extrinsicIndex,
onSelectFromCallData
}: Props) => {
const { api, isApiReady } = useApi()
const { api } = useApi()
const [palletRPCs, setPalletRPCs] = useState<any[]>([])
const [callables, setCallables] = useState<any[]>([])
const [paramFields, setParamFields] = useState<ParamField[] | null>(null)
Expand Down Expand Up @@ -247,7 +247,7 @@ const ManualExtrinsic = ({
)

useEffect(() => {
if (!isApiReady || !api) {
if (!api) {
return
}

Expand All @@ -271,7 +271,6 @@ const ManualExtrinsic = ({
api,
areAllParamsFilled,
callable,
isApiReady,
extrinsicIndex,
onSetErrorMessage,
onSetExtrinsic,
Expand Down
6 changes: 3 additions & 3 deletions packages/ui/src/components/Transactions/TransactionList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -146,11 +146,11 @@ const TransactionList = ({ className }: Props) => {
isLoading: isLoadingPendingTxs,
refresh
} = usePendingTx(selectedMultiProxy)
const { api, isApiReady } = useApi()
const { api } = useApi()
const { ownAddressList } = useAccounts()

useEffect(() => {
if (!isApiReady || !api) {
if (!api) {
return
}

Expand Down Expand Up @@ -179,7 +179,7 @@ const TransactionList = ({ className }: Props) => {
setAggregatedData(timestampObj)
})
.catch(console.error)
}, [api, pendingTxData, isApiReady, selectedMultiProxy])
}, [api, pendingTxData, selectedMultiProxy])

return (
<Box className={className}>
Expand Down
14 changes: 5 additions & 9 deletions packages/ui/src/components/modals/ChangeMultisig.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ type Step = 'selection' | 'summary' | 'call1' | 'call2'
const ChangeMultisig = ({ onClose, className }: Props) => {
const { getSubscanExtrinsicLink } = useGetSubscanLinks()
const modalRef = useRef<HTMLDivElement | null>(null)
const { isApiReady, api, chainInfo } = useApi()
const { api, chainInfo } = useApi()
const { selectedMultiProxy, getMultisigAsAccountBaseInfo, getMultisigByAddress } = useMultiProxy()
const { addToast } = useToasts()
const signCallBack2 = useSigningCallback({
Expand Down Expand Up @@ -90,7 +90,7 @@ const ChangeMultisig = ({ onClose, className }: Props) => {
const [callError, setCallError] = useState('')

const firstCall = useMemo(() => {
if (!isApiReady || !api) {
if (!api) {
// console.error('api is not ready')
return
}
Expand Down Expand Up @@ -133,7 +133,6 @@ const ChangeMultisig = ({ onClose, className }: Props) => {
}, [
api,
chainInfo,
isApiReady,
newMultisigAddress,
newThreshold,
oldThreshold,
Expand All @@ -143,7 +142,7 @@ const ChangeMultisig = ({ onClose, className }: Props) => {
])

const secondCall = useMemo(() => {
if (!isApiReady || !api) {
if (!api) {
// console.error('api is not ready')
return
}
Expand Down Expand Up @@ -180,7 +179,6 @@ const ChangeMultisig = ({ onClose, className }: Props) => {
}, [
api,
chainInfo,
isApiReady,
newSignatories,
newThreshold,
selectedAccount,
Expand Down Expand Up @@ -248,7 +246,7 @@ const ChangeMultisig = ({ onClose, className }: Props) => {
return
}

if (!isApiReady || !api) {
if (!api) {
console.error('api is not ready')
return
}
Expand Down Expand Up @@ -276,7 +274,6 @@ const ChangeMultisig = ({ onClose, className }: Props) => {
})
}, [
callError,
isApiReady,
api,
selectedAccount,
secondCall,
Expand All @@ -294,7 +291,7 @@ const ChangeMultisig = ({ onClose, className }: Props) => {

// first we add the new multisig as an any proxy of the pure proxy, signed by the old multisig
const onFirstCall = useCallback(async () => {
if (!isApiReady || !api) {
if (!api) {
console.error('api is not ready')
return
}
Expand All @@ -321,7 +318,6 @@ const ChangeMultisig = ({ onClose, className }: Props) => {
onErrorCallback(error.message)
})
}, [
isApiReady,
api,
selectedAccount,
firstCall,
Expand Down
5 changes: 2 additions & 3 deletions packages/ui/src/components/modals/ProposalSigning.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const ProposalSigning = ({
onSuccess
}: Props) => {
const { getSubscanExtrinsicLink } = useGetSubscanLinks()
const { api, isApiReady } = useApi()
const { api } = useApi()
const [isSubmitting, setIsSubmitting] = useState(false)
const { getMultisigByAddress } = useMultiProxy()
const { selectedAccount, selectedSigner } = useAccounts()
Expand Down Expand Up @@ -112,7 +112,7 @@ const ProposalSigning = ({
return
}

if (!isApiReady || !api) {
if (!api) {
const error = 'Api is not ready'
console.error(error)
setErrorMessage(error)
Expand Down Expand Up @@ -212,7 +212,6 @@ const ProposalSigning = ({
signatories,
threshold,
proposalData,
isApiReady,
api,
selectedAccount,
multisig,
Expand Down
8 changes: 3 additions & 5 deletions packages/ui/src/components/modals/Send.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ interface Props {

const Send = ({ onClose, className, onSuccess, onFinalized }: Props) => {
const { getSubscanExtrinsicLink } = useGetSubscanLinks()
const { api, isApiReady, chainInfo } = useApi()
const { api, chainInfo } = useApi()
const [isSubmitting, setIsSubmitting] = useState(false)
const { selectedMultiProxy, getMultisigAsAccountBaseInfo, getMultisigByAddress } = useMultiProxy()
const { selectedAccount, selectedSigner } = useAccounts()
Expand Down Expand Up @@ -82,7 +82,7 @@ const Send = ({ onClose, className, onSuccess, onFinalized }: Props) => {
return
}

if (!isApiReady || !api) {
if (!api) {
return
}

Expand Down Expand Up @@ -116,7 +116,6 @@ const Send = ({ onClose, className, onSuccess, onFinalized }: Props) => {
}, [
api,
extrinsicToCall,
isApiReady,
isProxySelected,
selectedAccount,
selectedMultisig,
Expand Down Expand Up @@ -215,7 +214,7 @@ const Send = ({ onClose, className, onSuccess, onFinalized }: Props) => {
return
}

if (!isApiReady || !api) {
if (!api) {
const error = 'Api is not ready'
console.error(error)
setErrorMessage(error)
Expand Down Expand Up @@ -254,7 +253,6 @@ const Send = ({ onClose, className, onSuccess, onFinalized }: Props) => {
})
}, [
threshold,
isApiReady,
api,
selectedAccount,
selectedOrigin,
Expand Down
29 changes: 15 additions & 14 deletions packages/ui/src/contexts/ApiContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ type ApiContextProps = {
const registry = new TypeRegistry()

export interface IApiContext {
api?: ApiPromise
isApiReady: boolean
api?: false | ApiPromise
chainInfo?: ChainInfoHuman
}

Expand All @@ -34,40 +33,43 @@ const ApiContext = createContext<IApiContext | undefined>(undefined)

const ApiContextProvider = ({ children, types }: ApiContextProps) => {
const { selectedNetworkInfo } = useNetwork()
const [chainInfo, setChainInfo] = useState<ChainInfoHuman | undefined>()
const [apiPromise, setApiPromise] = useState<ApiPromise | undefined>()
const [isApiReady, setIsApiReady] = useState(false)
const provider = useMemo(
() => !!selectedNetworkInfo?.rpcUrl && new WsProvider(selectedNetworkInfo?.rpcUrl),
[selectedNetworkInfo]
)
const [chainInfo, setChainInfo] = useState<ChainInfoHuman | undefined>()
const [apiPromise, setApiPromise] = useState<ApiPromise | undefined>()
const [isReady, setIsReady] = useState(false)

useEffect(() => {
if (!provider) return

// console.log('---> connecting to', provider.endpoint)
setApiPromise(new ApiPromise({ provider, types }))
setIsApiReady(false)
const api = new ApiPromise({ provider, types })
api.isReady.then((newApi) => setApiPromise(newApi)).catch(console.error)

return () => {
setIsReady(false)
// console.log('<---disconnecting')
!!apiPromise && apiPromise.disconnect()
setIsApiReady(false)
!!api && api.disconnect()
setApiPromise(undefined)
}

// prevent an infinite loop
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [provider, types])

useEffect(() => {
if (!apiPromise || !provider || isReady) return
if (!apiPromise || !provider) return

apiPromise.isReady
.then((api) => {
setIsApiReady(true)
if (types) {
registry.register(types)
}

setIsReady(true)
const info = api.registry.getChainProperties()
const raw = info?.toHuman() as unknown as RawChainInfoHuman

Expand All @@ -78,14 +80,13 @@ const ApiContextProvider = ({ children, types }: ApiContextProps) => {
tokenSymbol: raw?.tokenSymbol[0] || ''
})
})
.catch((e) => console.error(e))
}, [apiPromise, isReady, provider, types])
.catch(console.error)
}, [apiPromise, provider, types])

return (
<ApiContext.Provider
value={{
api: apiPromise,
isApiReady: isReady,
api: isApiReady && apiPromise,
chainInfo
}}
>
Expand Down
Loading

0 comments on commit 008478f

Please sign in to comment.