From 97ab54f4e9cd3e4abd0666579c0e68d92116c5ca Mon Sep 17 00:00:00 2001 From: Max Berman Date: Tue, 7 Jan 2020 16:34:35 +0100 Subject: [PATCH] switch network based on url param --- .../components/molecules/NetworkSwitcher.tsx | 67 ++++++-- client/src/config.ts | 12 +- client/src/context/MarketProvider.tsx | 144 +++++++++--------- client/src/context/UserProvider.tsx | 52 +++---- client/src/utils/utils.ts | 2 + 5 files changed, 154 insertions(+), 123 deletions(-) diff --git a/client/src/components/molecules/NetworkSwitcher.tsx b/client/src/components/molecules/NetworkSwitcher.tsx index 8e44d92..9cfbfe9 100644 --- a/client/src/components/molecules/NetworkSwitcher.tsx +++ b/client/src/components/molecules/NetworkSwitcher.tsx @@ -1,30 +1,73 @@ -import React, { useState, useContext } from 'react' -import { CONNECTIONS } from '../../config' +import React, { useState, useContext, useEffect } from 'react' +import { urlq } from '../../utils/utils' +import { + aquariusUri, + brizoUri, + brizoAddress, + nodeUri, + secretStoreUri, + verbose, + CONNECTIONS +} from '../../config' import { User } from '../../context' +const networkUrlParam = urlq.get('network') || '' +const defaultNetworkConfig = { + nodeUri, + aquariusUri, + brizoUri, + brizoAddress, + secretStoreUri, + verbose +} + +const getNetworkConfig = (network: string) => { + console.log(network) + const index = Object.keys(CONNECTIONS).indexOf(network) + // TypeScript doesn't let access CONNECTIONS[networkName] directly + return index !== -1 + ? Object.values(CONNECTIONS)[index] + : CONNECTIONS.pacific // Use defaul config in case of mispelled URL params or +} + +export const oceanConfig = + networkUrlParam !== '' + ? getNetworkConfig(networkUrlParam) + : defaultNetworkConfig + /* NETWORK SWITCHER */ - -const urlParams = new URLSearchParams(window.location.search) -const networkFromParam = urlParams.get('network') || 'pacific' - -// console.log(Object.keys(CONNECTIONS)) - export function NetworkSwitcher() { const userContext = useContext(User) + const switchNetwork = (networkName: string): any => { const idx = Object.keys(CONNECTIONS).indexOf(networkName) - userContext.switchNetwork(networkName, Object.values(CONNECTIONS)[idx]) // TypeScript won't let me access CONNECTIONS[networkName] directly + userContext.switchNetwork(networkName, getNetworkConfig(networkName)) } + + useEffect(() => { + if (networkUrlParam !== '') { + switchNetwork(networkUrlParam) + } + }, []) + return (
- {userContext.network} + + {userContext.network} +
) } diff --git a/client/src/config.ts b/client/src/config.ts index b68241d..5bdcae2 100644 --- a/client/src/config.ts +++ b/client/src/config.ts @@ -42,31 +42,31 @@ export const faucetUri = process.env.REACT_APP_FAUCET_URI || 'https://faucet.oceanprotocol.com' export const CONNECTIONS = { - Pacific: { + pacific: { nodeUri: 'https://pacific.oceanprotocol.com', aquariusUri: 'https://aquarius.commons.oceanprotocol.com', brizoUri: 'https://brizo.commons.oceanprotocol.com', brizoAddress: '0x008c25ed3594e094db4592f4115d5fa74c4f41ea', secretStoreUri: 'https://secret-store.oceanprotocol.com', - //faucetUri: 'https://faucet.oceanprotocol.com', + faucetUri: 'https://faucet.oceanprotocol.com', verbose: true }, - Nile: { + nile: { nodeUri: 'https://nile.dev-ocean.com', aquariusUri: 'https://aquarius.nile.dev-ocean.com', brizoUri: 'https://brizo.nile.dev-ocean.com', brizoAddress: '0x4aaab179035dc57b35e2ce066919048686f82972', secretStoreUri: 'https://secret-store.nile.dev-ocean.com', - //faucetUri: 'https://faucet.nile.dev-ocean.com', + faucetUri: 'https://faucet.nile.dev-ocean.com', verbose: true }, - Duero: { + duero: { nodeUri: 'https://duero.dev-ocean.com', aquariusUri: 'https://aquarius.duero.dev-ocean.com', brizoUri: 'https://brizo.duero.dev-ocean.com', brizoAddress: '0x9d4ed58293f71122ad6a733c1603927a150735d0', secretStoreUri: 'https://secret-store.duero.dev-ocean.com', - //faucetUri: 'https://faucet.duero.dev-ocean.com', + faucetUri: 'https://faucet.duero.dev-ocean.com', verbose: true } } diff --git a/client/src/context/MarketProvider.tsx b/client/src/context/MarketProvider.tsx index 416e32c..e7f581b 100644 --- a/client/src/context/MarketProvider.tsx +++ b/client/src/context/MarketProvider.tsx @@ -4,94 +4,94 @@ import { Market, User } from '.' import formPublish from '../data/form-publish.json' const categories = - (formPublish.steps[1].fields && - formPublish.steps[1].fields.categories && - formPublish.steps[1].fields.categories.options) || - [] + (formPublish.steps[1].fields && + formPublish.steps[1].fields.categories && + formPublish.steps[1].fields.categories.options) || + [] interface MarketProviderProps { - ocean: Ocean + ocean: Ocean } interface MarketProviderState { - totalAssets: number - categories: string[] - network: string - networkMatch: boolean + totalAssets: number + categories: string[] + network: string + networkMatch: boolean } export default class MarketProvider extends PureComponent< - MarketProviderProps, - MarketProviderState + MarketProviderProps, + MarketProviderState > { - public static contextType = User + public static contextType = User - public state = { - totalAssets: 0, - categories, - network: 'Pacific', - networkMatch: false - } - - public async componentDidMount() { - await this.checkCorrectUserNetwork() - } - - public async componentDidUpdate(prevProps: any) { - // Using ocean prop instead of getting it from context to be able to compare. - // Cause there is no `prevContext`. - if (prevProps.ocean !== this.props.ocean) { - await this.getTotalAssets() - await this.getMarketNetwork() - await this.checkCorrectUserNetwork() - } - } - - private getTotalAssets = async () => { - const searchQuery = { - offset: 1, - page: 1, - query: {}, - sort: { - value: 1 - } + public state = { + totalAssets: 0, + categories, + network: 'Pacific', + networkMatch: false } - try { - const { ocean } = this.props - const search = await ocean.assets.query(searchQuery) - this.setState({ totalAssets: search.totalResults }) - } catch (error) { - Logger.error('Error', error.message) + public async componentDidMount() { + await this.checkCorrectUserNetwork() } - } - private getMarketNetwork = async () => { - try { - const { ocean } = this.props - // Set desired network to whatever Brizo is running in - const brizo = await ocean.brizo.getVersionInfo() - const network = - brizo.network.charAt(0).toUpperCase() + brizo.network.slice(1) - this.setState({ network }) - } catch (error) { - Logger.error('Error', error.message) + public async componentDidUpdate(prevProps: any) { + // Using ocean prop instead of getting it from context to be able to compare. + // Cause there is no `prevContext`. + if (prevProps.ocean !== this.props.ocean) { + await this.getTotalAssets() + await this.getMarketNetwork() + await this.checkCorrectUserNetwork() + } } - } - private async checkCorrectUserNetwork() { - if (this.context.network === this.state.network) { - this.setState({ networkMatch: true }) - } else { - this.setState({ networkMatch: false }) + private getTotalAssets = async () => { + const searchQuery = { + offset: 1, + page: 1, + query: {}, + sort: { + value: 1 + } + } + + try { + const { ocean } = this.props + const search = await ocean.assets.query(searchQuery) + this.setState({ totalAssets: search.totalResults }) + } catch (error) { + Logger.error('Error', error.message) + } } - } - public render() { - return ( - - {this.props.children} - - ) - } + private getMarketNetwork = async () => { + try { + const { ocean } = this.props + // Set desired network to whatever Brizo is running in + const brizo = await ocean.brizo.getVersionInfo() + const network = + brizo.network.charAt(0).toUpperCase() + brizo.network.slice(1) + this.setState({ network }) + } catch (error) { + Logger.error('Error', error.message) + } + } + + private async checkCorrectUserNetwork() { + if (this.context.network === this.state.network) { + this.setState({ networkMatch: true }) + } else { + this.setState({ networkMatch: false }) + } + } + + public render() { + return ( + + {this.props.children} + + ) + } } diff --git a/client/src/context/UserProvider.tsx b/client/src/context/UserProvider.tsx index 87cb881..07df85e 100644 --- a/client/src/context/UserProvider.tsx +++ b/client/src/context/UserProvider.tsx @@ -6,30 +6,20 @@ import { provideOcean, requestFromFaucet, FaucetResponse } from '../ocean' import MarketProvider from './MarketProvider' import { MetamaskProvider } from './MetamaskProvider' import { BurnerWalletProvider } from './BurnerWalletProvider' -import { NetworkSwitcher } from '../components/molecules/NetworkSwitcher' - +import { urlq } from '../utils/utils' import { - aquariusUri, - brizoUri, - brizoAddress, - nodeUri, - secretStoreUri, - verbose, - CONNECTIONS -} from '../config' + NetworkSwitcher, + oceanConfig +} from '../components/molecules/NetworkSwitcher' -const oceanConfig = { - nodeUri, - aquariusUri, - brizoUri, - brizoAddress, - secretStoreUri, - verbose -} +console.log({ oceanConfig }) + +const { nodeUri } = oceanConfig const POLL_ACCOUNTS = 1000 // every 1s const POLL_NETWORK = POLL_ACCOUNTS * 60 // every 1 min const DEFAULT_WEB3 = new Web3(new Web3.providers.HttpProvider(nodeUri)) // default web3 +const networkUrlParam = urlq.get('network') || '' interface UserProviderState { isLogged: boolean @@ -77,7 +67,11 @@ export default class UserProvider extends PureComponent<{}, UserProviderState> { message: 'Connecting to Ocean...' } - private switchNetwork = (network: string, config: Config) => { + public async componentDidMount() { + await this.bootstrap() + } + + private switchNetwork = async (network: string, config: Config) => { console.log({ network, config, oceanConfig }) const nodeUrl: any = config.nodeUri this.setState( @@ -85,11 +79,12 @@ export default class UserProvider extends PureComponent<{}, UserProviderState> { network, web3: new Web3(new Web3.providers.HttpProvider(nodeUrl)) }, - () => + () => { this.loadOcean({ web3Provider: this.state.web3, ...config }) + } ) } @@ -114,7 +109,6 @@ export default class UserProvider extends PureComponent<{}, UserProviderState> { } private loginBurnerWallet = async () => { - console.log('loginMetamask') const burnerwalletProvider = new BurnerWalletProvider() await burnerwalletProvider.startLogin() const web3 = burnerwalletProvider.getProvider() @@ -124,7 +118,8 @@ export default class UserProvider extends PureComponent<{}, UserProviderState> { isBurner: true, web3 }, - () => { + async () => { + await this.switchNetwork(networkUrlParam, oceanConfig) this.loadOcean({ web3Provider: this.state.web3, ...oceanConfig @@ -142,10 +137,6 @@ export default class UserProvider extends PureComponent<{}, UserProviderState> { private networkInterval: any = null - public async componentDidMount() { - await this.bootstrap() - } - private initAccountsPoll() { if (!this.accountsInterval) { this.accountsInterval = setInterval( @@ -162,7 +153,6 @@ export default class UserProvider extends PureComponent<{}, UserProviderState> { } private loadDefaultWeb3 = async () => { - console.log('loadDefaultWeb3') this.setState( { isLogged: false, @@ -179,7 +169,6 @@ export default class UserProvider extends PureComponent<{}, UserProviderState> { } private loadOcean = async (config: Config) => { - console.log('load ocean', config) const { ocean } = await provideOcean({ web3Provider: this.state.web3, ...config @@ -196,8 +185,6 @@ export default class UserProvider extends PureComponent<{}, UserProviderState> { const logType = localStorage.getItem('logType') const metamaskProvider = new MetamaskProvider() - console.log('BOOTSTRAP', { logType }) - switch (logType) { case 'Metamask': if ( @@ -280,17 +267,16 @@ export default class UserProvider extends PureComponent<{}, UserProviderState> { private fetchNetwork = async () => { const { ocean } = this.state - console.log('1 this.state.network', this.state.network) let network = 'Unknown' if (ocean.keeper) { network = await ocean.keeper.getNetworkName() } - network !== this.state.network && this.setState({ network }) - console.log('2 this.state.network', this.state.network) + console.log(await ocean.keeper.getNetworkName()) } public render() { + //console.log(this.state.network) return ( diff --git a/client/src/utils/utils.ts b/client/src/utils/utils.ts index 928dc93..e67ce3a 100644 --- a/client/src/utils/utils.ts +++ b/client/src/utils/utils.ts @@ -11,6 +11,8 @@ export function formatBytes(a: number, b: number) { return parseFloat((a / Math.pow(c, f)).toFixed(d)) + ' ' + e[f] } +export const urlq = new URLSearchParams(window.location.search) + export function arraySum(array: number[]) { return array.reduce((a, b) => a + b, 0) }