1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-11-14 17:24:51 +01:00

chainId switching mechanism

This commit is contained in:
Matthias Kretschmann 2021-06-09 11:45:36 +02:00
parent f0b040c5cb
commit ef218a9d9e
Signed by: m
GPG Key ID: 606EEEF3C479A91F
12 changed files with 112 additions and 112 deletions

View File

@ -3,9 +3,12 @@ module.exports = {
process.env.METADATACACHE_URI || process.env.METADATACACHE_URI ||
'https://aquarius.mainnet.oceanprotocol.com', 'https://aquarius.mainnet.oceanprotocol.com',
// List of supported chainIds which metadata cache queries // List of chainIds which metadata cache queries will return by default.
// will return by default // This preselects the Chains user preferences.
chainIds: [1, 3, 4, 137, 1287], chainIds: [1, 137],
// List of all supported chainIds. Used to populate the Chains user preferences list.
chainIdsSupported: [1, 3, 4, 137, 1287],
infuraProjectId: process.env.GATSBY_INFURA_PROJECT_ID || 'xxx', infuraProjectId: process.env.GATSBY_INFURA_PROJECT_ID || 'xxx',

View File

@ -9,6 +9,6 @@
display: inline-block; display: inline-block;
width: 1.2em; width: 1.2em;
height: 1.2em; height: 1.2em;
fill: var(--color-secondary); fill: currentColor;
margin-right: calc(var(--spacer) / 12); margin-right: calc(var(--spacer) / 8);
} }

View File

@ -1,30 +1,37 @@
.buttons { .chains {
composes: buttons from './Appearance.module.css'; composes: box from '../../atoms/Box.module.css';
box-shadow: none;
padding: 0;
} }
.button { .radioWrap {
composes: button from './Appearance.module.css'; composes: radioWrap from '../../atoms/Input/InputElement.module.css';
padding: calc(var(--spacer) / 6) calc(var(--spacer) / 3);
border-bottom: 1px solid var(--border-color);
} }
.button span { .radioWrap:last-child {
display: block; border-bottom: none;
font-size: var(--font-size-small); }
font-family: var(--font-family-base);
.input {
composes: checkbox from '../../atoms/Input/InputElement.module.css';
vertical-align: baseline;
margin-right: calc(var(--spacer) / 3);
margin-top: 0;
}
.radioLabel {
composes: radioLabel from '../../atoms/Input/InputElement.module.css';
font-weight: var(--font-weight-base); font-weight: var(--font-weight-base);
margin-top: calc(var(--spacer) / 10); display: flex;
align-items: center;
margin: 0;
padding: 0;
width: 100%;
} }
.selected { .input:checked + span {
composes: selected from './Appearance.module.css'; color: var(--font-color-text);
} font-weight: var(--font-weight-bold);
.chains div[class*='boxSelectionsWrapper'] {
display: grid;
gap: calc(var(--spacer) / 4);
grid-template-columns: repeat(auto-fit, minmax(6rem, 1fr));
padding-bottom: calc(var(--spacer) / 8);
}
.chains label[class*='boxSelection'] {
padding: calc(var(--spacer) / 3) calc(var(--spacer) / 4) !important;
} }

View File

