reload window upon network switch

This commit is contained in:
Max Berman 2020-01-09 18:40:42 +01:00
parent f853c880c5
commit 5e954f187a
8 changed files with 277 additions and 317 deletions

View File

@ -1,54 +1,39 @@
import React, { useState, useContext, useEffect } from 'react'
import { urlq } from '../../utils/utils'
import {
aquariusUri,
brizoUri,
brizoAddress,
nodeUri,
secretStoreUri,
verbose,
CONNECTIONS
} from '../../config'
import { 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
: CONNECTIONS.pacific // Use default config in case of mispelled URL params or
}
export const oceanConfig =
networkUrlParam !== ''
? getNetworkConfig(networkUrlParam)
: defaultNetworkConfig
: getNetworkConfig('pacific')
/* NETWORK SWITCHER */
export function NetworkSwitcher() {
const userContext = useContext(User)
const switchNetwork = (networkName: string): any => {
const idx = Object.keys(CONNECTIONS).indexOf(networkName)
userContext.switchNetwork(networkName, getNetworkConfig(networkName))
}
/*
useEffect(() => {
if (networkUrlParam !== '') {
switchNetwork(networkUrlParam)
}
}, [])
}, [])
*/
const userContext = useContext(User)
const switchNetwork = (networkName: string): any =>
// Force page to get refreshed
(window.location.href = `${window.location.origin}?network=${networkName}`)
//userContext.switchNetwork(networkName, getNetworkConfig(networkName))
return (
<div>
@ -66,7 +51,11 @@ export function NetworkSwitcher() {
: ''
}}
>
<span style={{ textTransform: 'capitalize' }}>
<span
style={{
textTransform: 'capitalize'
}}
>
{networkName}
</span>
</li>

View File

@ -5,107 +5,99 @@ import styles from './VersionTable.module.scss'
import VersionNumber from './VersionNumber'
import { useParams } from 'react-router-dom'
import {
serviceUri,
nodeUri,
aquariusUri,
brizoUri,
brizoAddress,
secretStoreUri,
faucetUri,
CONNECTIONS
} from '../../../config'
// const commonsConfig = {
// serviceUri,
// nodeUri,
// aquariusUri,
// brizoUri,
// brizoAddress,
// secretStoreUri,
// faucetUri
// }
const commonsConfig = {
serviceUri,
nodeUri,
aquariusUri,
brizoUri,
brizoAddress,
secretStoreUri,
faucetUri
}
import { NetworkSwitcher, oceanConfig } from '../../molecules/NetworkSwitcher'
export const VersionTableContracts = ({
contracts,
network,
keeperVersion
contracts,
network,
keeperVersion
}: {
contracts: {
[contractName: string]: string
}
network: string
keeperVersion?: string
contracts: { [contractName: string]: string }
network: string
keeperVersion?: string
}) => (
<table>
<tbody>
<tr>
<td>
<strong>Keeper Contracts</strong>
</td>
<td>
<VersionNumber name="Keeper Contracts" version={keeperVersion} />
</td>
</tr>
{contracts &&
Object.keys(contracts)
// sort alphabetically
.sort((a, b) => a.localeCompare(b))
.map(key => {
const submarineLink = `https://submarine.${
network === 'pacific' ? 'oceanprotocol' : `${network}.dev-ocean`
}.com/address/${contracts[key]}`
<table>
<tbody>
<tr>
<td>
<strong>Keeper Contracts</strong>
</td>
<td>
<VersionNumber
name="Keeper Contracts"
version={keeperVersion}
/>
</td>
</tr>
{contracts &&
Object.keys(contracts)
// sort alphabetically
.sort((a, b) => a.localeCompare(b))
.map(key => {
const submarineLink = `https://submarine.${
network === 'pacific'
? 'oceanprotocol'
: `${network}.dev-ocean`
}.com/address/${contracts[key]}`
return (
<tr key={key}>
<td>
<code className={styles.label}>{key}</code>
</td>
<td>
<a href={submarineLink}>
<code>{contracts[key]}</code>
</a>
</td>
</tr>
)
})}
</tbody>
</table>
return (
<tr key={key}>
<td>
<code className={styles.label}>{key}</code>
</td>
<td>
<a href={submarineLink}>
<code>{contracts[key]}</code>
</a>
</td>
</tr>
)
})}
</tbody>
</table>
)
export const VersionTableCommons = () => (
<table>
<tbody>
{Object.entries(commonsConfig).map(([key, value]) => (
<tr key={key}>
<td>
<code className={styles.label}>{key}</code>
</td>
<td>
<code>{value}</code>
</td>
</tr>
))}
</tbody>
</table>
<table>
<tbody>
{Object.entries(oceanConfig).map(([key, value]) => (
<tr key={key}>
<td>
<code className={styles.label}>{key}</code>
</td>
<td>
<code>{value}</code>
</td>
</tr>
))}
</tbody>
</table>
)
const VersionTable = ({ data }: { data: VersionNumbersState }) => {
return (
<div className={styles.tableWrap}>
<table className={styles.table}>
<tbody>
{Object.entries(data)
.filter(([key]) => key !== 'status')
.map(([key, value]) => (
<VersionTableRow key={key} value={value} />
))}
</tbody>
</table>
</div>
)
return (
<div className={styles.tableWrap}>
<table className={styles.table}>
<tbody>
{Object.entries(data)
.filter(([key]) => key !== 'status')
.map(([key, value]) => (
<VersionTableRow key={key} value={value} />
))}
</tbody>
</table>
</div>
)
}
export default VersionTable

View File

@ -8,12 +8,17 @@ import axios from 'axios'
import { version } from '../../../../package.json'
import styles from './index.module.scss'
import { nodeUri, faucetUri } from '../../../config'
//import { nodeUri, faucetUri } from '../../../config'
import { oceanConfig } from '../../molecules/NetworkSwitcher'
import { User, Market } from '../../../context'
import VersionTable from './VersionTable'
import VersionStatus from './VersionStatus'
const { nodeUri, faucetUri } = oceanConfig
interface VersionNumbersProps {
minimal?: boolean
account: string
@ -91,8 +96,8 @@ export default class VersionNumbers extends PureComponent<
// Workaround: Using account prop instead of getting it from
// context to be able to compare. Cause there is no `prevContext`.
if (prevProps.account !== this.props.account) {
this.getOceanVersions()
this.getFaucetVersion()
await this.getOceanVersions()
await this.getFaucetVersion()
}
}

View File

@ -25,22 +25,6 @@ export const ipfsNodeUri =
//
// OCEAN REMOTE CONNECTIONS
//
export const nodeUri =
process.env.REACT_APP_NODE_URI || 'https://pacific.oceanprotocol.com'
export const aquariusUri =
process.env.REACT_APP_AQUARIUS_URI ||
'https://aquarius.commons.oceanprotocol.com'
export const brizoUri =
process.env.REACT_APP_BRIZO_URI || 'https://brizo.commons.oceanprotocol.com'
export const brizoAddress =
process.env.REACT_APP_BRIZO_ADDRESS ||
'0x008c25ed3594e094db4592f4115d5fa74c4f41ea'
export const secretStoreUri =
process.env.REACT_APP_SECRET_STORE_URI ||
'https://secret-store.oceanprotocol.com'
export const faucetUri =
process.env.REACT_APP_FAUCET_URI || 'https://faucet.oceanprotocol.com'
export const CONNECTIONS = {
pacific: {
nodeUri: 'https://pacific.oceanprotocol.com',
@ -48,8 +32,7 @@ export const CONNECTIONS = {
brizoUri: 'https://brizo.commons.oceanprotocol.com',
brizoAddress: '0x008c25ed3594e094db4592f4115d5fa74c4f41ea',
secretStoreUri: 'https://secret-store.oceanprotocol.com',
faucetUri: 'https://faucet.oceanprotocol.com',
verbose: true
faucetUri: 'https://faucet.oceanprotocol.com'
},
nile: {
nodeUri: 'https://nile.dev-ocean.com',
@ -57,8 +40,7 @@ export const CONNECTIONS = {
brizoUri: 'https://brizo.nile.dev-ocean.com',
brizoAddress: '0x4aaab179035dc57b35e2ce066919048686f82972',
secretStoreUri: 'https://secret-store.nile.dev-ocean.com',
faucetUri: 'https://faucet.nile.dev-ocean.com',
verbose: true
faucetUri: 'https://faucet.nile.dev-ocean.com'
},
duero: {
nodeUri: 'https://duero.dev-ocean.com',
@ -66,7 +48,6 @@ export const CONNECTIONS = {
brizoUri: 'https://brizo.duero.dev-ocean.com',
brizoAddress: '0x9d4ed58293f71122ad6a733c1603927a150735d0',
secretStoreUri: 'https://secret-store.duero.dev-ocean.com',
faucetUri: 'https://faucet.duero.dev-ocean.com',
verbose: true
faucetUri: 'https://faucet.duero.dev-ocean.com'
}
}

View File

@ -1,10 +1,11 @@
import Web3 from 'web3'
import HDWalletProvider from '@truffle/hdwallet-provider'
import { nodeUri } from '../config'
import { oceanConfig } from '../components/molecules/NetworkSwitcher'
import { requestFromFaucet } from '../ocean'
// eslint-disable-next-line @typescript-eslint/no-var-requires
const bip39 = require('bip39')
const { nodeUri } = oceanConfig
export class BurnerWalletProvider {
private web3: Web3
@ -30,9 +31,9 @@ export class BurnerWalletProvider {
} else {
mnemonic = bip39.generateMnemonic()
localStorage.setItem('seedphrase', mnemonic)
localStorage.setItem('logType', 'BurnerWallet')
}
localStorage.setItem('logType', 'BurnerWallet')
const provider = new HDWalletProvider(mnemonic, nodeUri, 0, 1)
this.web3 = new Web3(provider as any)
const accounts = await this.web3.eth.getAccounts()

View File

@ -12,17 +12,15 @@ import {
oceanConfig
} from '../components/molecules/NetworkSwitcher'
console.log({ oceanConfig })
const { nodeUri } = oceanConfig
console.log(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') || ''
console.log({ nodeUri })
interface UserProviderState {
isLogged: boolean
isBurner: boolean
@ -74,20 +72,12 @@ export default class UserProvider extends PureComponent<{}, UserProviderState> {
}
private switchNetwork = async (network: string, config: Config) => {
console.log({ network, config, oceanConfig })
const nodeUrl: any = config.nodeUri
this.setState(
{
network,
web3: new Web3(new Web3.providers.HttpProvider(nodeUrl))
},
() => {
this.loadOcean({
web3Provider: this.state.web3,
...config
})
}
)
this.setState({ network }, async () => {
this.loadOcean({
web3Provider: this.state.web3,
...config
})
})
}
private loginMetamask = async () => {
@ -221,7 +211,6 @@ export default class UserProvider extends PureComponent<{}, UserProviderState> {
private fetchAccounts = async () => {
const { ocean, isLogged } = this.state
if (isLogged) {
let accounts
@ -237,9 +226,10 @@ export default class UserProvider extends PureComponent<{}, UserProviderState> {
accounts = await ocean.accounts.list()
//console.log('fetch', accounts)
if (accounts.length > 0) {
const account = await accounts[0].getId()
if (account !== this.state.account) {
this.setState({
account,
@ -278,7 +268,7 @@ export default class UserProvider extends PureComponent<{}, UserProviderState> {
}
public render() {
//console.log(this.state.network)
// console.log(this.state.network)
return (
<User.Provider value={this.state}>
<MarketProvider ocean={this.state.ocean}>

View File

@ -1,36 +1,37 @@
import { Ocean, Logger, Config } from '@oceanprotocol/squid'
import { faucetUri } from './config'
import { oceanConfig } from './components/molecules/NetworkSwitcher'
const { faucetUri } = oceanConfig
export async function provideOcean(config: Config) {
const ocean: Ocean = await Ocean.getInstance(config)
return { ocean }
const ocean: Ocean = await Ocean.getInstance(config)
return { ocean }
}
//
// Faucet
//
export interface FaucetResponse {
success: boolean
message: string
trxHash?: string
success: boolean
message: string
trxHash?: string
}
export async function requestFromFaucet(account: string) {
try {
const url = `${faucetUri}/faucet`
const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
address: account,
agent: 'commons'
})
})
return response.json()
} catch (error) {
Logger.error('requestFromFaucet', error.message)
}
try {
const url = `${faucetUri}/faucet`
const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
address: account,
agent: 'commons'
})
})
return response.json()
} catch (error) {
Logger.error('requestFromFaucet', error.message)
}
}

View File

@ -13,152 +13,153 @@ import Content from '../components/atoms/Content'
import withTracker from '../hoc/withTracker'
interface SearchProps {
location: Location
history: History
location: Location
history: History
}
interface SearchState {
results: any[]
totalResults: number
offset: number
totalPages: number
currentPage: number
isLoading: boolean
searchTerm: string
searchCategories: string
results: any[]
totalResults: number
offset: number
totalPages: number
currentPage: number
isLoading: boolean
searchTerm: string
searchCategories: string
}
class Search extends PureComponent<SearchProps, SearchState> {
public static contextType = User
public static contextType = User
public state = {
results: [],
totalResults: 0,
offset: 25,
totalPages: 1,
currentPage: 1,
isLoading: true,
searchTerm: '',
searchCategories: ''
}
public async componentDidMount() {
const { search } = this.props.location
const { text, page, categories } = queryString.parse(search)
if (text) {
await this.setState({
searchTerm: decodeURIComponent(`${text}`)
})
public state = {
results: [],
totalResults: 0,
offset: 25,
totalPages: 1,
currentPage: 1,
isLoading: true,
searchTerm: '',
searchCategories: ''
}
if (categories) {
await this.setState({
searchCategories: decodeURIComponent(`${categories}`)
})
public async componentDidMount() {
const { search } = this.props.location
const { text, page, categories } = queryString.parse(search)
if (text) {
this.setState({
searchTerm: decodeURIComponent(`${text}`)
})
}
if (categories) {
this.setState({
searchCategories: decodeURIComponent(`${categories}`)
})
}
// switch to respective page if query string is present
if (page) {
const currentPage = Number(page)
this.setState({ currentPage })
}
this.searchAssets()
}
// switch to respective page if query string is present
if (page) {
const currentPage = Number(page)
await this.setState({ currentPage })
private searchAssets = async () => {
const { ocean } = this.context
const { offset, currentPage, searchTerm, searchCategories } = this.state
const queryValues =
searchCategories !== '' && searchTerm !== ''
? { text: [searchTerm], categories: [searchCategories] }
: searchCategories !== '' && searchTerm === ''
? { categories: [searchCategories] }
: { text: [searchTerm] }
const searchQuery = {
offset,
page: currentPage,
query: {
...queryValues
},
sort: {
created: -1
}
}
try {
const search = await ocean.assets.query(searchQuery)
this.setState({
results: search.results,
totalResults: search.totalResults,
totalPages: search.totalPages,
isLoading: false
})
} catch (error) {
Logger.error(error.message)
this.setState({ isLoading: false })
}
}
this.searchAssets()
}
private handlePageClick = async (data: { selected: number }) => {
// react-pagination starts counting at 0, we start at 1
const toPage = data.selected + 1
private searchAssets = async () => {
const { ocean } = this.context
const { offset, currentPage, searchTerm, searchCategories } = this.state
this.props.history.push({
pathname: this.props.location.pathname,
search: `?text=${this.state.searchTerm}&page=${toPage}`
})
const queryValues =
searchCategories !== '' && searchTerm !== ''
? { text: [searchTerm], categories: [searchCategories] }
: searchCategories !== '' && searchTerm === ''
? { categories: [searchCategories] }
: { text: [searchTerm] }
const searchQuery = {
offset,
page: currentPage,
query: {
...queryValues
},
sort: {
created: -1
}
await this.setState({ currentPage: toPage, isLoading: true })
await this.searchAssets()
}
try {
const search = await ocean.assets.query(searchQuery)
this.setState({
results: search.results,
totalResults: search.totalResults,
totalPages: search.totalPages,
isLoading: false
})
} catch (error) {
Logger.error(error.message)
this.setState({ isLoading: false })
public renderResults = () =>
this.state.isLoading ? (
<Spinner message="Searching..." />
) : this.state.results && this.state.results.length ? (
<div className={styles.results}>
{this.state.results.map((asset: any) => (
<AssetTeaser key={asset.id} asset={asset} />
))}
</div>
) : (
<div className={styles.empty}>
<p>No Data Sets Found.</p>
<Link to="/publish">+ Publish A Data Set</Link>
</div>
)
public render() {
const { totalResults, totalPages, currentPage } = this.state
return (
<Route title="Search" wide>
<Content wide>
{!this.state.isLoading && (
<h2 className={styles.resultsTitle}>
{totalResults} results for{' '}
<span>
{decodeURIComponent(
this.state.searchTerm ||
this.state.searchCategories
)}
</span>
</h2>
)}
{this.renderResults()}
<Pagination
totalPages={totalPages}
currentPage={currentPage}
handlePageClick={this.handlePageClick}
/>
</Content>
</Route>
)
}
}
private handlePageClick = async (data: { selected: number }) => {
// react-pagination starts counting at 0, we start at 1
const toPage = data.selected + 1
this.props.history.push({
pathname: this.props.location.pathname,
search: `?text=${this.state.searchTerm}&page=${toPage}`
})
await this.setState({ currentPage: toPage, isLoading: true })
await this.searchAssets()
}
public renderResults = () =>
this.state.isLoading ? (
<Spinner message="Searching..." />
) : this.state.results && this.state.results.length ? (
<div className={styles.results}>
{this.state.results.map((asset: any) => (
<AssetTeaser key={asset.id} asset={asset} />
))}
</div>
) : (
<div className={styles.empty}>
<p>No Data Sets Found.</p>
<Link to="/publish">+ Publish A Data Set</Link>
</div>
)
public render() {
const { totalResults, totalPages, currentPage } = this.state
return (
<Route title="Search" wide>
<Content wide>
{!this.state.isLoading && (
<h2 className={styles.resultsTitle}>
{totalResults} results for{' '}
<span>
{decodeURIComponent(
this.state.searchTerm || this.state.searchCategories
)}
</span>
</h2>
)}
{this.renderResults()}
<Pagination
totalPages={totalPages}
currentPage={currentPage}
handlePageClick={this.handlePageClick}
/>
</Content>
</Route>
)
}
}
export default withTracker(Search)