1
0
mirror of https://github.com/oceanprotocol/commons.git synced 2023-03-15 18:03:00 +01:00

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 React, { useState, useContext, useEffect } from 'react'
import { urlq } from '../../utils/utils' import { urlq } from '../../utils/utils'
import { import { CONNECTIONS } from '../../config'
aquariusUri,
brizoUri,
brizoAddress,
nodeUri,
secretStoreUri,
verbose,
CONNECTIONS
} from '../../config'
import { User } from '../../context' import { User } from '../../context'
const networkUrlParam = urlq.get('network') || '' const networkUrlParam = urlq.get('network') || ''
const defaultNetworkConfig = {
nodeUri,
aquariusUri,
brizoUri,
brizoAddress,
secretStoreUri,
verbose
}
const getNetworkConfig = (network: string) => { const getNetworkConfig = (network: string) => {
console.log(network)
const index = Object.keys(CONNECTIONS).indexOf(network) const index = Object.keys(CONNECTIONS).indexOf(network)
// TypeScript doesn't let access CONNECTIONS[networkName] directly // TypeScript doesn't let access CONNECTIONS[networkName] directly
return index !== -1 return index !== -1
? Object.values(CONNECTIONS)[index] ? 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 = export const oceanConfig =
networkUrlParam !== '' networkUrlParam !== ''
? getNetworkConfig(networkUrlParam) ? getNetworkConfig(networkUrlParam)
: defaultNetworkConfig : getNetworkConfig('pacific')
/* NETWORK SWITCHER */ /* NETWORK SWITCHER */
export function NetworkSwitcher() { 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(() => { useEffect(() => {
if (networkUrlParam !== '') { if (networkUrlParam !== '') {
switchNetwork(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 ( return (
<div> <div>
@ -66,7 +51,11 @@ export function NetworkSwitcher() {
: '' : ''
}} }}
> >
<span style={{ textTransform: 'capitalize' }}> <span
style={{
textTransform: 'capitalize'
}}
>
{networkName} {networkName}
</span> </span>
</li> </li>

View File

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

View File

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

View File

@ -25,22 +25,6 @@ export const ipfsNodeUri =
// //
// OCEAN REMOTE CONNECTIONS // 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 = { export const CONNECTIONS = {
pacific: { pacific: {
nodeUri: 'https://pacific.oceanprotocol.com', nodeUri: 'https://pacific.oceanprotocol.com',
@ -48,8 +32,7 @@ export const CONNECTIONS = {
brizoUri: 'https://brizo.commons.oceanprotocol.com', brizoUri: 'https://brizo.commons.oceanprotocol.com',
brizoAddress: '0x008c25ed3594e094db4592f4115d5fa74c4f41ea', brizoAddress: '0x008c25ed3594e094db4592f4115d5fa74c4f41ea',
secretStoreUri: 'https://secret-store.oceanprotocol.com', 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', nodeUri: 'https://nile.dev-ocean.com',
@ -57,8 +40,7 @@ export const CONNECTIONS = {
brizoUri: 'https://brizo.nile.dev-ocean.com', brizoUri: 'https://brizo.nile.dev-ocean.com',
brizoAddress: '0x4aaab179035dc57b35e2ce066919048686f82972', brizoAddress: '0x4aaab179035dc57b35e2ce066919048686f82972',
secretStoreUri: 'https://secret-store.nile.dev-ocean.com', 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', nodeUri: 'https://duero.dev-ocean.com',
@ -66,7 +48,6 @@ export const CONNECTIONS = {
brizoUri: 'https://brizo.duero.dev-ocean.com', brizoUri: 'https://brizo.duero.dev-ocean.com',
brizoAddress: '0x9d4ed58293f71122ad6a733c1603927a150735d0', brizoAddress: '0x9d4ed58293f71122ad6a733c1603927a150735d0',
secretStoreUri: 'https://secret-store.duero.dev-ocean.com', secretStoreUri: 'https://secret-store.duero.dev-ocean.com',
faucetUri: 'https://faucet.duero.dev-ocean.com', faucetUri: 'https://faucet.duero.dev-ocean.com'
verbose: true
} }
} }

View File

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

View File

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

View File

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

View File

@ -13,152 +13,153 @@ import Content from '../components/atoms/Content'
import withTracker from '../hoc/withTracker' import withTracker from '../hoc/withTracker'
interface SearchProps { interface SearchProps {
location: Location location: Location
history: History history: History
} }
interface SearchState { interface SearchState {
results: any[] results: any[]
totalResults: number totalResults: number
offset: number offset: number
totalPages: number totalPages: number
currentPage: number currentPage: number
isLoading: boolean isLoading: boolean
searchTerm: string searchTerm: string
searchCategories: string searchCategories: string
} }
class Search extends PureComponent<SearchProps, SearchState> { class Search extends PureComponent<SearchProps, SearchState> {
public static contextType = User public static contextType = User
public state = { public state = {
results: [], results: [],
totalResults: 0, totalResults: 0,
offset: 25, offset: 25,
totalPages: 1, totalPages: 1,
currentPage: 1, currentPage: 1,
isLoading: true, isLoading: true,
searchTerm: '', searchTerm: '',
searchCategories: '' searchCategories: ''
}
public async componentDidMount() {
const { search } = this.props.location
const { text, page, categories } = queryString.parse(search)
if (text) {
await this.setState({
searchTerm: decodeURIComponent(`${text}`)
})
} }
if (categories) { public async componentDidMount() {
await this.setState({ const { search } = this.props.location
searchCategories: decodeURIComponent(`${categories}`) 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 private searchAssets = async () => {
if (page) { const { ocean } = this.context
const currentPage = Number(page) const { offset, currentPage, searchTerm, searchCategories } = this.state
await this.setState({ currentPage })
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 () => { this.props.history.push({
const { ocean } = this.context pathname: this.props.location.pathname,
const { offset, currentPage, searchTerm, searchCategories } = this.state search: `?text=${this.state.searchTerm}&page=${toPage}`
})
const queryValues = await this.setState({ currentPage: toPage, isLoading: true })
searchCategories !== '' && searchTerm !== '' await this.searchAssets()
? { text: [searchTerm], categories: [searchCategories] }
: searchCategories !== '' && searchTerm === ''
? { categories: [searchCategories] }
: { text: [searchTerm] }
const searchQuery = {
offset,
page: currentPage,
query: {
...queryValues
},
sort: {
created: -1
}
} }
try { public renderResults = () =>
const search = await ocean.assets.query(searchQuery) this.state.isLoading ? (
this.setState({ <Spinner message="Searching..." />
results: search.results, ) : this.state.results && this.state.results.length ? (
totalResults: search.totalResults, <div className={styles.results}>
totalPages: search.totalPages, {this.state.results.map((asset: any) => (
isLoading: false <AssetTeaser key={asset.id} asset={asset} />
}) ))}
} catch (error) { </div>
Logger.error(error.message) ) : (
this.setState({ isLoading: false }) <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) export default withTracker(Search)