@ -1,59 +1,50 @@
import { ConfigHelperConfig } from '@oceanprotocol/lib' import React, { ChangeEvent, ReactElement } from 'react'
import React, { ReactElement, ChangeEvent } from 'react'
import { useOcean } from '../../../providers/Ocean'
import { getOceanConfig } from '../../../utils/ocean'
import FormHelp from '../../atoms/Input/Help'
import Label from '../../atoms/Input/Label' import Label from '../../atoms/Input/Label'
import BoxSelection, { BoxSelectionOption } from '../FormFields/BoxSelection' import { useUserPreferences } from '../../../providers/UserPreferences'
import { ReactComponent as EthIcon } from '../../../images/eth.svg' import { useSiteMetadata } from '../../../hooks/useSiteMetadata'
import { ReactComponent as PolygonIcon } from '../../../images/polygon.svg' import NetworkName from '../../atoms/NetworkName'
import { ReactComponent as MoonbeamIcon } from '../../../images/moonbeam.svg' import { removeItemFromArray } from '../../../utils'
import FormHelp from '../../atoms/Input/Help'
import styles from './Chain.module.css' import styles from './Chain.module.css'
export default function Chain(): ReactElement { export default function Chain(): ReactElement {
const { config, connect } = useOcean() const { appConfig } = useSiteMetadata()
const { chainIds, setChainIds } = useUserPreferences()
async function connectOcean(event: ChangeEvent<HTMLInputElement>) { function handleChainChanged(e: ChangeEvent<HTMLInputElement>) {
const config = getOceanConfig(event.target.value) const { value } = e.target
await connect(config)
// storing all chainId everywhere as a number so convert from here
const valueAsNumber = Number(value)
const newChainIds = chainIds.includes(valueAsNumber)
? [...removeItemFromArray(chainIds, valueAsNumber)]
: [...chainIds, valueAsNumber]
setChainIds(newChainIds)
} }
function isNetworkSelected(oceanConfig: string) {
return (config as ConfigHelperConfig).network === oceanConfig
}
const options: BoxSelectionOption[] = [
{
name: 'mainnet',
checked: isNetworkSelected('mainnet'),
title: 'ETH',
text: 'Mainnet',
icon: <EthIcon />
},
{
name: 'polygon',
checked: isNetworkSelected('polygon'),
title: 'Polygon',
text: 'Mainnet',
icon: <PolygonIcon />
},
{
name: 'moonbeamalpha',
checked: isNetworkSelected('moonbeamalpha'),
title: 'Moonbase Alpha',
text: 'Testnet',
icon: <MoonbeamIcon />
}
]
return ( return (
<li className={styles.chains}> <li>
<Label htmlFor="">Chain</Label> <Label htmlFor="chains">Chains</Label>
<BoxSelection <div className={styles.chains}>
options={options} {appConfig.chainIdsSupported.map((chainId) => (
name="chain" <div className={styles.radioWrap} key={chainId}>
handleChange={connectOcean} <label className={styles.radioLabel} htmlFor={`opt-${chainId}`}>
/> <input
className={styles.input}
id={`opt-${chainId}`}
type="checkbox"
name="chainIds"
value={chainId}
onChange={handleChainChanged}
defaultChecked={chainIds.includes(chainId)}
/>
<NetworkName key={chainId} networkId={chainId} />
</label>
</div>
))}
</div>
<FormHelp>Switch the data source for the interface.</FormHelp> <FormHelp>Switch the data source for the interface.</FormHelp>
</li> </li>
) )

View File

@ -1,23 +1,21 @@
import React, { ReactElement } from 'react' import React, { ReactElement } from 'react'
import { useUserPreferences } from '../../../providers/UserPreferences' import { useUserPreferences } from '../../../providers/UserPreferences'
import FormHelp from '../../atoms/Input/Help' import Input from '../../atoms/Input'
import InputElement from '../../atoms/Input/InputElement'
export default function Debug(): ReactElement { export default function Debug(): ReactElement {
const { debug, setDebug } = useUserPreferences() const { debug, setDebug } = useUserPreferences()
return ( return (
<li> <li>
<InputElement <Input
label="Debug"
help="Show geeky information in some places, and in your console."
name="debug" name="debug"
type="checkbox" type="checkbox"
options={['Debug Mode']} options={['Activate Debug Mode']}
defaultChecked={debug === true} defaultChecked={debug === true}
onChange={() => setDebug(!debug)} onChange={() => setDebug(!debug)}
/> />
<FormHelp>
Show geeky information in some places, and in your console.
</FormHelp>
</li> </li>
) )
} }

View File

@ -40,16 +40,16 @@
max-width: 20rem; max-width: 20rem;
} }
.preferencesDetails li > div, .preferencesDetails > li > div,
.preferencesDetails li p { .preferencesDetails p:last-child {
margin: 0; margin-bottom: 0;
} }
.preferencesDetails li p { .preferencesDetails li p {
margin-top: calc(var(--spacer) / 8); margin-top: calc(var(--spacer) / 8);
} }
.preferencesDetails li { .preferencesDetails > li {
padding-top: calc(var(--spacer) / 3); padding-top: calc(var(--spacer) / 3);
padding-bottom: calc(var(--spacer) / 3); padding-bottom: calc(var(--spacer) / 3);
} }

