Skip to content

Commit

Permalink
Do manual health check on rpcs instead of relying on getDefaultBrowse…
Browse files Browse the repository at this point in the history
…r for more reliable rpc connections
  • Loading branch information
sophialittlejohn committed Aug 27, 2024
1 parent dd9ae1f commit ae84511
Show file tree
Hide file tree
Showing 16 changed files with 46 additions and 41 deletions.
1 change: 1 addition & 0 deletions centrifuge-app/.env-config/.env.altair
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ REACT_APP_WALLETCONNECT_ID=c32fa79350803519804a67fcab0b742a
REACT_APP_TINLAKE_SUBGRAPH_URL=https://api.goldsky.com/api/public/project_clhi43ef5g4rw49zwftsvd2ks/subgraphs/main/prod/gn
REACT_APP_TREASURY=kAJkmGxAd6iqX9JjWTdhXgCf2PL1TAphTRYrmEqzBrYhwbXAn
REACT_APP_PRIME_IPFS_HASH=QmQfcuHM3EGrtpjhitDwJsgie5THLPtRNzvk7N3uymgHGc
REACT_APP_ONFINALITY_KEY=18704429-288d-4f55-bda8-8b60f4c53b96
3 changes: 2 additions & 1 deletion centrifuge-app/.env-config/.env.catalyst
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ REACT_APP_MEMBERLIST_ADMIN_PURE_PROXY=4bo2vNkwZtr2PuqppWwqya6dPC8MzxqZ4kgnAoTZyK
REACT_APP_WALLETCONNECT_ID=c32fa79350803519804a67fcab0b742a
REACT_APP_TINLAKE_SUBGRAPH_URL=https://api.goldsky.com/api/public/project_clhi43ef5g4rw49zwftsvd2ks/subgraphs/main/prod/gn
REACT_APP_TREASURY=kAJkmGxAd6iqX9JjWTdhXgCf2PL1TAphTRYrmEqzBrYhwbXAn
REACT_APP_PRIME_IPFS_HASH=QmQfcuHM3EGrtpjhitDwJsgie5THLPtRNzvk7N3uymgHGc
REACT_APP_PRIME_IPFS_HASH=QmQfcuHM3EGrtpjhitDwJsgie5THLPtRNzvk7N3uymgHGc
REACT_APP_ONFINALITY_KEY=18704429-288d-4f55-bda8-8b60f4c53b96
1 change: 1 addition & 0 deletions centrifuge-app/.env-config/.env.demo
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ REACT_APP_WALLETCONNECT_ID=c32fa79350803519804a67fcab0b742a
REACT_APP_TINLAKE_SUBGRAPH_URL=https://api.goldsky.com/api/public/project_clhi43ef5g4rw49zwftsvd2ks/subgraphs/main/prod/gn
REACT_APP_TREASURY=kAJkmGxAd6iqX9JjWTdhXgCf2PL1TAphTRYrmEqzBrYhwbXAn
REACT_APP_PRIME_IPFS_HASH=QmQfcuHM3EGrtpjhitDwJsgie5THLPtRNzvk7N3uymgHGc
REACT_APP_ONFINALITY_KEY=0e1c049f-d876-4e77-a45f-b5afdf5739b2
1 change: 1 addition & 0 deletions centrifuge-app/.env-config/.env.development
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ REACT_APP_WALLETCONNECT_ID=c32fa79350803519804a67fcab0b742a
REACT_APP_TINLAKE_SUBGRAPH_URL=https://api.goldsky.com/api/public/project_clhi43ef5g4rw49zwftsvd2ks/subgraphs/main/prod/gn
REACT_APP_TREASURY=kAJkmGxAd6iqX9JjWTdhXgCf2PL1TAphTRYrmEqzBrYhwbXAn
REACT_APP_PRIME_IPFS_HASH=QmQfcuHM3EGrtpjhitDwJsgie5THLPtRNzvk7N3uymgHGc
REACT_APP_ONFINALITY_KEY=0e1c049f-d876-4e77-a45f-b5afdf5739b2
1 change: 1 addition & 0 deletions centrifuge-app/.env-config/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ REACT_APP_WALLETCONNECT_ID=c32fa79350803519804a67fcab0b742a
REACT_APP_TINLAKE_SUBGRAPH_URL=https://api.goldsky.com/api/public/project_clhi43ef5g4rw49zwftsvd2ks/subgraphs/main/prod/gn
REACT_APP_TREASURY=kAJkmGxAd6iqX9JjWTdhXgCf2PL1TAphTRYrmEqzBrYhwbXAn
REACT_APP_PRIME_IPFS_HASH=QmQfcuHM3EGrtpjhitDwJsgie5THLPtRNzvk7N3uymgHGc
REACT_APP_ONFINALITY_KEY=0e1c049f-d876-4e77-a45f-b5afdf5739b2
3 changes: 2 additions & 1 deletion centrifuge-app/.env-config/.env.ff-prod
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ REACT_APP_MEMBERLIST_ADMIN_PURE_PROXY=kALJqPUHFzDR2VkoQYWefPQyzjGzKznNny2smXGQpS
REACT_APP_WALLETCONNECT_ID=c32fa79350803519804a67fcab0b742a
REACT_APP_TINLAKE_SUBGRAPH_URL=https://api.goldsky.com/api/public/project_clhi43ef5g4rw49zwftsvd2ks/subgraphs/main/prod/gn
REACT_APP_TREASURY=4dpEcgqJRyJK3J8Es6v8ZfVntV7c64Ysgcjd4hYwyGoFPWbg
REACT_APP_PRIME_IPFS_HASH=QmS5gX2sk1ZCEyWnMjjmQyYkLTz27VVNGzVtCKWneABbj5
REACT_APP_PRIME_IPFS_HASH=QmS5gX2sk1ZCEyWnMjjmQyYkLTz27VVNGzVtCKWneABbj5
REACT_APP_ONFINALITY_KEY=18704429-288d-4f55-bda8-8b60f4c53b96
3 changes: 2 additions & 1 deletion centrifuge-app/.env-config/.env.production
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ REACT_APP_MEMBERLIST_ADMIN_PURE_PROXY=kALJqPUHFzDR2VkoQYWefPQyzjGzKznNny2smXGQpS
REACT_APP_WALLETCONNECT_ID=c32fa79350803519804a67fcab0b742a
REACT_APP_TINLAKE_SUBGRAPH_URL=https://api.goldsky.com/api/public/project_clhi43ef5g4rw49zwftsvd2ks/subgraphs/main/prod/gn
REACT_APP_TREASURY=4dpEcgqJRyJK3J8Es6v8ZfVntV7c64Ysgcjd4hYwyGoFPWbg
REACT_APP_PRIME_IPFS_HASH=QmS5gX2sk1ZCEyWnMjjmQyYkLTz27VVNGzVtCKWneABbj5
REACT_APP_PRIME_IPFS_HASH=QmS5gX2sk1ZCEyWnMjjmQyYkLTz27VVNGzVtCKWneABbj5
REACT_APP_ONFINALITY_KEY=84bb59f4-05cc-440b-8fd4-7917623a90c6
1 change: 1 addition & 0 deletions centrifuge-app/declarations.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ interface ImportMetaEnv {
REACT_APP_ALCHEMY_KEY: string
REACT_APP_WALLETCONNECT_ID: string
REACT_APP_PRIME_IPFS_HASH: string
REACT_APP_ONFINALITY_KEY: string
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export function InvestRedeemLiquidityPoolsProvider({ poolId, trancheId, children
const tranche = pool.tranches.find((t) => t.id === trancheId)
const { data: metadata, isLoading: isMetadataLoading } = usePoolMetadata(pool)
const trancheMeta = metadata?.tranches?.[trancheId]
const chainId = provider?.network.chainId || 1
const chainId = Number(provider?._network.chainId) || 1

if (!tranche) throw new Error(`Token not found. Pool id: ${poolId}, token id: ${trancheId}`)

Expand Down Expand Up @@ -228,12 +228,13 @@ export function InvestRedeemLiquidityPoolsProvider({ poolId, trancheId, children
// If the last tx was an approve, we may not have refetched the allowance yet,
// so assume the allowance is enough to do a normal invest
else if (lpInvest.lpCurrencyAllowance.lt(assets) && supportsPermits && pendingAction !== 'approvePoolCurrency') {
const signer = provider!.getSigner()
const signer = await provider!.getSigner()
const connectedCent = cent.connectEvm(evmAddress!, signer)
const permit = await connectedCent.liquidityPools.signPermit([
lpInvest.lpAddress,
lpInvest.currency.address,
assets,
chainId,
])
console.log('permit', permit)
// investWithPermit.execute([lpInvest.lpAddress, assets, permit])
Expand Down
2 changes: 1 addition & 1 deletion centrifuge-app/src/components/PoolOverview/KeyMetrics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ const AvailableNetworks = ({ poolId }: { poolId: string }) => {
<Spinner size="iconSmall" />
)}
{activeDomains.data
?.filter((domain) => domain.isActive)
?.filter((domain) => domain.isActive && domain.chainId !== 5)
.map((domain) => {
const chain = (evmChains as any)[domain.chainId]
return (
Expand Down
2 changes: 0 additions & 2 deletions centrifuge-app/src/components/Root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,6 @@ export function Root() {
showAdvancedAccounts={debugState.showAdvancedAccounts}
showTestNets={debugState.showTestNets}
showFinoa={debugState.showFinoa}
alchemyKey={import.meta.env.REACT_APP_ALCHEMY_KEY}
infuraKey={import.meta.env.REACT_APP_INFURA_KEY}
>
<SupportedBrowserBanner />
<OnboardingAuthProvider>
Expand Down
12 changes: 9 additions & 3 deletions centrifuge-app/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ const CENTRIFUGE: EnvironmentConfig = {
const ethNetwork = import.meta.env.REACT_APP_TINLAKE_NETWORK || 'mainnet'

const alchemyKey = import.meta.env.REACT_APP_ALCHEMY_KEY

const onfinalityKey = import.meta.env.REACT_APP_ONFINALITY_KEY
export const ethConfig = {
rpcUrl: `https://eth-mainnet.g.alchemy.com/v2/${alchemyKey}`,
chainId: 1,
Expand Down Expand Up @@ -156,15 +156,21 @@ export const evmChains: EvmChains = {
decimals: 18,
},
blockExplorerUrl: 'https://etherscan.io/',
urls: [`https://eth-mainnet.g.alchemy.com/v2/${alchemyKey}`],
urls: [
`https://eth-mainnet.g.alchemy.com/v2/${alchemyKey}`,
`https://eth.api.onfinality.io/rpc?apikey=${onfinalityKey}`,
],
iconUrl: ethereumLogo,
isTestnet: false,
},
11155111: {
name: 'Ethereum Sepolia',
nativeCurrency: { name: 'Sepolia Ether', symbol: 'sepETH', decimals: 18 },
blockExplorerUrl: 'https://sepolia.etherscan.io/',
urls: [`https://eth-sepolia.g.alchemy.com/v2/${alchemyKey}`],
urls: [
`https://eth-sepolia.g.alchemy.com/v2/${alchemyKey}`,
`https://eth-sepolia.api.onfinality.io/rpc?apikey=${onfinalityKey}`,
],
iconUrl: sepoliaLogo,
isTestnet: true,
},
Expand Down
2 changes: 1 addition & 1 deletion centrifuge-app/src/utils/tinlake/useEvmTransaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export function useEvmTransaction<T extends Array<any>>(

async function doTransaction(id: string, args: T, txOptions?: TransactionRequest) {
try {
const signer = provider!.getSigner()
const signer = await provider!.getSigner()
const connectedCent = centrifuge.connectEvm(selectedAddress!, signer)
const transaction = transactionCallback(connectedCent)
updateTransaction(id, { status: 'unconfirmed' })
Expand Down
4 changes: 2 additions & 2 deletions centrifuge-js/src/modules/liquidityPools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ export function getLiquidityPoolsModule(inst: Centrifuge) {
const currencyData = await multicall<{
currencies: { currencySupportsPermit?: boolean }[]
trancheTokenSymbol: string
trancheTokenDecimals: number
trancheTokenDecimals: BigInt
}>(
[
...Object.values(currenciesByLpAddress).flatMap(
Expand Down Expand Up @@ -521,7 +521,7 @@ export function getLiquidityPoolsModule(inst: Centrifuge) {
managerAddress,
trancheTokenAddress: shareData.share,
trancheTokenSymbol: currencyData.trancheTokenSymbol,
trancheTokenDecimals: currencyData.trancheTokenDecimals,
trancheTokenDecimals: Number(currencyData.trancheTokenDecimals),
currencySupportsPermit: currencyData.currencies?.[i]?.currencySupportsPermit,
}))
return result
Expand Down
40 changes: 17 additions & 23 deletions centrifuge-react/src/components/WalletProvider/WalletProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { getWallets } from '@subwallet/wallet-connect/dotsama/wallets'
import { Wallet } from '@subwallet/wallet-connect/types'
import { Web3ReactState } from '@web3-react/types'
import { WalletConnect as WalletConnectV2 } from '@web3-react/walletconnect-v2'
import { getDefaultProvider, JsonRpcProvider, Networkish, Provider } from 'ethers'
import { JsonRpcProvider, Provider } from 'ethers'
import * as React from 'react'
import { useQuery } from 'react-query'
import { firstValueFrom, map, switchMap } from 'rxjs'
Expand Down Expand Up @@ -129,12 +129,10 @@ type WalletProviderProps = {
showAdvancedAccounts?: boolean
showTestNets?: boolean
showFinoa?: boolean
alchemyKey?: string
infuraKey?: string
}

let cachedEvmConnectors: EvmConnectorMeta[] | undefined = undefined
const cachedProviders = new Map<Networkish, Provider>()
const cachedProviders = new Map<number, JsonRpcProvider>()

export function WalletProvider({
children,
Expand All @@ -150,8 +148,6 @@ export function WalletProvider({
showAdvancedAccounts,
showTestNets,
showFinoa,
alchemyKey,
infuraKey,
}: WalletProviderProps) {
if (!evmChainsProp[1]?.urls[0]) throw new Error('Mainnet should be defined in EVM Chains')

Expand Down Expand Up @@ -244,28 +240,26 @@ export function WalletProvider({

const [proxies] = useCentrifugeQuery(['allProxies'], (cent) => cent.proxies.getAllProxies())

function getProvider(networkish: Networkish) {
let network = networkish
const cachedProvider = cachedProviders.get(network)
if (cachedProvider) {
return cachedProvider
} else {
async function findHealthyProvider(chainId: number, urls: string[]): Promise<JsonRpcProvider> {
for (const url of urls) {
try {
const provider = getDefaultProvider(network, {
alchemy: alchemyKey,
infura: infuraKey,
})
cachedProviders.set(network, provider)
const provider = new JsonRpcProvider(url, chainId)
await provider.getBlockNumber()
cachedProviders.set(chainId, provider)
return provider
} catch (error) {
if (typeof network === 'number') {
const provider = new JsonRpcProvider((evmChains as any)[network].urls[0], network)
cachedProviders.set(network, provider)
return provider
}
throw error
console.error(`Provider health check failed for ${url}:`, error)
}
}
throw new Error(`No healthy provider found for chain ${chainId}`)
}

function getProvider(chainId: number): JsonRpcProvider {
const urls = (evmChains as any)[chainId].urls
if (!cachedProviders.has(chainId)) {
findHealthyProvider(chainId, urls).catch(console.error)
}
return cachedProviders.get(chainId) || new JsonRpcProvider(urls[0], chainId)
}

function setFilteredAccounts(accounts: SubstrateAccount[]) {
Expand Down
6 changes: 2 additions & 4 deletions centrifuge-react/src/components/WalletProvider/evm/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { createWeb3ReactStoreAndActions } from '@web3-react/store'
import { Actions, Provider as Web3ReactProvider, Web3ReactState, Web3ReactStore } from '@web3-react/types'
import { WalletConnect as WalletConnectV2 } from '@web3-react/walletconnect-v2'
import type { Networkish } from 'ethers'
import { BrowserProvider } from 'ethers'
import * as React from 'react'
import { useQuery } from 'react-query'
import { useWallet } from '../WalletProvider'
Expand Down Expand Up @@ -49,10 +50,7 @@ function getProviderKey(connector: Connector) {
return providerKey
}

export function useProviderForConnector<T extends Web3ReactProvider = Web3ReactProvider>(
connector?: Connector | null,
network?: Networkish
) {
export function useProviderForConnector<T extends BrowserProvider>(connector?: Connector | null, network?: Networkish) {
const conn = connector ?? emptyConnector
const state = useConnectorState(conn)
const isActive = computeIsActive(state)
Expand Down

0 comments on commit ae84511

Please sign in to comment.