1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-06-30 05:41:41 +02:00
market/src/@context/Ocean.tsx

108 lines
2.4 KiB
TypeScript
Raw Normal View History

import React, {
useContext,
useState,
createContext,
ReactElement,
useCallback,
ReactNode,
useEffect
} from 'react'
import { Config, LoggerInstance } from '@oceanprotocol/lib'
import { useWeb3 } from './Web3'
2021-10-13 18:48:59 +02:00
import { getDevelopmentConfig, getOceanConfig } from '@utils/ocean'
2021-05-31 14:27:04 +02:00
import { useAsset } from './Asset'
interface OceanProviderValue {
config: Config
}
const OceanContext = createContext({} as OceanProviderValue)
2021-05-28 14:47:47 +02:00
function OceanProvider({ children }: { children: ReactNode }): ReactElement {
2021-05-31 14:27:04 +02:00
const { web3, accountId } = useWeb3()
const { ddo } = useAsset()
2021-05-28 14:47:47 +02:00
const [config, setConfig] = useState<Config>()
2021-05-28 14:47:47 +02:00
// -----------------------------------
2021-05-31 14:27:04 +02:00
// Helper: Create Ocean instance
// -----------------------------------
const connect = useCallback(
async (config: Config) => {
if (!web3) return
2021-05-28 14:47:47 +02:00
const newConfig: Config = {
2021-05-31 14:27:04 +02:00
...config,
web3Provider: web3
}
2021-05-28 14:47:47 +02:00
2021-05-31 14:27:04 +02:00
try {
LoggerInstance.log(
'[ocean] Connecting Ocean... not anymore ',
newConfig
)
2021-06-04 15:50:24 +02:00
setConfig(newConfig)
} catch (error) {
LoggerInstance.error('[ocean] Error: ', error.message)
}
},
[web3]
)
// -----------------------------------
// Initial asset details connection
// -----------------------------------
useEffect(() => {
if (!ddo?.chainId) return
2021-05-31 14:27:04 +02:00
2021-05-28 14:47:47 +02:00
const config = {
...getOceanConfig(ddo?.chainId),
2021-05-28 14:47:47 +02:00
// add local dev values
...(ddo?.chainId === 8996 && {
2021-05-28 14:47:47 +02:00
...getDevelopmentConfig()
})
}
async function init() {
2021-05-28 14:47:47 +02:00
await connect(config)
}
init()
2021-06-11 15:35:28 +02:00
}, [connect, ddo])
// -----------------------------------
// Get user info, handle account change from web3
// -----------------------------------
// useEffect(() => {
// if ( !accountId || !web3) return
// async function getInfo() {
// const account = (await ocean.accounts.list())[0]
// LoggerInstance.log('[ocean] Account: ', account)
// setAccount(account)
// }
// getInfo()
// }, [ocean, accountId, web3])
return (
<OceanContext.Provider
value={
{
2021-06-04 15:50:24 +02:00
connect,
config
2021-05-28 14:47:47 +02:00
// refreshBalance
} as OceanProviderValue
}
>
{children}
</OceanContext.Provider>
)
}
// Helper hook to access the provider values
const useOcean = (): OceanProviderValue => useContext(OceanContext)
export { OceanProvider, useOcean, OceanContext }
export default OceanProvider