View File

@ -11,16 +11,16 @@ import { darkModeConfig } from '../../../../app.config'
import Chain from './Chain' import Chain from './Chain'
export default function UserPreferences(): ReactElement { export default function UserPreferences(): ReactElement {
// Calling this here because <Theme /> is not mounted on first load // Calling this here because <Style /> is not mounted on first load
const darkMode = useDarkMode(false, darkModeConfig) const darkMode = useDarkMode(false, darkModeConfig)
return ( return (
<Tooltip <Tooltip
content={ content={
<ul className={styles.preferencesDetails}> <ul className={styles.preferencesDetails}>
<Chain />
<Currency /> <Currency />
<Appearance darkMode={darkMode} /> <Appearance darkMode={darkMode} />
{/* <Chain /> */}
<Debug /> <Debug />
</ul> </ul>
} }

View File

@ -5,19 +5,18 @@ import AssetList from '../../organisms/AssetList'
import axios from 'axios' import axios from 'axios'
import { queryMetadata } from '../../../utils/aquarius' import { queryMetadata } from '../../../utils/aquarius'
import { useWeb3 } from '../../../providers/Web3' import { useWeb3 } from '../../../providers/Web3'
import { useOcean } from '../../../providers/Ocean'
import { useSiteMetadata } from '../../../hooks/useSiteMetadata' import { useSiteMetadata } from '../../../hooks/useSiteMetadata'
import { useUserPreferences } from '../../../providers/UserPreferences'
export default function PublishedList(): ReactElement { export default function PublishedList(): ReactElement {
const { accountId } = useWeb3() const { accountId } = useWeb3()
const { appConfig } = useSiteMetadata() const { appConfig } = useSiteMetadata()
const { chainIds } = useUserPreferences()
const [queryResult, setQueryResult] = useState<QueryResult>() const [queryResult, setQueryResult] = useState<QueryResult>()
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
const [page, setPage] = useState<number>(1) const [page, setPage] = useState<number>(1)
const source = axios.CancelToken.source()
useEffect(() => { useEffect(() => {
async function getPublished() { async function getPublished() {
if (!accountId) return if (!accountId) return
@ -34,6 +33,8 @@ export default function PublishedList(): ReactElement {
sort: { created: -1 } sort: { created: -1 }
} }
try { try {
const source = axios.CancelToken.source()
queryResult || setIsLoading(true) queryResult || setIsLoading(true)
const result = await queryMetadata( const result = await queryMetadata(
queryPublishedAssets, queryPublishedAssets,
@ -48,7 +49,7 @@ export default function PublishedList(): ReactElement {
} }
} }
getPublished() getPublished()
}, [accountId, page, appConfig.metadataCacheUri]) }, [accountId, page, appConfig.metadataCacheUri, chainIds])
return accountId ? ( return accountId ? (
<AssetList <AssetList

View File

@ -14,6 +14,7 @@ import { queryMetadata } from '../../utils/aquarius'
import { getHighestLiquidityDIDs } from '../../utils/subgraph' import { getHighestLiquidityDIDs } from '../../utils/subgraph'
import { DDO, Logger } from '@oceanprotocol/lib' import { DDO, Logger } from '@oceanprotocol/lib'
import { useSiteMetadata } from '../../hooks/useSiteMetadata' import { useSiteMetadata } from '../../hooks/useSiteMetadata'
import { useUserPreferences } from '../../providers/UserPreferences'
async function getQueryHighest( async function getQueryHighest(
chainIds: number[] chainIds: number[]
@ -122,14 +123,13 @@ function SectionQueryResult({
export default function HomePage(): ReactElement { export default function HomePage(): ReactElement {
const [queryAndDids, setQueryAndDids] = useState<[SearchQuery, string]>() const [queryAndDids, setQueryAndDids] = useState<[SearchQuery, string]>()
// TODO: appConfig.chainIds needs to come from UserPreferences instead const { chainIds } = useUserPreferences()
const { appConfig } = useSiteMetadata()
useEffect(() => { useEffect(() => {
getQueryHighest(appConfig.chainIds).then((results) => { getQueryHighest(chainIds).then((results) => {
setQueryAndDids(results) setQueryAndDids(results)
}) })
}, [appConfig.chainIds]) }, [chainIds])
return ( return (
<> <>
@ -152,7 +152,7 @@ export default function HomePage(): ReactElement {
<SectionQueryResult <SectionQueryResult
title="Recently Published" title="Recently Published"
query={getQueryLatest(appConfig.chainIds)} query={getQueryLatest(chainIds)}
action={ action={
<Button style="text" to="/search?sort=created&sortOrder=desc"> <Button style="text" to="/search?sort=created&sortOrder=desc">
All data sets and algorithms All data sets and algorithms

View File

@ -23,6 +23,7 @@ interface UseSiteMetadata {
metadataCacheUri: string metadataCacheUri: string
infuraProjectId: string infuraProjectId: string
chainIds: number[] chainIds: number[]
chainIdsSupported: number[]
marketFeeAddress: string marketFeeAddress: string
currencies: string[] currencies: string[]
portisId: string portisId: string
@ -56,6 +57,7 @@ const query = graphql`
metadataCacheUri metadataCacheUri
infuraProjectId infuraProjectId
chainIds chainIds
chainIdsSupported
marketFeeAddress marketFeeAddress
currencies currencies
portisId portisId

View File

@ -18,8 +18,7 @@ interface UserPreferencesValue {
bookmarks: { bookmarks: {
[network: string]: string[] [network: string]: string[]
} }
addChainId: (chain: number) => void setChainIds: (chainIds: number[]) => void
removeChainId: (chain: number) => void
setDebug: (value: boolean) => void setDebug: (value: boolean) => void
setCurrency: (value: string) => void setCurrency: (value: string) => void
addBookmark: (did: string) => void addBookmark: (did: string) => void
@ -57,8 +56,10 @@ function UserPreferencesProvider({
localStorage?.currency || 'EUR' localStorage?.currency || 'EUR'
) )
const [locale, setLocale] = useState<string>() const [locale, setLocale] = useState<string>()
const [chainIds, setChainIds] = useState(appConfig.chainIds)
const [bookmarks, setBookmarks] = useState(localStorage?.bookmarks || {}) const [bookmarks, setBookmarks] = useState(localStorage?.bookmarks || {})
const [chainIds, setChainIds] = useState(
localStorage?.chainIds || appConfig.chainIds
)
// Write values to localStorage on change // Write values to localStorage on change
useEffect(() => { useEffect(() => {
@ -78,16 +79,6 @@ function UserPreferencesProvider({
setLocale(window.navigator.language) setLocale(window.navigator.language)
}, []) }, [])
function addChainId(chain: number): void {
const newChainIds = [...chainIds, chain]
setChainIds(newChainIds)
}
function removeChainId(chain: number): void {
const newChainIds = chainIds.filter((chainId) => chainId !== chain)
setChainIds(newChainIds)
}
// function addBookmark(didToAdd: string): void { // function addBookmark(didToAdd: string): void {
// const newPinned = { // const newPinned = {
// ...bookmarks, // ...bookmarks,
@ -122,8 +113,7 @@ function UserPreferencesProvider({
locale, locale,
chainIds, chainIds,
bookmarks, bookmarks,
addChainId, setChainIds,
removeChainId,
setDebug, setDebug,
setCurrency setCurrency
// addBookmark, // addBookmark,

View File

@ -59,3 +59,11 @@ export function sleep(ms: number): Promise<void> {
setTimeout(resolve, ms) setTimeout(resolve, ms)
}) })
} }
export function removeItemFromArray<T>(arr: Array<T>, value: T): Array<T> {
const index = arr.indexOf(value)
if (index > -1) {
arr.splice(index, 1)
}
return arr
}