1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-12-02 05:57:29 +01:00

Various fixes in the pool component (#1327)

* remove legacy check to prevent rug pull

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* various fixes

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* remove old prop

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* remove old prop

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* add expected output to remove

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* remove console.logs

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* fix max calculations

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* refactors

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* temp fixes for build

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* fixes

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* local calc for pice and liquidity

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* remove var

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* fix

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* fix

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* fix profile liquidity

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* global context, opc fee

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* comment

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* various fixes

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* refactor global context

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* remove nesting from market context

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* fix build

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* fix undefined appConfig

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* direct import of appConfig & siteContent

* this never changes on run time, so we should never have to wait for it and have it in js bundle at all times
* in utility methods, import directly
* for components, import directly in MarketMetadata context  and pass through

* remove screen CSS fixes

* put back auto-fetching indicator, move manual refresh action behind debug

Co-authored-by: Matthias Kretschmann <m@kretschmann.io>
This commit is contained in:
mihaisc 2022-04-21 17:38:35 -07:00 committed by GitHub
parent 986fd37d3e
commit d1e21b7f03
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
65 changed files with 689 additions and 532 deletions

View File

@ -134,7 +134,7 @@ const queryLatest = {
}
function Component() {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const [result, setResult] = useState<QueryResult>()
useEffect(() => {

View File

@ -2,8 +2,8 @@ module.exports = {
// URI of single metadata cache instance for all networks.
// While ocean.js includes this value for each network as part of its ConfigHelper,
// it is assumed to be the same for all networks.
// In components can be accessed with the useSiteMetadata hook:
// const { appConfig } = useSiteMetadata()
// In components can be accessed with the useMarketMetadata hook:
// const { appConfig } = useMarketMetadata()
// return appConfig.metadataCacheUri
metadataCacheUri:
process.env.NEXT_PUBLIC_METADATACACHE_URI ||

View File

@ -61,8 +61,8 @@
"title": "Remove Liquidity",
"simple": "Set the amount of your pool shares to spend. You will get the equivalent value in OCEAN, limited to maximum amount for pool protection.",
"output": {
"titleIn": "You will spend",
"titleOut": "You will receive"
"titleOutExpected": "Expected output",
"titleOutMinimum": "Minimum received"
},
"action": "Remove"
}

View File

@ -11,12 +11,12 @@ import { Config, LoggerInstance, Purgatory } from '@oceanprotocol/lib'
import { CancelToken } from 'axios'
import { retrieveAsset } from '@utils/aquarius'
import { useWeb3 } from './Web3'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { useCancelToken } from '@hooks/useCancelToken'
import { getOceanConfig, getDevelopmentConfig } from '@utils/ocean'
import { AssetExtended } from 'src/@types/AssetExtended'
import { getAccessDetails } from '@utils/accessDetailsAndPricing'
import { useIsMounted } from '@hooks/useIsMounted'
import { useMarketMetadata } from './MarketMetadata'
interface AssetProviderValue {
isInPurgatory: boolean
@ -40,7 +40,7 @@ function AssetProvider({
did: string
children: ReactNode
}): ReactElement {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const { chainId, accountId } = useWeb3()
const [isInPurgatory, setIsInPurgatory] = useState(false)

View File

@ -8,7 +8,7 @@ import React, {
} from 'react'
import { deleteCookie, getCookieValue, setCookie } from '@utils/cookies'
import { UseGdprMetadata, useGdprMetadata } from '@hooks/useGdprMetadata'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { useMarketMetadata } from './MarketMetadata'
export enum CookieConsentStatus {
NOT_AVAILABLE = -1,
@ -32,7 +32,7 @@ const ConsentContext = createContext({} as ConsentProviderValue)
function ConsentProvider({ children }: { children: ReactNode }): ReactElement {
const cookies = useGdprMetadata()
const { privacyPreferenceCenter } = useSiteMetadata().appConfig
const { appConfig } = useMarketMetadata()
const [consentStatus, setConsentStatus] = useState({} as ConsentStatus)
@ -80,7 +80,7 @@ function ConsentProvider({ children }: { children: ReactNode }): ReactElement {
}
useEffect(() => {
if (privacyPreferenceCenter !== 'true') return
if (appConfig?.privacyPreferenceCenter !== 'true') return
const initialValues = {} as ConsentStatus
cookies.optionalCookies?.map((cookie) => {
@ -100,8 +100,7 @@ function ConsentProvider({ children }: { children: ReactNode }): ReactElement {
})
setConsentStatus(initialValues)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
}, [cookies.optionalCookies, appConfig])
useEffect(() => {
Object.keys(consentStatus).map((cookieName) => {

View File

@ -0,0 +1,12 @@
import { gql } from 'urql'
export const opcQuery = gql`
query OpcQuery {
opc(id: 1) {
swapOceanFee
swapNonOceanFee
approvedTokens
id
}
}
`

View File

@ -0,0 +1,58 @@
export interface OpcFee {
chainId: number
swapNotApprovedFee: string
swapApprovedFee: string
approvedTokens: string[]
}
export interface AppConfig {
metadataCacheUri: string
infuraProjectId: string
chainIds: number[]
chainIdsSupported: number[]
marketFeeAddress: string
publisherMarketOrderFee: string
publisherMarketPoolSwapFee: string
publisherMarketFixedSwapFee: string
consumeMarketOrderFee: string
consumeMarketPoolSwapFee: string
consumeMarketFixedSwapFee: string
currencies: string[]
portisId: string
allowFixedPricing: string
allowDynamicPricing: string
allowFreePricing: string
defaultPrivacyPolicySlug: string
privacyPreferenceCenter: string
darkModeConfig: {
classNameDark: string
classNameLight: string
storageKey: string
}
}
export interface SiteContent {
siteTitle: string
siteTagline: string
siteUrl: string
siteImage: string
copyright: string
menu: {
name: string
link: string
}[]
warning: {
main: string
polygonPublish: string
}
announcement: {
main: string
polygon: string
}
}
export interface MarketMetadataProviderValue {
opcFees: OpcFee[]
siteContent: SiteContent
appConfig: AppConfig
getOpcFeeForToken: (tokenAddress: string, chainId: number) => string
}

View File

@ -0,0 +1,80 @@
import React, {
createContext,
ReactElement,
ReactNode,
useCallback,
useContext,
useEffect,
useState
} from 'react'
import { OpcQuery } from 'src/@types/subgraph/OpcQuery'
import { OperationResult } from 'urql'
import { opcQuery } from './_queries'
import { MarketMetadataProviderValue, OpcFee } from './_types'
import siteContent from '../../../content/site.json'
import appConfig from '../../../app.config'
import { fetchData, getQueryContext } from '@utils/subgraph'
const MarketMetadataContext = createContext({} as MarketMetadataProviderValue)
function MarketMetadataProvider({
children
}: {
children: ReactNode
}): ReactElement {
const [opcFees, setOpcFees] = useState<OpcFee[]>()
useEffect(() => {
async function getOpcData() {
const opcData = []
for (let i = 0; i < appConfig.chainIdsSupported.length; i++) {
const response: OperationResult<OpcQuery> = await fetchData(
opcQuery,
null,
getQueryContext(appConfig.chainIdsSupported[i])
)
opcData.push({
chainId: appConfig.chainIdsSupported[i],
approvedTokens: response.data?.opc.approvedTokens,
swapApprovedFee: response.data?.opc.swapOceanFee,
swapNotApprovedFee: response.data.opc.swapNonOceanFee
} as OpcFee)
}
setOpcFees(opcData)
}
getOpcData()
}, [])
const getOpcFeeForToken = useCallback(
(tokenAddress: string, chainId: number): string => {
if (!opcFees) return
const opc = opcFees.filter((x) => x.chainId === chainId)[0]
const isTokenApproved = opc.approvedTokens.includes(tokenAddress)
return isTokenApproved ? opc.swapApprovedFee : opc.swapNotApprovedFee
},
[opcFees]
)
return (
<MarketMetadataContext.Provider
value={
{
opcFees,
siteContent,
appConfig,
getOpcFeeForToken
} as MarketMetadataProviderValue
}
>
{children}
</MarketMetadataContext.Provider>
)
}
// Helper hook to access the provider values
const useMarketMetadata = (): MarketMetadataProviderValue =>
useContext(MarketMetadataContext)
export { MarketMetadataProvider, useMarketMetadata, MarketMetadataContext }
export default MarketMetadataProvider

View File

@ -1,4 +1,3 @@
import Decimal from 'decimal.js'
import {
PoolData_poolSnapshots as PoolDataPoolSnapshots,
PoolData_poolData as PoolDataPoolData
@ -15,13 +14,12 @@ export interface PoolInfo {
baseTokenSymbol: string
baseTokenAddress: string
totalPoolTokens: string
totalLiquidityInOcean: Decimal
}
export interface PoolInfoUser {
liquidity: Decimal // liquidity in base token
poolShares: string // pool share tokens
poolShare: string // in %
liquidity: string
poolShares: string
poolSharePercentage: string
}
export interface PoolProviderValue {
@ -31,7 +29,6 @@ export interface PoolProviderValue {
poolInfoUser: PoolInfoUser
poolSnapshots: PoolDataPoolSnapshots[]
hasUserAddedLiquidity: boolean
isRemoveDisabled: boolean
refreshInterval: number
fetchAllData: () => void
}

View File

@ -1,5 +1,4 @@
import { LoggerInstance, Pool } from '@oceanprotocol/lib'
import { isValidNumber } from '@utils/numbers'
import { LoggerInstance } from '@oceanprotocol/lib'
import Decimal from 'decimal.js'
import React, {
useContext,
@ -16,22 +15,17 @@ import {
} from 'src/@types/subgraph/PoolData'
import { useAsset } from '../Asset'
import { useWeb3 } from '../Web3'
import { calculateSharesVL } from '@utils/pool'
import { calcSingleOutGivenPoolIn } from '@utils/pool'
import { PoolProviderValue, PoolInfo, PoolInfoUser } from './_types'
import { getFee, getPoolData, getWeight } from './_utils'
Decimal.set({ toExpNeg: -18, precision: 18, rounding: 1 })
import { useMarketMetadata } from '@context/MarketMetadata'
const PoolContext = createContext({} as PoolProviderValue)
const refreshInterval = 10000 // 10 sec.
const initialPoolInfo: Partial<PoolInfo> = {
totalLiquidityInOcean: new Decimal(0)
}
const initialPoolInfoUser: Partial<PoolInfoUser> = {
liquidity: new Decimal(0),
liquidity: '0',
poolShares: '0'
}
@ -39,12 +33,10 @@ const initialPoolInfoCreator: Partial<PoolInfoUser> = initialPoolInfoUser
function PoolProvider({ children }: { children: ReactNode }): ReactElement {
const { accountId, web3, chainId } = useWeb3()
const { isInPurgatory, asset, owner } = useAsset()
const { asset, owner } = useAsset()
const { getOpcFeeForToken } = useMarketMetadata()
const [poolData, setPoolData] = useState<PoolDataPoolData>()
const [poolInfo, setPoolInfo] = useState<PoolInfo>(
initialPoolInfo as PoolInfo
)
const [poolInfo, setPoolInfo] = useState<PoolInfo>()
const [poolInfoOwner, setPoolInfoOwner] = useState<PoolInfoUser>(
initialPoolInfoCreator as PoolInfoUser
)
@ -53,10 +45,7 @@ function PoolProvider({ children }: { children: ReactNode }): ReactElement {
)
const [poolSnapshots, setPoolSnapshots] = useState<PoolDataPoolSnapshots[]>()
const [hasUserAddedLiquidity, setUserHasAddedLiquidity] = useState(false)
const [isRemoveDisabled, setIsRemoveDisabled] = useState(false)
// const [fetchInterval, setFetchInterval] = useState<NodeJS.Timeout>()
const [ownerPoolShares, setOwnerPoolShares] = useState('0')
const [userPoolShares, setUserPoolShares] = useState('0')
const fetchAllData = useCallback(async () => {
if (!asset?.chainId || !asset?.accessDetails?.addressOrId || !owner) return
@ -87,8 +76,11 @@ function PoolProvider({ children }: { children: ReactNode }): ReactElement {
//
useEffect(() => {
if (asset?.accessDetails?.type !== 'dynamic') return
fetchAllData()
const interval = setInterval(() => {
fetchAllData()
}, refreshInterval)
return () => clearInterval(interval)
}, [fetchAllData, asset?.accessDetails?.type])
//
@ -97,37 +89,24 @@ function PoolProvider({ children }: { children: ReactNode }): ReactElement {
useEffect(() => {
if (!poolData) return
// once we have poolData, we need to get owner's pool shares (OVL)
calculateSharesVL(
poolData.id,
poolData.baseToken.address,
poolData.shares[0].shares,
asset.chainId
).then((shares) => {
setOwnerPoolShares(shares)
})
// Total Liquidity
const totalLiquidityInOcean = new Decimal(
poolData.baseTokenLiquidity * 2 || 0
)
const newPoolInfo = {
liquidityProviderSwapFee: getFee(poolData.liquidityProviderSwapFee),
publishMarketSwapFee: getFee(poolData.publishMarketSwapFee),
opcFee: getFee(poolData.opcFee),
opcFee: getFee(
getOpcFeeForToken(poolData.baseToken.address, asset?.chainId)
),
weightBaseToken: getWeight(poolData.baseTokenWeight),
weightDt: getWeight(poolData.datatokenWeight),
datatokenSymbol: poolData.datatoken.symbol,
datatokenAddress: poolData.datatoken.address,
baseTokenSymbol: poolData.baseToken.symbol,
baseTokenAddress: poolData.baseToken.address,
totalPoolTokens: poolData.totalShares,
totalLiquidityInOcean
totalPoolTokens: poolData.totalShares
}
setPoolInfo(newPoolInfo)
LoggerInstance.log('[pool] Created new pool info:', newPoolInfo)
}, [asset?.chainId, chainId, poolData, web3])
}, [asset?.chainId, chainId, getOpcFeeForToken, poolData, web3])
//
// 2 Pool Creator Info
@ -136,29 +115,34 @@ function PoolProvider({ children }: { children: ReactNode }): ReactElement {
if (
!poolData ||
!poolInfo?.totalPoolTokens ||
!poolInfo.totalLiquidityInOcean ||
ownerPoolShares === '0'
poolData.shares[0]?.shares === '0'
)
return
// Pool share tokens.
const poolShare = new Decimal(ownerPoolShares)
.dividedBy(poolInfo.totalLiquidityInOcean)
const poolSharePercentage = new Decimal(poolData.shares[0]?.shares)
.dividedBy(poolInfo.totalPoolTokens)
.mul(100)
.toFixed(2)
const ownerLiquidity = calcSingleOutGivenPoolIn(
poolData.baseTokenLiquidity,
poolData.totalShares,
poolData?.shares[0]?.shares
)
const newPoolOwnerInfo = {
liquidity: new Decimal(ownerPoolShares), // liquidity in base token, values from from `calcSingleOutGivenPoolIn` method
poolShares: ownerPoolShares,
poolShare
liquidity: ownerLiquidity,
poolShares: poolData.shares[0]?.shares,
poolSharePercentage
}
setPoolInfoOwner(newPoolOwnerInfo)
LoggerInstance.log('[pool] Created new owner pool info:', newPoolOwnerInfo)
LoggerInstance.log('[pool] Created new pool creatorinfo:', newPoolOwnerInfo)
}, [
ownerPoolShares,
asset?.chainId,
poolData,
poolInfo.totalLiquidityInOcean,
poolInfo.totalPoolTokens
poolInfo?.baseTokenAddress,
poolInfo?.totalPoolTokens
])
//
@ -169,35 +153,29 @@ function PoolProvider({ children }: { children: ReactNode }): ReactElement {
!poolData ||
!poolInfo?.totalPoolTokens ||
!poolInfoUser?.poolShares ||
!poolInfo?.totalLiquidityInOcean ||
!poolData?.baseTokenLiquidity ||
!asset?.chainId ||
!accountId ||
!poolInfoUser
!asset?.chainId
)
return
// once we have poolData, we need to get user's pool shares (VL)
calculateSharesVL(
poolData.id,
poolData.baseToken.address,
poolInfoUser.poolShares,
asset.chainId
).then((shares) => {
setUserPoolShares(shares)
})
const userLiquidity = calcSingleOutGivenPoolIn(
poolData.baseTokenLiquidity,
poolData.totalShares,
poolInfoUser.poolShares
)
// Pool share in %.
const poolShare = new Decimal(userPoolShares)
.dividedBy(new Decimal(poolInfo.totalLiquidityInOcean))
const poolSharePercentage = new Decimal(poolInfoUser.poolShares)
.dividedBy(new Decimal(poolInfo.totalPoolTokens))
.mul(100)
.toFixed(2)
setUserHasAddedLiquidity(Number(poolShare) > 0)
setUserHasAddedLiquidity(Number(poolSharePercentage) > 0)
const newPoolInfoUser = {
liquidity: new Decimal(userPoolShares), // liquidity in base token, values from from `calcSingleOutGivenPoolIn` method
poolShare
const newPoolInfoUser: PoolInfoUser = {
liquidity: userLiquidity,
poolShares: poolInfoUser.poolShares,
poolSharePercentage
}
setPoolInfoUser((prevState: PoolInfoUser) => ({
...prevState,
@ -205,29 +183,16 @@ function PoolProvider({ children }: { children: ReactNode }): ReactElement {
}))
LoggerInstance.log('[pool] Created new user pool info:', {
poolShares: userPoolShares,
...newPoolInfoUser
})
// poolInfoUser was not added on purpose, we use setPoolInfoUser so it will just loop
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
poolData,
poolInfoUser?.poolShares,
accountId,
userPoolShares,
asset?.chainId,
owner,
poolInfo?.totalPoolTokens
])
//
// Check if removing liquidity should be disabled.
//
useEffect(() => {
if (!owner || !accountId) return
setIsRemoveDisabled(isInPurgatory && owner === accountId)
}, [isInPurgatory, owner, accountId])
return (
<PoolContext.Provider
value={
@ -238,7 +203,6 @@ function PoolProvider({ children }: { children: ReactNode }): ReactElement {
poolInfoUser,
poolSnapshots,
hasUserAddedLiquidity,
isRemoveDisabled,
refreshInterval,
fetchAllData
} as PoolProviderValue

View File

@ -3,12 +3,13 @@ import React, {
ReactElement,
createContext,
useContext,
ReactNode
ReactNode,
useEffect
} from 'react'
import { fetchData } from '@utils/fetch'
import useSWR from 'swr'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { LoggerInstance } from '@oceanprotocol/lib'
import { useMarketMetadata } from './MarketMetadata'
interface Prices {
[key: string]: number
@ -34,12 +35,19 @@ export default function PricesProvider({
}: {
children: ReactNode
}): ReactElement {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const tokenId = 'ocean-protocol'
const currencies = appConfig.currencies.join(',') // comma-separated list
const url = `https://api.coingecko.com/api/v3/simple/price?ids=${tokenId}&vs_currencies=${currencies}`
const [prices, setPrices] = useState(initialData)
const [url, setUrl] = useState('')
useEffect(() => {
if (!appConfig) return
// comma-separated list
const currencies = appConfig.currencies.join(',')
const url = `https://api.coingecko.com/api/v3/simple/price?ids=${tokenId}&vs_currencies=${currencies}`
setUrl(url)
}, [appConfig])
const onSuccess = async (data: { [tokenId]: Prices }) => {
if (!data) return

View File

@ -16,11 +16,11 @@ import { useUserPreferences } from './UserPreferences'
import { PoolShares_poolShares as PoolShare } from '../@types/subgraph/PoolShares'
import { Asset, LoggerInstance } from '@oceanprotocol/lib'
import { getDownloadAssets, getPublishedAssets } from '@utils/aquarius'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { accountTruncate } from '@utils/web3'
import axios, { CancelToken } from 'axios'
import get3BoxProfile from '@utils/profile'
import web3 from 'web3'
import { useMarketMetadata } from './MarketMetadata'
interface ProfileProviderValue {
profile: Profile
@ -49,7 +49,7 @@ function ProfileProvider({
children: ReactNode
}): ReactElement {
const { chainIds } = useUserPreferences()
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const [isEthAddress, setIsEthAddress] = useState<boolean>()

View File

@ -8,7 +8,7 @@ import React, {
} from 'react'
import { LoggerInstance, LogLevel } from '@oceanprotocol/lib'
import { isBrowser } from '@utils/index'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { useMarketMetadata } from './MarketMetadata'
interface UserPreferencesValue {
debug: boolean
@ -51,9 +51,8 @@ function UserPreferencesProvider({
}: {
children: ReactNode
}): ReactElement {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const localStorage = getLocalStorage()
// Set default values from localStorage
const [debug, setDebug] = useState<boolean>(localStorage?.debug || false)
const [currency, setCurrency] = useState<string>(
@ -64,7 +63,7 @@ function UserPreferencesProvider({
const [chainIds, setChainIds] = useState(
localStorage?.chainIds || appConfig.chainIds
)
const { defaultPrivacyPolicySlug } = useSiteMetadata().appConfig
const { defaultPrivacyPolicySlug } = appConfig
const [privacyPolicySlug, setPrivacyPolicySlug] = useState<string>(
localStorage?.privacyPolicySlug || defaultPrivacyPolicySlug

View File

@ -1,6 +0,0 @@
import { UseSiteMetadata } from './types'
import { getSiteMetadata } from '@utils/siteConfig'
export function useSiteMetadata(): UseSiteMetadata {
return getSiteMetadata()
}

View File

@ -1,44 +0,0 @@
export interface UseSiteMetadata {
siteTitle: string
siteTagline: string
siteUrl: string
siteImage: string
copyright: string
menu: {
name: string
link: string
}[]
warning: {
main: string
polygonPublish: string
}
announcement: {
main: string
polygon: string
}
appConfig: {
metadataCacheUri: string
infuraProjectId: string
chainIds: number[]
chainIdsSupported: number[]
marketFeeAddress: string
publisherMarketOrderFee: string
publisherMarketPoolSwapFee: string
publisherMarketFixedSwapFee: string
consumeMarketOrderFee: string
consumeMarketPoolSwapFee: string
consumeMarketFixedSwapFee: string
currencies: string[]
portisId: string
allowFixedPricing: string
allowDynamicPricing: string
allowFreePricing: string
defaultPrivacyPolicySlug: string
privacyPreferenceCenter: string
darkModeConfig: {
classNameDark: string
classNameLight: string
storageKey: string
}
}
}

9
src/@types/Utils.d.ts vendored Normal file
View File

@ -0,0 +1,9 @@
interface CalcInGivenOutParams {
tokenInLiquidity: string
tokenOutLiquidity: string
tokenOutAmount: string
opcFee: string
lpSwapFee: string
publishMarketSwapFee: string
consumeMarketSwapFee: string
}

View File

@ -10,11 +10,11 @@ import {
} from '../@types/subgraph/TokensPriceQuery'
import { Asset, LoggerInstance, ProviderInstance } from '@oceanprotocol/lib'
import { AssetExtended } from 'src/@types/AssetExtended'
import { calculateBuyPrice } from './pool'
import { calcInGivenOut } from './pool'
import { getFixedBuyPrice } from './fixedRateExchange'
import { getSiteMetadata } from './siteConfig'
import { AccessDetails, OrderPriceAndFees } from 'src/@types/Price'
import Decimal from 'decimal.js'
import { consumeMarketOrderFee } from '../../app.config'
const TokensPriceQuery = gql`
query TokensPriceQuery($datatokenIds: [ID!], $account: String) {
@ -229,17 +229,16 @@ function getAccessDetailsFromTokenPrice(
*/
export async function getOrderPriceAndFees(
asset: AssetExtended,
accountId: string
accountId: string,
paramsForPool: CalcInGivenOutParams
): Promise<OrderPriceAndFees> {
const { appConfig } = getSiteMetadata()
const orderPriceAndFee = {
price: '0',
publisherMarketOrderFee:
asset?.accessDetails?.publisherMarketOrderFee || '0',
publisherMarketPoolSwapFee: '0',
publisherMarketFixedSwapFee: '0',
consumeMarketOrderFee: appConfig.consumeMarketOrderFee || '0',
consumeMarketOrderFee: consumeMarketOrderFee || '0',
consumeMarketPoolSwapFee: '0',
consumeMarketFixedSwapFee: '0',
providerFee: {
@ -261,10 +260,7 @@ export async function getOrderPriceAndFees(
// fetch price and swap fees
switch (asset?.accessDetails?.type) {
case 'dynamic': {
const poolPrice = await calculateBuyPrice(
asset?.accessDetails,
asset?.chainId
)
const poolPrice = calcInGivenOut(paramsForPool)
orderPriceAndFee.price = poolPrice.tokenAmount
orderPriceAndFee.liquidityProviderSwapFee =
poolPrice.liquidityProviderSwapFeeAmount
@ -279,7 +275,6 @@ export async function getOrderPriceAndFees(
orderPriceAndFee.price = fixed.baseTokenAmount
orderPriceAndFee.opcFee = fixed.oceanFeeAmount
orderPriceAndFee.publisherMarketFixedSwapFee = fixed.marketFeeAmount
// hack because we don't have it in contracts
orderPriceAndFee.consumeMarketFixedSwapFee = fixed.consumeMarketFeeAmount
break

View File

@ -30,3 +30,9 @@ export function randomIntFromInterval(min: number, max: number): number {
// min and max are included
return Math.floor(Math.random() * (max - min + 1) + min)
}
export function getMaxDecimalsValidation(max: number): RegExp {
// eslint-disable-next-line security/detect-non-literal-regexp
const maxDecimalsValidation = new RegExp('^\\d+(\\.\\d{1,' + max + '})?$')
return maxDecimalsValidation
}

View File

@ -9,8 +9,12 @@ import { AssetExtended } from 'src/@types/AssetExtended'
import Web3 from 'web3'
import { getOceanConfig } from './ocean'
import { TransactionReceipt } from 'web3-eth'
import { getSiteMetadata } from './siteConfig'
import { OrderPriceAndFees } from 'src/@types/Price'
import {
marketFeeAddress,
consumeMarketOrderFee,
consumeMarketFixedSwapFee
} from '../../app.config'
/**
* For pool you need to buy the datatoken beforehand, this always assumes you want to order the first service
@ -27,7 +31,6 @@ export async function order(
): Promise<TransactionReceipt> {
const datatoken = new Datatoken(web3)
const config = getOceanConfig(asset.chainId)
const { appConfig } = getSiteMetadata()
const initializeData = await ProviderInstance.initialize(
asset.id,
@ -42,8 +45,8 @@ export async function order(
serviceIndex: 0,
_providerFee: initializeData.providerFee,
_consumeMarketFee: {
consumeMarketFeeAddress: appConfig.marketFeeAddress,
consumeMarketFeeAmount: appConfig.consumeMarketOrderFee,
consumeMarketFeeAddress: marketFeeAddress,
consumeMarketFeeAmount: consumeMarketOrderFee,
consumeMarketFeeToken: config.oceanTokenAddress
}
} as OrderParams
@ -68,8 +71,8 @@ export async function order(
exchangeContract: config.fixedRateExchangeAddress,
exchangeId: asset.accessDetails.addressOrId,
maxBaseTokenAmount: orderPriceAndFees.price,
swapMarketFee: appConfig.consumeMarketFixedSwapFee,
marketFeeAddress: appConfig.marketFeeAddress
swapMarketFee: consumeMarketFixedSwapFee,
marketFeeAddress
} as FreOrderParams
const tx = await datatoken.buyFromFreAndOrder(
asset.accessDetails.datatoken.address,

View File

@ -1,12 +1,11 @@
import { approve, Pool, PoolPriceAndFees } from '@oceanprotocol/lib'
import Web3 from 'web3'
import { getSiteMetadata } from './siteConfig'
import { getDummyWeb3 } from './web3'
import { TransactionReceipt } from 'web3-eth'
import Decimal from 'decimal.js'
import { AccessDetails } from 'src/@types/Price'
import { isValidNumber } from './numbers'
import { MAX_DECIMALS } from './constants'
import { consumeMarketPoolSwapFee, marketFeeAddress } from '../../app.config'
/**
* This is used to calculate the price to buy one datatoken from a pool, that is different from spot price. You need to pass either a web3 object or a chainId. If you pass a chainId a dummy web3 object will be created
* @param {AccessDetails} accessDetails
@ -27,13 +26,13 @@ export async function calculateBuyPrice(
}
const pool = new Pool(web3)
const { appConfig } = getSiteMetadata()
const estimatedPrice = await pool.getAmountInExactOut(
accessDetails.addressOrId,
accessDetails.baseToken.address,
accessDetails.datatoken.address,
'1',
appConfig.consumeMarketPoolSwapFee
consumeMarketPoolSwapFee
)
return estimatedPrice
@ -45,7 +44,6 @@ export async function buyDtFromPool(
web3: Web3
): Promise<TransactionReceipt> {
const pool = new Pool(web3)
const { appConfig } = getSiteMetadata()
// we need to calculate the actual price to buy one datatoken
const dtPrice = await calculateBuyPrice(accessDetails, null, web3)
const approveTx = await approve(
@ -63,14 +61,14 @@ export async function buyDtFromPool(
accountId,
accessDetails.addressOrId,
{
marketFeeAddress: appConfig.marketFeeAddress,
marketFeeAddress,
tokenIn: accessDetails.baseToken.address,
tokenOut: accessDetails.datatoken.address
},
{
// this is just to be safe
maxAmountIn: new Decimal(dtPrice.tokenAmount).mul(10).toString(),
swapMarketFee: appConfig.consumeMarketPoolSwapFee,
swapMarketFee: consumeMarketPoolSwapFee,
tokenAmountOut: '1'
}
)
@ -79,61 +77,105 @@ export async function buyDtFromPool(
}
/**
* Calculate the base token liquidity based on shares info
* @param {string} shares
* @param {string} totalShares
* @param {string} baseTokenLiquidity
* This is used to calculate the actual price of buying a datatoken, it's a copy of the math in the contracts.
* @param params
* @returns
*/
export function calculateUserLiquidity(
shares: string,
totalShares: string,
baseTokenLiquidity: string
): string {
const totalLiquidity =
isValidNumber(shares) &&
isValidNumber(totalShares) &&
isValidNumber(baseTokenLiquidity)
? new Decimal(shares)
.dividedBy(new Decimal(totalShares))
.mul(baseTokenLiquidity)
: new Decimal(0)
return totalLiquidity.toDecimalPlaces(MAX_DECIMALS).toString()
export function calcInGivenOut(params: CalcInGivenOutParams): PoolPriceAndFees {
const result = {
tokenAmount: '0',
liquidityProviderSwapFeeAmount: '0',
oceanFeeAmount: '0',
publishMarketSwapFeeAmount: '0',
consumeMarketSwapFeeAmount: '0'
} as PoolPriceAndFees
const one = new Decimal(1)
const tokenOutLiqudity = new Decimal(params.tokenOutLiquidity)
const tokenInLiquidity = new Decimal(params.tokenInLiquidity)
const tokenOutAmount = new Decimal(params.tokenOutAmount)
const opcFee = new Decimal(params.opcFee)
const lpFee = new Decimal(params.lpSwapFee)
const publishMarketSwapFee = new Decimal(params.publishMarketSwapFee)
const consumeMarketSwapFee = new Decimal(params.consumeMarketSwapFee)
const diff = tokenOutLiqudity.minus(tokenOutAmount)
const y = tokenOutLiqudity.div(diff)
let foo = y.pow(one)
foo = foo.minus(one)
const totalFee = lpFee
.plus(opcFee)
.plus(publishMarketSwapFee)
.plus(consumeMarketSwapFee)
const tokenAmountIn = tokenInLiquidity.mul(foo).div(one.sub(totalFee))
result.tokenAmount = tokenAmountIn.toString()
result.oceanFeeAmount = tokenAmountIn
.sub(tokenAmountIn.mul(one.sub(opcFee)))
.toString()
result.publishMarketSwapFeeAmount = tokenAmountIn
.sub(tokenAmountIn.mul(one.sub(publishMarketSwapFee)))
.toString()
result.consumeMarketSwapFeeAmount = tokenAmountIn
.sub(tokenAmountIn.mul(one.sub(consumeMarketSwapFee)))
.toString()
result.liquidityProviderSwapFeeAmount = tokenAmountIn
.sub(tokenAmountIn.mul(one.sub(lpFee)))
.toString()
return result
}
export function calculateUserTVL(
shares: string,
totalShares: string,
baseTokenLiquidity: string
/**
* Used to calculate swap values, it's a copy of the math in the contracts.
* @param tokenLiquidity
* @param poolSupply
* @param poolShareAmount
* @returns
*/
export function calcSingleOutGivenPoolIn(
tokenLiquidity: string,
poolSupply: string,
poolShareAmount: string
): string {
const liquidity = calculateUserLiquidity(
shares,
totalShares,
baseTokenLiquidity
)
const tvl = new Decimal(liquidity).mul(2) // we multiply by 2 because of 50/50 weight
return tvl.toDecimalPlaces(MAX_DECIMALS).toString()
const tokenLiquidityD = new Decimal(tokenLiquidity)
const poolSupplyD = new Decimal(poolSupply)
const poolShareAmountD = new Decimal(poolShareAmount)
const newPoolSupply = poolSupplyD.sub(poolShareAmountD)
const poolRatio = newPoolSupply.div(poolSupplyD)
const tokenOutRatio = poolRatio.pow(2)
const newTokenBalanceOut = tokenLiquidityD.mul(tokenOutRatio)
const tokensOut = tokenLiquidityD.sub(newTokenBalanceOut)
return tokensOut.toString()
}
export async function calculateSharesVL(
/**
* Returns the amount of tokens (based on tokenAddress) that can be withdrawn from the pool
* @param {string} poolAddress
* @param {string} tokenAddress
* @param {string} shares
* @param {number} chainId
* @returns
*/
export async function getLiquidityByShares(
pool: string,
tokenAddress: string,
shares: string,
chainId?: number
chainId: number
): Promise<string> {
if (!chainId) throw new Error("chainId can't be undefined at the same time!")
// we only use the dummyWeb3 connection here
const web3 = await getDummyWeb3(chainId)
const poolInstance = new Pool(web3)
// get shares VL in ocean
const amountOcean = await poolInstance.calcSingleOutGivenPoolIn(
const amountBaseToken = await poolInstance.calcSingleOutGivenPoolIn(
pool,
tokenAddress,
shares
)
const tvl = new Decimal(amountOcean || 0).mul(2) // we multiply by 2 because of 50/50 weight
return tvl.toDecimalPlaces(MAX_DECIMALS).toString()
return amountBaseToken
}

View File

@ -1,12 +0,0 @@
import { UseSiteMetadata } from '@hooks/useSiteMetadata/types'
import siteContent from '../../content/site.json'
import appConfig from '../../app.config'
export function getSiteMetadata(): UseSiteMetadata {
const siteMeta: UseSiteMetadata = {
...siteContent,
appConfig
}
return siteMeta
}

View File

@ -15,7 +15,7 @@ import {
import { OrdersData_orders as OrdersData } from '../@types/subgraph/OrdersData'
import { UserSalesQuery as UsersSalesList } from '../@types/subgraph/UserSalesQuery'
import { OpcFeesQuery as OpcFeesData } from '../@types/subgraph/OpcFeesQuery'
import { calculateUserTVL } from './pool'
import { calcSingleOutGivenPoolIn, getLiquidityByShares } from './pool'
import Decimal from 'decimal.js'
import { MAX_DECIMALS } from './constants'
@ -243,13 +243,10 @@ export async function fetchDataForMultipleChains(
let datas: any[] = []
try {
for (const chainId of chainIds) {
// console.log('fetch chainID', chainId)
const context: OperationContext = getQueryContext(chainId)
const response = await fetchData(query, variables, context)
// console.log('fetch response', response)
if (!response || response.error) continue
datas = datas.concat(response?.data)
// console.log('fetch datas', datas)
}
return datas
} catch (error) {
@ -343,7 +340,7 @@ export async function getHighestLiquidityDatatokens(
return dtList
}
export async function getAccountTVLInOwnAssets(
export async function getAccountLiquidityInOwnAssets(
accountId: string,
chainIds: number[],
pools: string[]
@ -357,22 +354,20 @@ export async function getAccountTVLInOwnAssets(
queryVariables,
chainIds
)
let tvl = new Decimal(0)
// console.log('resss', results)
let totalLiquidity = new Decimal(0)
for (const result of results) {
// console.log('result.poolShares', result.poolShares)
for (const poolShare of result.poolShares) {
const poolUserTvl = calculateUserTVL(
poolShare.shares,
const poolUserLiquidity = calcSingleOutGivenPoolIn(
poolShare.pool.baseTokenLiquidity,
poolShare.pool.totalShares,
poolShare.pool.baseTokenLiquidity
poolShare.shares
)
tvl = tvl.add(new Decimal(poolUserTvl))
// console.log('result.poolShares', tvl.toString())
totalLiquidity = totalLiquidity.add(new Decimal(poolUserLiquidity))
}
}
return tvl.toDecimalPlaces(MAX_DECIMALS).toString()
return totalLiquidity.toDecimalPlaces(MAX_DECIMALS).toString()
}
export async function getPoolSharesData(

View File

@ -3,8 +3,8 @@ import React, { ReactElement, useEffect, useState } from 'react'
import { getAssetsNames } from '@utils/aquarius'
import styles from './AssetListTitle.module.css'
import axios from 'axios'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { Asset } from '@oceanprotocol/lib'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function AssetListTitle({
asset,
@ -15,7 +15,7 @@ export default function AssetListTitle({
did?: string
title?: string
}): ReactElement {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const [assetTitle, setAssetTitle] = useState<string>(title)
useEffect(() => {

View File

@ -1,7 +1,8 @@
import React, { ReactElement } from 'react'
import Head from 'next/head'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { isBrowser } from '@utils/index'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function Seo({
title,
@ -12,14 +13,14 @@ export default function Seo({
description?: string
uri: string
}): ReactElement {
const { siteTitle, siteTagline, siteUrl, siteImage } = useSiteMetadata()
const { siteContent } = useMarketMetadata()
// Remove trailing slash from all URLs
const canonical = `${siteUrl}${uri}`.replace(/\/$/, '')
const canonical = `${siteContent?.siteUrl}${uri}`.replace(/\/$/, '')
const pageTitle = title
? `${title} - ${siteTitle}`
: `${siteTitle}${siteTagline}`
? `${title} - ${siteContent?.siteTitle}`
: `${siteContent?.siteTitle}${siteContent?.siteTagline}`
return (
<Head>
@ -47,10 +48,16 @@ export default function Seo({
<meta property="og:description" content={description} />
<meta property="og:url" content={canonical} />
<meta name="image" content={`${siteUrl}${siteImage}`} />
<meta property="og:image" content={`${siteUrl}${siteImage}`} />
<meta
name="image"
content={`${siteContent?.siteUrl}${siteContent?.siteImage}`}
/>
<meta
property="og:image"
content={`${siteContent?.siteUrl}${siteContent?.siteImage}`}
/>
<meta property="og:site_name" content={siteTitle} />
<meta property="og:site_name" content={siteContent?.siteTitle} />
<meta name="twitter:creator" content="@oceanprotocol" />
<meta name="twitter:card" content="summary_large_image" />
</Head>

View File

@ -6,7 +6,6 @@ import { useUserPreferences } from '@context/UserPreferences'
import { gql } from 'urql'
import { TransactionHistory_poolTransactions as TransactionHistoryPoolTransactions } from '../../../@types/subgraph/TransactionHistory'
import { fetchDataForMultipleChains } from '@utils/subgraph'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import NetworkName from '@shared/NetworkName'
import { getAssetsFromDtList } from '@utils/aquarius'
import { getAsset } from '../../Profile/History/PoolShares/_utils'
@ -15,6 +14,7 @@ import Title from './Title'
import styles from './index.module.css'
import { Asset, LoggerInstance } from '@oceanprotocol/lib'
import { useCancelToken } from '@hooks/useCancelToken'
import { useMarketMetadata } from '@context/MarketMetadata'
const REFETCH_INTERVAL = 20000
@ -135,7 +135,7 @@ export default function PoolTransactions({
accountId: string
}): ReactElement {
const { chainIds } = useUserPreferences()
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const cancelToken = useCancelToken()
const [transactions, setTransactions] = useState<PoolTransaction[]>()
@ -199,7 +199,7 @@ export default function PoolTransactions({
setTransactions(sortedTransactions)
setIsLoading(false)
},
[data, chainIds, setIsLoading]
[data, minimal, chainIds, poolChainId]
)
//

View File

@ -2,9 +2,7 @@ import React, { ReactElement } from 'react'
import styles from './index.module.css'
import PriceUnit from '@shared/Price/PriceUnit'
import Logo from '@shared/atoms/Logo'
import Decimal from 'decimal.js'
import Conversion from '@shared/Price/Conversion'
import { MAX_DECIMALS } from '@utils/constants'
export default function Token({
symbol,
@ -15,7 +13,7 @@ export default function Token({
}: {
symbol: string
balance: string
conversion?: Decimal
conversion?: boolean
noIcon?: boolean
size?: 'small' | 'mini'
}): ReactElement {
@ -29,11 +27,8 @@ export default function Token({
</figure>
<PriceUnit price={balance} symbol={symbol} size={size} />
</div>
{conversion?.greaterThan(0) && (
<Conversion
price={conversion.toDecimalPlaces(MAX_DECIMALS).toString()}
className={styles.conversion}
/>
{conversion && (
<Conversion price={balance} className={`${styles.conversion}`} />
)}
</>
)

View File

@ -3,7 +3,6 @@ import Alert from '@shared/atoms/Alert'
import Footer from '../Footer/Footer'
import Header from '../Header'
import { useWeb3 } from '@context/Web3'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { useAccountPurgatory } from '@hooks/useAccountPurgatory'
import AnnouncementBanner from '@shared/AnnouncementBanner'
import PrivacyPreferenceCenter from '../Privacy/PrivacyPreferenceCenter'
@ -11,6 +10,7 @@ import styles from './index.module.css'
import { ToastContainer } from 'react-toastify'
import { useRouter } from 'next/router'
import content from '../../../content/purgatory.json'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function App({
children
@ -19,14 +19,14 @@ export default function App({
}): ReactElement {
const router = useRouter()
const { warning, appConfig } = useSiteMetadata()
const { siteContent, appConfig } = useMarketMetadata()
const { accountId } = useWeb3()
const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId)
return (
<div className={styles.app}>
{router.pathname === '/' && warning.main !== '' && (
<AnnouncementBanner text={warning.main} />
{router.pathname === '/' && siteContent?.warning.main !== '' && (
<AnnouncementBanner text={siteContent?.warning.main} />
)}
<Header />
@ -41,7 +41,7 @@ export default function App({
<main className={styles.main}>{children}</main>
<Footer />
{appConfig.privacyPreferenceCenter === 'true' && (
{appConfig?.privacyPreferenceCenter === 'true' && (
<PrivacyPreferenceCenter style="small" />
)}

View File

@ -1,8 +1,5 @@
import React, { useState, ReactElement, useEffect, useCallback } from 'react'
import {
LoggerInstance,
ComputeAlgorithm,
ComputeOutput,
Asset,
DDO,
PublisherTrustedAlgorithm,
@ -12,7 +9,6 @@ import { toast } from 'react-toastify'
import Price from '@shared/Price'
import FileIcon from '@shared/FileIcon'
import Alert from '@shared/atoms/Alert'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { useWeb3 } from '@context/Web3'
import {
generateBaseQuery,
@ -25,7 +21,7 @@ import axios from 'axios'
import FormStartComputeDataset from './FormComputeDataset'
import styles from './index.module.css'
import SuccessConfetti from '@shared/SuccessConfetti'
import { getServiceByName, secondsToString } from '@utils/ddo'
import { getServiceByName } from '@utils/ddo'
import { AssetSelectionAsset } from '@shared/FormFields/AssetSelection'
import AlgorithmDatasetsListForCompute from './AlgorithmDatasetsListForCompute'
import { getPreviousOrders } from '@utils/subgraph'
@ -37,6 +33,7 @@ import { SortTermOptions } from '../../../../@types/aquarius/SearchQuery'
import { getAccessDetails } from '@utils/accessDetailsAndPricing'
import { AccessDetails } from 'src/@types/Price'
import { transformAssetToAssetSelection } from '@utils/assetConvertor'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function Compute({
ddo,
@ -55,7 +52,7 @@ export default function Compute({
isConsumable?: boolean
consumableFeedback?: string
}): ReactElement {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const { accountId } = useWeb3()
const [isJobStarting, setIsJobStarting] = useState(false)
const [error, setError] = useState<string>()

View File

@ -17,6 +17,8 @@ import { getOrderPriceAndFees } from '@utils/accessDetailsAndPricing'
import { OrderPriceAndFees } from 'src/@types/Price'
import { toast } from 'react-toastify'
import { useIsMounted } from '@hooks/useIsMounted'
import { usePool } from '@context/Pool'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function Download({
asset,
@ -34,6 +36,7 @@ export default function Download({
consumableFeedback?: string
}): ReactElement {
const { accountId, web3 } = useWeb3()
const { getOpcFeeForToken } = useMarketMetadata()
const { isInPurgatory, isAssetNetwork } = useAsset()
const isMounted = useIsMounted()
@ -44,6 +47,7 @@ export default function Download({
const [isOwned, setIsOwned] = useState(false)
const [validOrderTx, setValidOrderTx] = useState('')
const { poolData } = usePool()
const [orderPriceAndFees, setOrderPriceAndFees] =
useState<OrderPriceAndFees>()
useEffect(() => {
@ -55,19 +59,35 @@ export default function Download({
async function init() {
if (
asset?.accessDetails?.addressOrId === ZERO_ADDRESS ||
asset?.accessDetails?.type === 'free'
asset?.accessDetails?.type === 'free' ||
(!poolData && asset?.accessDetails?.type === 'dynamic')
)
return
setIsLoading(true)
setStatusText('Calculating price including fees.')
const orderPriceAndFees = await getOrderPriceAndFees(asset, ZERO_ADDRESS)
const params: CalcInGivenOutParams = {
tokenInLiquidity: poolData?.baseTokenLiquidity,
tokenOutLiquidity: poolData?.datatokenLiquidity,
tokenOutAmount: '1',
opcFee: getOpcFeeForToken(poolData.baseToken.address, asset?.chainId),
lpSwapFee: poolData?.liquidityProviderSwapFee,
publishMarketSwapFee: poolData?.publishMarketSwapFee,
consumeMarketSwapFee: '0'
}
const orderPriceAndFees = await getOrderPriceAndFees(
asset,
ZERO_ADDRESS,
params
)
setOrderPriceAndFees(orderPriceAndFees)
setIsLoading(false)
}
init()
}, [asset, accountId])
}, [asset, accountId, poolData, getOpcFeeForToken])
useEffect(() => {
setHasDatatoken(Number(dtBalance) >= 1)

View File

@ -4,13 +4,18 @@
margin-bottom: var(--spacer);
padding-bottom: calc(var(--spacer) / 2);
border-bottom: 1px solid var(--border-color);
margin-top: -1rem;
margin-left: -2rem;
margin-right: -2rem;
padding-left: var(--spacer);
padding-right: var(--spacer);
}
@media (min-width: 40rem) {
.header {
margin-top: -1rem;
}
}
.headerTitle {
font-size: var(--font-size-large);
margin: 0;

View File

@ -1,6 +1,6 @@
.buttonMax {
position: absolute;
font-size: var(--font-size-mini);
bottom: calc(var(--spacer) / 2);
bottom: calc(var(--spacer) / 2.6);
right: calc(var(--spacer) * 2.5);
}

View File

@ -1,12 +1,8 @@
import React, { ReactElement, useEffect } from 'react'
import styles from './FormAdd.module.css'
import Input from '@shared/FormInput'
import {
Field,
FieldInputProps,
FormikContextType,
useFormikContext
} from 'formik'
import Error from '@shared/FormInput/Error'
import { FormikContextType, useField, useFormikContext } from 'formik'
import Button from '@shared/atoms/Button'
import { FormAddLiquidity } from '.'
import UserLiquidity from '../../UserLiquidity'
@ -36,7 +32,7 @@ export default function FormAdd({
values,
isSubmitting
}: FormikContextType<FormAddLiquidity> = useFormikContext()
const [field, meta] = useField('amount')
useEffect(() => {
async function calculatePoolShares() {
if (!web3 || !poolData?.id || !poolInfo?.totalPoolTokens) return
@ -53,7 +49,7 @@ export default function FormAdd({
const poolTokens = await poolInstance.calcPoolOutGivenSingleIn(
poolData.id,
poolInfo.baseTokenAddress,
values.amount
values.amount.toString()
)
setNewPoolTokens(poolTokens)
const newPoolShareDecimal =
@ -89,29 +85,15 @@ export default function FormAdd({
symbol={poolInfo?.baseTokenSymbol}
/>
<Field name="amount">
{({
field,
form
}: {
field: FieldInputProps<FormAddLiquidity>
form: any
}) => (
<Input
type="number"
name="amount"
max={amountMax}
min="0"
value={values.amount}
step="any"
prefix={poolInfo?.baseTokenSymbol}
placeholder="0"
field={field}
form={form}
disabled={!isAssetNetwork || isSubmitting}
/>
)}
</Field>
<Input
type="number"
min="0"
prefix={poolInfo?.baseTokenSymbol}
placeholder="0"
disabled={!isAssetNetwork || isSubmitting}
{...field}
additionalComponent={<Error meta={meta} />}
/>
{Number(balance.ocean) > 0 && (
<Button

View File

@ -15,13 +15,15 @@ import { useAsset } from '@context/Asset'
import content from '../../../../../../content/price.json'
import { calcMaxExactIn, LoggerInstance, Pool } from '@oceanprotocol/lib'
import { usePool } from '@context/Pool'
import { MAX_DECIMALS } from '@utils/constants'
import { getMaxDecimalsValidation } from '@utils/numbers'
export interface FormAddLiquidity {
amount: string
amount: number
}
const initialValues: FormAddLiquidity = {
amount: ''
amount: 0
}
export default function Add({
@ -43,12 +45,18 @@ export default function Add({
// Live validation rules
// https://github.com/jquense/yup#number
const validationSchema: Yup.SchemaOf<FormAddLiquidity> = Yup.object().shape({
amount: Yup.string()
amount: Yup.number()
.min(0.00001, (param) => `Must be more or equal to ${param.min}`)
.max(
Number(amountMax),
`Maximum you can add is ${Number(amountMax).toFixed(2)} OCEAN`
)
.test(
'maxDigitsAfterDecimal',
`Must have maximum ${MAX_DECIMALS} decimal digits`,
(param) =>
getMaxDecimalsValidation(MAX_DECIMALS).test(param?.toString())
)
.required('Required')
})
@ -126,7 +134,7 @@ export default function Add({
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={async (values, { setSubmitting, resetForm }) => {
await handleAddLiquidity(values.amount, resetForm)
await handleAddLiquidity(values.amount.toString(), resetForm)
setSubmitting(false)
}}
>
@ -162,15 +170,14 @@ export default function Add({
!isValid ||
!isWarningAccepted ||
!values.amount ||
values.amount === '' ||
values.amount === '0'
values.amount === 0
}
isLoading={isSubmitting}
loaderMessage="Adding Liquidity..."
successMessage="Successfully added liquidity."
actionName={content.pool.add.action}
action={submitForm}
amount={values.amount}
amount={values.amount.toString()}
tokenAddress={poolInfo?.baseTokenAddress}
tokenSymbol={poolInfo?.baseTokenSymbol}
txId={txId}

View File

@ -53,7 +53,6 @@ export default function Graph(): ReactElement {
const conversionSpotPrice = prices[currency.toLowerCase()]
const tvl = new Decimal(item.baseTokenLiquidity)
.mul(2)
.mul(conversionSpotPrice) // convert to user currency
.toString()
return tvl

View File

@ -1,19 +1,38 @@
import { calcMaxExactOut } from '@oceanprotocol/lib'
import { PoolInfo, PoolInfoUser } from '@context/Pool/_types'
import { calcMaxExactOut, Pool } from '@oceanprotocol/lib'
import Decimal from 'decimal.js'
import { PoolData_poolData as PoolData } from 'src/@types/subgraph/PoolData'
export async function getMax(poolTokens: string, totalPoolTokens: string) {
const poolTokensAmount = !poolTokens || poolTokens === '0' ? '1' : poolTokens
const maxTokensToRemoveFromPool = calcMaxExactOut(totalPoolTokens)
const poolTokensDecimal = new Decimal(poolTokensAmount)
const maxTokensToRemoveForUser = maxTokensToRemoveFromPool.greaterThan(
poolTokensDecimal
export async function getMax(
poolInstance: Pool,
poolInfo: PoolInfo,
poolInfoUser: PoolInfoUser,
poolData: PoolData
) {
const maxBaseTokensRemovable = calcMaxExactOut(poolData.baseTokenLiquidity)
const maxPoolSharesRemovable = await poolInstance.calcPoolInGivenSingleOut(
poolData.id,
poolInfo.baseTokenAddress,
maxBaseTokensRemovable.toString()
)
? poolTokensDecimal
: maxTokensToRemoveFromPool
const maxPercent = new Decimal(100)
.mul(maxTokensToRemoveForUser)
.div(poolTokensDecimal)
const userPoolShares = poolInfoUser.poolShares
const maxPoolSharesRemovableDecimal = new Decimal(maxPoolSharesRemovable)
const userPoolSharesDecimal = new Decimal(userPoolShares)
const maxPoolSharesRemovableByUser =
maxPoolSharesRemovableDecimal.greaterThan(userPoolSharesDecimal)
? userPoolSharesDecimal
: maxPoolSharesRemovableDecimal
// small hack because if the values are equal the decimal.js result is 99.(9)
const maxPercent = maxPoolSharesRemovableByUser.equals(userPoolSharesDecimal)
? new Decimal(100)
: new Decimal(100)
.mul(maxPoolSharesRemovableByUser)
.div(userPoolSharesDecimal)
return maxPercent.toDecimalPlaces(0, Decimal.ROUND_DOWN).toString()
}

View File

@ -3,6 +3,7 @@
padding-left: calc(var(--spacer) * 2);
padding-right: calc(var(--spacer) * 2);
padding-bottom: calc(var(--spacer) / 2);
margin-bottom: 0;
}
.range {
@ -50,25 +51,22 @@
}
.output {
composes: output from '../Add/Output.module.css';
}
.output [class*='token'] {
white-space: nowrap;
}
.output [class*='token'] > figure {
display: inline-block;
}
.output figure[class*='pool shares'] {
display: none;
composes: container from '../Section/index.module.css';
display: grid;
gap: var(--spacer);
grid-template-columns: 1fr 1fr;
}
.output p {
font-weight: var(--font-weight-bold);
margin-bottom: calc(var(--spacer) / 8);
font-size: var(--font-size-small);
}
.output [class*='token'] > figure {
display: none;
}
.slippage {
composes: slippage from '../../Trade/Slippage.module.css';
}

View File

@ -43,8 +43,6 @@ export default function Remove({
const [slippage, setSlippage] = useState<string>('5')
const [minOceanAmount, setMinOceanAmount] = useState<string>('0')
// TODO: precision needs to be set based on baseToken decimals
Decimal.set({ toExpNeg: -18, precision: 18, rounding: 1 })
const poolInstance = new Pool(web3)
async function handleRemoveLiquidity() {
@ -79,10 +77,18 @@ export default function Remove({
if (!accountId || !poolInfoUser?.poolShares || !poolInfo?.totalPoolTokens)
return
getMax(poolInfoUser.poolShares, poolInfo.totalPoolTokens).then((max) =>
getMax(poolInstance, poolInfo, poolInfoUser, poolData).then((max) =>
setAmountMaxPercent(max)
)
}, [accountId, poolInfoUser?.poolShares, poolInfo?.totalPoolTokens])
}, [
accountId,
poolInfoUser?.poolShares,
poolInfo?.totalPoolTokens,
poolInfoUser,
poolInfo,
poolInstance,
poolData
])
const getValues = useRef(
debounce(async (newAmountPoolShares) => {
@ -91,7 +97,6 @@ export default function Remove({
poolInfo?.baseTokenAddress,
newAmountPoolShares
)
setAmountOcean(newAmountOcean)
}, 150)
)
@ -137,20 +142,18 @@ export default function Remove({
.dividedBy(100)
.mul(new Decimal(poolInfoUser.poolShares))
.toString()
setAmountPoolShares(`${amountPoolShares.slice(0, 18)}`)
setAmountPoolShares(amountPoolShares)
}
function handleMaxButton(e: ChangeEvent<HTMLInputElement>) {
e.preventDefault()
setAmountPercent(amountMaxPercent)
const amountPoolShares = new Decimal(amountMaxPercent)
.dividedBy(100)
.mul(new Decimal(poolInfoUser?.poolShares))
.toString()
setAmountPoolShares(`${amountPoolShares.slice(0, 18)}`)
setAmountPoolShares(amountPoolShares)
}
function handleSlippageChange(e: ChangeEvent<HTMLSelectElement>) {
@ -196,13 +199,17 @@ export default function Remove({
</form>
<div className={styles.output}>
<div>
<p>{content.pool.remove.output.titleOut} minimum</p>
<p>{content.pool.remove.output.titleOutExpected}</p>
<Token
symbol={poolInfo?.baseTokenSymbol}
balance={amountOcean}
noIcon
/>
</div>
<div>
<p>{content.pool.remove.output.titleOutMinimum}</p>
<Token symbol={poolInfo?.baseTokenSymbol} balance={minOceanAmount} />
</div>
{/* <div>
<p>{content.pool.remove.output.titleIn}</p>
<Token symbol="pool shares" balance={amountPoolShares} noIcon />
</div> */}
</div>
<div className={styles.slippage}>
<strong>Slippage Tolerance</strong>

View File

@ -1,4 +1,6 @@
.update {
display: block;
margin: 0;
font-size: var(--font-size-mini);
color: var(--color-secondary);
text-align: center;
@ -6,27 +8,31 @@
padding-bottom: calc(var(--spacer) / 3);
}
/* .update:before {
content: '';
width: 6px;
height: 6px;
border-radius: 50%;
display: inline-block;
border: 1px solid var(--brand-alert-green);
margin-right: 0.2rem;
margin-top: -0.1rem;
vertical-align: middle;
animation: pulse 2s ease-in-out infinite;
.update:before {
content: '';
width: 6px;
height: 6px;
border-radius: 50%;
display: inline-block;
border: 1px solid var(--brand-alert-green);
margin-right: 0.2rem;
margin-top: -0.1rem;
vertical-align: middle;
animation: pulse 2s ease-in-out infinite;
}
.button {
font-size: var(--font-size-mini);
}
@keyframes pulse {
0% {
background: transparent;
}
@keyframes pulse {
0% {
background: transparent;
}
50% {
background: var(--brand-alert-green);
}
100% {
background: transparent;
}
} */
50% {
background: var(--brand-alert-green);
}
100% {
background: transparent;
}
}

View File

@ -1,17 +1,26 @@
import { usePool } from '@context/Pool'
import { useUserPreferences } from '@context/UserPreferences'
import Button from '@shared/atoms/Button'
import React from 'react'
import styles from './Update.module.css'
export default function Update() {
const { fetchAllData } = usePool()
const { debug } = useUserPreferences()
const { fetchAllData, refreshInterval } = usePool()
return (
<div className={styles.update}>
<Button style="text" size="small" onClick={() => fetchAllData()}>
Refresh Data
</Button>
{/* Fetching every {refreshInterval / 1000} sec. */}
</div>
<p className={styles.update}>
Fetching every {refreshInterval / 1000} sec.{' '}
{debug && (
<Button
style="text"
size="small"
onClick={() => fetchAllData()}
className={styles.button}
>
Refresh Data
</Button>
)}
</p>
)
}

View File

@ -47,9 +47,10 @@ export default function PoolSections() {
</PoolSection>
<PoolSection
title="Your Value Locked"
title="Your liquidity"
titlePostfix={
poolInfoUser?.poolShare && `${poolInfoUser?.poolShare}% of pool`
poolInfoUser?.poolSharePercentage &&
`${poolInfoUser?.poolSharePercentage}% of pool`
}
tooltip={content.pool.tooltips.liquidity.replace(
'SWAPFEE',
@ -59,27 +60,27 @@ export default function PoolSections() {
>
<Token
symbol={poolInfo?.baseTokenSymbol}
balance={poolInfoUser?.liquidity.toString()}
conversion={poolInfoUser?.liquidity}
balance={poolInfoUser?.liquidity}
conversion
/>
</PoolSection>
<PoolSection
title="Owner Value Locked"
titlePostfix={`${poolInfoOwner?.poolShare}% of pool`}
title="Owner liquidity"
titlePostfix={`${poolInfoOwner?.poolSharePercentage}% of pool`}
>
<Token
symbol={poolInfo?.baseTokenSymbol}
balance={poolInfoOwner?.liquidity.toString()}
conversion={poolInfoOwner?.liquidity}
balance={poolInfoOwner?.liquidity}
conversion
/>
</PoolSection>
<PoolSection title="Total Value Locked">
<Token
symbol={poolInfo?.baseTokenSymbol}
balance={poolInfo?.totalLiquidityInOcean.toString()}
conversion={poolInfo?.totalLiquidityInOcean}
balance={poolData?.baseTokenLiquidity.toString()}
conversion
/>
</PoolSection>
@ -92,7 +93,6 @@ export default function PoolSections() {
titlePostfixTitle={`Weight of ${poolInfo?.weightBaseToken}% ${poolInfo?.baseTokenSymbol} & ${poolInfo?.weightDt}% ${poolInfo?.datatokenSymbol}`}
>
<Graph />
<Token
symbol={poolInfo?.baseTokenSymbol}
balance={`${poolData?.baseTokenLiquidity}`}
@ -105,7 +105,7 @@ export default function PoolSections() {
/>
<Token
symbol="% pool fee"
symbol="% swap fee"
balance={poolInfo?.liquidityProviderSwapFee}
noIcon
size="mini"
@ -117,7 +117,7 @@ export default function PoolSections() {
size="mini"
/>
<Token
symbol="% OPF fee"
symbol="% OPC fee"
balance={poolInfo?.opcFee}
noIcon
size="mini"

View File

@ -13,7 +13,7 @@ import PoolSections from './Sections'
export default function Pool(): ReactElement {
const { isInPurgatory, asset, isAssetNetwork } = useAsset()
const { hasUserAddedLiquidity, isRemoveDisabled } = usePool()
const { hasUserAddedLiquidity } = usePool()
const { accountId } = useWeb3()
const [showAdd, setShowAdd] = useState(false)
@ -34,12 +34,12 @@ export default function Pool(): ReactElement {
style="primary"
size="small"
onClick={() => setShowAdd(true)}
disabled={isInPurgatory}
disabled={isInPurgatory || !isAssetNetwork}
>
Add Liquidity
</Button>
{hasUserAddedLiquidity && !isRemoveDisabled && (
{hasUserAddedLiquidity && (
<Button
size="small"
onClick={() => setShowRemove(true)}

View File

@ -22,7 +22,7 @@ import { initialValues } from './_constants'
import content from '../../../../../content/price.json'
import { AssetExtended } from 'src/@types/AssetExtended'
import { usePool } from '@context/Pool'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function FormTrade({
asset,
@ -34,7 +34,7 @@ export default function FormTrade({
const { web3, accountId } = useWeb3()
const { isAssetNetwork } = useAsset()
const { debug } = useUserPreferences()
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const { poolInfo } = usePool()
const [txId, setTxId] = useState<string>()
const [coinFrom, setCoinFrom] = useState<string>('OCEAN')
@ -67,7 +67,7 @@ export default function FormTrade({
.defined()
async function handleTrade(values: FormTradeData) {
if (!web3 || !asset || !poolInfo || !values) return
if (!web3 || !asset || !poolInfo || !values || !appConfig) return
try {
const poolInstance = new Pool(web3)

View File

@ -20,8 +20,8 @@ import {
} from '@oceanprotocol/lib'
import { AssetExtended } from 'src/@types/AssetExtended'
import { usePool } from '@context/Pool'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { MAX_DECIMALS } from '@utils/constants'
import { useMarketMetadata } from '@context/MarketMetadata'
// Decimal.set({ toExpNeg: -15, precision: 5, rounding: Decimal.ROUND_DOWN })
@ -41,7 +41,7 @@ export default function Swap({
const { isAssetNetwork } = useAsset()
const { web3 } = useWeb3()
const { poolInfo, poolData } = usePool()
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const [baseTokenItem, setBaseTokenItem] = useState<TradeItem>({
amount: '0',
@ -69,7 +69,7 @@ export default function Swap({
const [lpSwapFee, setLpSwapFee] = useState<string>()
useEffect(() => {
if (!asset || !balance || !values?.type || !web3) return
if (!asset || !balance || !values?.type || !web3 || !appConfig) return
const poolInstance = new Pool(web3)
async function calculateMaximum() {
@ -171,6 +171,7 @@ export default function Swap({
poolInfo.liquidityProviderSwapFee,
poolInfo.datatokenAddress,
poolInfo.baseTokenAddress,
appConfig,
appConfig.consumeMarketPoolSwapFee
])

View File

@ -11,12 +11,12 @@ import {
} from '@utils/aquarius'
import { useAsset } from '@context/Asset'
import { PublisherTrustedAlgorithm } from '@oceanprotocol/lib'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import FormActions from './FormActions'
import { useCancelToken } from '@hooks/useCancelToken'
import { SortTermOptions } from '../../../@types/aquarius/SearchQuery'
import { getServiceByName } from '@utils/ddo'
import { transformAssetToAssetSelection } from '@utils/assetConvertor'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function FormEditComputeDataset({
data,
@ -25,7 +25,7 @@ export default function FormEditComputeDataset({
data: InputProps[]
title: string
}): ReactElement {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const { asset } = useAsset()
const { values }: FormikContextType<ComputePrivacyForm> = useFormikContext()
const [allAlgorithms, setAllAlgorithms] = useState<AssetSelectionAsset[]>()
@ -59,7 +59,7 @@ export default function FormEditComputeDataset({
getAlgorithmList(publisherTrustedAlgorithms).then((algorithms) => {
setAllAlgorithms(algorithms)
})
}, [appConfig.metadataCacheUri, publisherTrustedAlgorithms])
}, [appConfig, appConfig.metadataCacheUri, publisherTrustedAlgorithms])
return (
<Form className={styles.form}>

View File

@ -1,15 +1,15 @@
import React, { ReactElement } from 'react'
import styles from './Footer.module.css'
import Markdown from '@shared/Markdown'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import MarketStats from './MarketStats'
import BuildId from './BuildId'
import Links from './Links'
import Button from '@shared/atoms/Button'
import External from '@images/external.svg'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function Footer(): ReactElement {
const { copyright } = useSiteMetadata()
const { siteContent } = useMarketMetadata()
const year = new Date().getFullYear()
return (
@ -20,7 +20,7 @@ export default function Footer(): ReactElement {
<div className={styles.grid}>
<Links />
<div className={styles.copyright}>
© {year} <Markdown text={copyright} />
© {year} <Markdown text={siteContent?.copyright} />
<Button
style="text"
size="small"

View File

@ -1,15 +1,15 @@
import { useUserPreferences } from '@context/UserPreferences'
import { useGdprMetadata } from '@hooks/useGdprMetadata'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import Button from '@shared/atoms/Button'
import Link from 'next/link'
import React, { Fragment } from 'react'
import content from '../../../content/footer.json'
import External from '@images/external.svg'
import styles from './Links.module.css'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function Links() {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const { setShowPPC, privacyPolicySlug } = useUserPreferences()
const cookies = useGdprMetadata()
@ -35,7 +35,7 @@ export default function Links() {
<Link href={privacyPolicySlug}>
<a>Privacy</a>
</Link>
{appConfig.privacyPreferenceCenter === 'true' && (
{appConfig?.privacyPreferenceCenter === 'true' && (
<>
{' — '}
<Button

View File

@ -2,7 +2,6 @@ import React, { ReactElement, useCallback, useEffect, useState } from 'react'
import { OperationContext } from 'urql'
import Tooltip from '@shared/atoms/Tooltip'
import { fetchData, getSubgraphUri } from '@utils/subgraph'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import useNetworkMetadata, {
filterNetworksByType
} from '@hooks/useNetworkMetadata'
@ -16,6 +15,7 @@ import { usePrices } from '@context/Prices'
import { useUserPreferences } from '@context/UserPreferences'
import Decimal from 'decimal.js'
import { StatsTotal, StatsValue } from './_types'
import { useMarketMetadata } from '@context/MarketMetadata'
const initialTotal: StatsTotal = {
totalValueLockedInOcean: 0,
@ -27,14 +27,15 @@ const initialTotal: StatsTotal = {
}
export default function MarketStats(): ReactElement {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const { networksList } = useNetworkMetadata()
const { currency } = useUserPreferences()
const { prices } = usePrices()
const [mainChainIds, setMainChainIds] = useState<number[]>()
const [data, setData] =
useState<{ [chainId: number]: FooterStatsValuesGlobalStatistics }>()
const [data, setData] = useState<{
[chainId: number]: FooterStatsValuesGlobalStatistics
}>()
const [totalValueLockedInOcean, setTotalValueLockedInOcean] =
useState<StatsValue>()
const [totalOceanLiquidity, setTotalOceanLiquidity] = useState<StatsValue>()
@ -45,7 +46,7 @@ export default function MarketStats(): ReactElement {
// Set the main chain ids we want to display stats for
//
useEffect(() => {
if (!networksList) return
if (!networksList || !appConfig || !appConfig?.chainIdsSupported) return
const mainChainIdsList = filterNetworksByType(
'mainnet',
@ -53,7 +54,7 @@ export default function MarketStats(): ReactElement {
networksList
)
setMainChainIds(mainChainIdsList)
}, [appConfig.chainIdsSupported, networksList])
}, [appConfig, appConfig?.chainIdsSupported, networksList])
//
// Helper: fetch data from subgraph

View File

@ -1,7 +1,6 @@
import React, { ReactElement } from 'react'
import Link from 'next/link'
import loadable from '@loadable/component'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import Badge from '@shared/atoms/Badge'
import Logo from '@shared/atoms/Logo'
import UserPreferences from './UserPreferences'
@ -9,6 +8,7 @@ import Networks from './UserPreferences/Networks'
import SearchBar from './SearchBar'
import styles from './Menu.module.css'
import { useRouter } from 'next/router'
import { useMarketMetadata } from '@context/MarketMetadata'
const Wallet = loadable(() => import('./Wallet'))
@ -33,7 +33,7 @@ function MenuLink({ item }: { item: MenuItem }) {
}
export default function Menu(): ReactElement {
const { menu, siteTitle } = useSiteMetadata()
const { siteContent } = useMarketMetadata()
return (
<nav className={styles.menu}>
@ -41,13 +41,13 @@ export default function Menu(): ReactElement {
<a className={styles.logo}>
<Logo noWordmark />
<h1 className={styles.title}>
{siteTitle} <Badge label="v4" />
{siteContent?.siteTitle} <Badge label="v4" />
</h1>
</a>
</Link>
<ul className={styles.navigation}>
{menu.map((item: MenuItem) => (
{siteContent?.menu.map((item: MenuItem) => (
<li key={item.name}>
<MenuLink item={item} />
</li>

View File

@ -1,11 +1,11 @@
import React, { ReactElement, ChangeEvent } from 'react'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { useUserPreferences } from '@context/UserPreferences'
import Input from '@shared/FormInput'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function Currency(): ReactElement {
const { currency, setCurrency } = useUserPreferences()
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
return (
<li>
@ -14,7 +14,7 @@ export default function Currency(): ReactElement {
label="Currency"
help="Your conversion display currency."
type="select"
options={appConfig.currencies}
options={appConfig?.currencies}
value={currency}
onChange={(e: ChangeEvent<HTMLSelectElement>) =>
setCurrency(e.target.value)

View File

@ -1,6 +1,5 @@
import React, { ReactElement } from 'react'
import Label from '@shared/FormInput/Label'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import FormHelp from '@shared/FormInput/Help'
import Tooltip from '@shared/atoms/Tooltip'
import Caret from '@images/caret.svg'
@ -12,10 +11,11 @@ import useNetworkMetadata, {
filterNetworksByType
} from '@hooks/useNetworkMetadata'
import { useUserPreferences } from '@context/UserPreferences'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function Networks(): ReactElement {
const { appConfig } = useMarketMetadata()
const { networksList } = useNetworkMetadata()
const { appConfig } = useSiteMetadata()
const { chainIds } = useUserPreferences()
const networksMain = filterNetworksByType(

View File

@ -8,12 +8,12 @@ import Caret from '@images/caret.svg'
import useDarkMode from 'use-dark-mode'
import Appearance from './Appearance'
import TokenApproval from './TokenApproval'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function UserPreferences(): ReactElement {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
// Calling this here because <Style /> is not mounted on first load
const darkMode = useDarkMode(false, appConfig.darkModeConfig)
const darkMode = useDarkMode(false, appConfig?.darkModeConfig)
return (
<Tooltip

View File

@ -6,11 +6,11 @@ import Price from '@shared/Price'
import Tooltip from '@shared/atoms/Tooltip'
import AssetTitle from '@shared/AssetList/AssetListTitle'
import { retrieveDDOListByDIDs } from '@utils/aquarius'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { useCancelToken } from '@hooks/useCancelToken'
import { AssetExtended } from 'src/@types/AssetExtended'
import { getAccessDetailsForAssets } from '@utils/accessDetailsAndPricing'
import { useWeb3 } from '@context/Web3'
import { useMarketMetadata } from '@context/MarketMetadata'
const columns = [
{
@ -43,7 +43,7 @@ const columns = [
]
export default function Bookmarks(): ReactElement {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const { accountId } = useWeb3()
const { bookmarks } = useUserPreferences()

View File

@ -1,32 +1,30 @@
import { LoggerInstance } from '@oceanprotocol/lib'
import React, { useEffect, useState, ReactElement } from 'react'
import { useUserPreferences } from '@context/UserPreferences'
import { getAccountTVLInOwnAssets, UserLiquidity } from '@utils/subgraph'
import { getAccountLiquidityInOwnAssets } from '@utils/subgraph'
import Conversion from '@shared/Price/Conversion'
import NumberUnit from './NumberUnit'
import styles from './Stats.module.css'
import { useProfile } from '@context/Profile'
import { PoolShares_poolShares as PoolShare } from '../../../@types/subgraph/PoolShares'
import { getAccessDetailsForAssets } from '@utils/accessDetailsAndPricing'
import { calculateUserTVL } from '@utils/pool'
import { calcSingleOutGivenPoolIn } from '@utils/pool'
import Decimal from 'decimal.js'
import { MAX_DECIMALS } from '@utils/constants'
async function getPoolSharesLiquidity(
poolShares: PoolShare[]
): Promise<string> {
let tvl = new Decimal(0)
function getPoolSharesLiquidity(poolShares: PoolShare[]): string {
let liquidity = new Decimal(0)
for (const poolShare of poolShares) {
const poolUserTvl = calculateUserTVL(
poolShare.shares,
const poolUserLiquidity = calcSingleOutGivenPoolIn(
poolShare.pool.baseTokenLiquidity,
poolShare.pool.totalShares,
poolShare.pool.baseTokenLiquidity
poolShare.shares
)
tvl = tvl.add(new Decimal(poolUserTvl))
liquidity = liquidity.add(new Decimal(poolUserLiquidity))
}
return tvl.toDecimalPlaces(MAX_DECIMALS).toString()
return liquidity.toDecimalPlaces(MAX_DECIMALS).toString()
}
export default function Stats({
@ -61,7 +59,7 @@ export default function Stats({
)
}
}
const userTvl = await getAccountTVLInOwnAssets(
const userTvl = await getAccountLiquidityInOwnAssets(
accountId,
chainIds,
accountPoolAdresses
@ -91,11 +89,11 @@ export default function Stats({
return (
<div className={styles.stats}>
<NumberUnit
label="TVL in Own Assets"
label="Liquidity in Own Assets"
value={<Conversion price={publisherTvl} hideApproximateSymbol />}
/>
<NumberUnit
label="TVL"
label="Liquidity"
value={<Conversion price={totalTvl} hideApproximateSymbol />}
/>
<NumberUnit label={`Sale${sales === 1 ? '' : 's'}`} value={sales} />

View File

@ -7,8 +7,8 @@ import { retrieveAsset } from '@utils/aquarius'
import Results from './Results'
import styles from './Details.module.css'
import { useCancelToken } from '@hooks/useCancelToken'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import MetaItem from '../../../Asset/AssetContent/MetaItem'
import { useMarketMetadata } from '@context/MarketMetadata'
function Asset({
title,
@ -40,7 +40,7 @@ function Asset({
}
function DetailsAssets({ job }: { job: ComputeJobMetaData }) {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const [algoName, setAlgoName] = useState<string>()
const [algoDtSymbol, setAlgoDtSymbol] = useState<string>()
const newCancelToken = useCancelToken()

View File

@ -1,11 +1,10 @@
import React from 'react'
import React, { useEffect, useState } from 'react'
import Conversion from '@shared/Price/Conversion'
import styles from './Liquidity.module.css'
import Token from '../../../@shared/Token'
import { isValidNumber } from '@utils/numbers'
import Decimal from 'decimal.js'
import { AssetPoolShare } from './index'
import { calculateUserTVL } from '@utils/pool'
import { calcSingleOutGivenPoolIn } from '@utils/pool'
export function Liquidity({
row,
@ -14,38 +13,34 @@ export function Liquidity({
row: AssetPoolShare
type: string
}) {
let price = '0'
let liquidity = '0'
const [liquidity, setLiquidity] = useState('0')
if (type === 'user') {
price = new Decimal(row.userLiquidity).mul(2).toString()
useEffect(() => {
let calculatedLiquidity = '0'
if (type === 'user') {
calculatedLiquidity = calcSingleOutGivenPoolIn(
row.poolShare.pool.baseTokenLiquidity,
row.poolShare.pool.totalShares,
row.poolShare.shares
)
}
if (type === 'pool') {
calculatedLiquidity = new Decimal(
row.poolShare.pool.baseTokenLiquidity
).toString()
}
setLiquidity(calculatedLiquidity)
}, [
row.poolShare.pool.baseTokenLiquidity,
row.poolShare.pool.totalShares,
row.poolShare.shares,
type
])
// Liquidity in base token, calculated from pool share tokens.
liquidity = calculateUserTVL(
row.poolShare.shares,
row.poolShare.pool.totalShares,
row.poolShare.pool.baseTokenLiquidity
)
}
if (type === 'pool') {
price =
isValidNumber(row.poolShare.pool.baseTokenLiquidity) &&
isValidNumber(row.poolShare.pool.datatokenLiquidity) &&
isValidNumber(row.poolShare.pool.spotPrice)
? new Decimal(row.poolShare.pool.datatokenLiquidity)
.mul(new Decimal(row.poolShare.pool.spotPrice))
.plus(row.poolShare.pool.baseTokenLiquidity)
.toString()
: '0'
liquidity = new Decimal(row.poolShare.pool.baseTokenLiquidity)
.mul(2)
.toString()
}
return (
<div className={styles.userLiquidity}>
<Conversion
price={price}
price={liquidity}
className={styles.totalLiquidity}
hideApproximateSymbol
/>

View File

@ -1,5 +1,5 @@
import { getAssetsFromDtList } from '@utils/aquarius'
import { calculateUserLiquidity } from '@utils/pool'
import { calcSingleOutGivenPoolIn, getLiquidityByShares } from '@utils/pool'
import { CancelToken } from 'axios'
import { PoolShares_poolShares as PoolShare } from '../../../../@types/subgraph/PoolShares'
import { AssetPoolShare } from '.'
@ -31,10 +31,10 @@ export async function getAssetsFromPoolShares(
const ddoList = await getAssetsFromDtList(dtList, chainIds, cancelToken)
for (let i = 0; i < data.length; i++) {
const userLiquidity = calculateUserLiquidity(
data[i].shares,
const userLiquidity = calcSingleOutGivenPoolIn(
data[i].pool.baseTokenLiquidity,
data[i].pool.totalShares,
data[i].pool.baseTokenLiquidity
data[i].shares
)
assetList.push({
poolShare: data[i],

View File

@ -38,7 +38,7 @@ const columns = [
}
},
{
name: 'Your Value Locked',
name: 'Your liquidity',
selector: function getAssetRow(row: AssetPoolShare) {
return <Liquidity row={row} type="user" />
},

View File

@ -2,18 +2,18 @@ import { LoggerInstance } from '@oceanprotocol/lib'
import React, { ReactElement, useEffect, useState, useCallback } from 'react'
import AssetList from '@shared/AssetList'
import { getPublishedAssets } from '@utils/aquarius'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { useUserPreferences } from '@context/UserPreferences'
import styles from './PublishedList.module.css'
import { useCancelToken } from '@hooks/useCancelToken'
import Filters from '../../Search/Filters'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function PublishedList({
accountId
}: {
accountId: string
}): ReactElement {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
const { chainIds } = useUserPreferences()
const [queryResult, setQueryResult] = useState<PagedAssets>()
@ -56,7 +56,7 @@ export default function PublishedList({
}, [
accountId,
page,
appConfig.metadataCacheUri,
appConfig?.metadataCacheUri,
chainIds,
newCancelToken,
getPublished,

View File

@ -7,7 +7,7 @@ import Error from '@shared/FormInput/Error'
import { getOpcFees } from '../../../@utils/subgraph'
import { OpcFeesQuery_opc as OpcFeesData } from '../../../@types/subgraph/OpcFeesQuery'
import { useWeb3 } from '@context/Web3'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import { useMarketMetadata } from '@context/MarketMetadata'
const Default = ({
title,
@ -45,7 +45,7 @@ export default function Fees({
const [field, meta] = useField('pricing.swapFee')
const [opcFees, setOpcFees] = useState<OpcFeesData>(undefined)
const { chainId } = useWeb3()
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
useEffect(() => {
getOpcFees(chainId || 1).then((response: OpcFeesData) => {
@ -88,8 +88,8 @@ export default function Fees({
tooltip={tooltips.marketplaceFee}
value={
pricingType === 'dynamic'
? appConfig.publisherMarketPoolSwapFee
: appConfig.publisherMarketFixedSwapFee
? appConfig?.publisherMarketPoolSwapFee
: appConfig?.publisherMarketFixedSwapFee
}
/>
</div>

View File

@ -1,6 +1,6 @@
import Conversion from '@shared/Price/Conversion'
import { Field, useField, useFormikContext } from 'formik'
import React, { ReactElement } from 'react'
import React, { ReactElement, useEffect } from 'react'
import Input from '@shared/FormInput'
import Error from '@shared/FormInput/Error'
import PriceUnit from '@shared/Price/PriceUnit'

View File

@ -1,6 +1,5 @@
import React, { ReactElement, useEffect } from 'react'
import { useFormikContext } from 'formik'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import Tabs from '@shared/atoms/Tabs'
import { isValidNumber } from '@utils/numbers'
import Decimal from 'decimal.js'
@ -11,9 +10,10 @@ import Fixed from './Fixed'
import Free from './Free'
import content from '../../../../content/price.json'
import styles from './index.module.css'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function PricingFields(): ReactElement {
const { appConfig } = useSiteMetadata()
const { appConfig } = useMarketMetadata()
// Connect with main publish form
const { values, setFieldValue } = useFormikContext<FormPublishData>()

View File

@ -17,7 +17,6 @@ import {
import { mapTimeoutStringToSeconds } from '@utils/ddo'
import { generateNftCreateData } from '@utils/nft'
import { getEncryptedFiles } from '@utils/provider'
import { getSiteMetadata } from '@utils/siteConfig'
import Decimal from 'decimal.js'
import slugify from 'slugify'
import Web3 from 'web3'
@ -26,6 +25,12 @@ import {
MetadataAlgorithmContainer
} from './_constants'
import { FormPublishData } from './_types'
import {
marketFeeAddress,
publisherMarketOrderFee,
publisherMarketPoolSwapFee,
publisherMarketFixedSwapFee
} from '../../../app.config'
export function getFieldContent(
fieldName: string,
@ -201,7 +206,6 @@ export async function createTokensAndPricing(
accountId,
values.metadata.transferable
)
const { appConfig } = getSiteMetadata()
LoggerInstance.log('[publish] Creating NFT with metadata', nftCreateData)
// TODO: cap is hardcoded for now to 1000, this needs to be discussed at some point
@ -209,9 +213,9 @@ export async function createTokensAndPricing(
templateIndex: values.pricing.type === 'dynamic' ? 1 : 2,
minter: accountId,
paymentCollector: accountId,
mpFeeAddress: appConfig.marketFeeAddress,
mpFeeAddress: marketFeeAddress,
feeToken: config.oceanTokenAddress,
feeAmount: appConfig.publisherMarketOrderFee,
feeAmount: publisherMarketOrderFee,
// max number
cap: '115792089237316195423570985008687907853269984665640564039457',
name: values.services[0].dataTokenOptions.name,
@ -234,7 +238,7 @@ export async function createTokensAndPricing(
baseTokenAddress: config.oceanTokenAddress,
baseTokenSender: config.erc721FactoryAddress,
publisherAddress: accountId,
marketFeeCollector: appConfig.marketFeeAddress,
marketFeeCollector: marketFeeAddress,
poolTemplateAddress: config.poolTemplateAddress,
rate: new Decimal(1).div(values.pricing.price).toString(),
baseTokenDecimals: 18,
@ -242,7 +246,7 @@ export async function createTokensAndPricing(
vestedBlocks: 2726000,
initialBaseTokenLiquidity: values.pricing.amountOcean.toString(),
swapFeeLiquidityProvider: (values.pricing.swapFee / 100).toString(),
swapFeeMarketRunner: appConfig.publisherMarketPoolSwapFee
swapFeeMarketRunner: publisherMarketPoolSwapFee
}
LoggerInstance.log(
@ -286,11 +290,11 @@ export async function createTokensAndPricing(
fixedRateAddress: config.fixedRateExchangeAddress,
baseTokenAddress: config.oceanTokenAddress,
owner: accountId,
marketFeeCollector: appConfig.marketFeeAddress,
marketFeeCollector: marketFeeAddress,
baseTokenDecimals: 18,
datatokenDecimals: 18,
fixedRate: values.pricing.price.toString(),
marketFee: appConfig.publisherMarketFixedSwapFee,
marketFee: publisherMarketFixedSwapFee,
withMint: true
}

View File

@ -2,6 +2,7 @@ import { MAX_DECIMALS } from '@utils/constants'
import { initialValues } from './_constants'
import * as Yup from 'yup'
import Decimal from 'decimal.js'
import { getMaxDecimalsValidation } from '@utils/numbers'
// TODO: conditional validation
// e.g. when algo is selected, Docker image is required
@ -63,10 +64,6 @@ const validationService = {
})
}
const maxDecimalsValidation = new RegExp(
'^\\d+(\\.\\d{1,' + MAX_DECIMALS + '})?$'
)
const validationPricing = {
type: Yup.string()
.matches(/fixed|dynamic|free/g, { excludeEmptyString: true })
@ -82,7 +79,7 @@ const validationPricing = {
.test(
'maxDigitsAfterDecimal',
`Must have maximum ${MAX_DECIMALS} decimal digits`,
(param) => maxDecimalsValidation.test(param?.toString())
(param) => getMaxDecimalsValidation(MAX_DECIMALS).test(param?.toString())
)
.required('Required'),
amountDataToken: Yup.number().required('Required'),
@ -110,7 +107,7 @@ const validationPricing = {
.test(
'maxDigitsAfterDecimal',
`Must have maximum ${MAX_DECIMALS} decimal digits`,
(param) => maxDecimalsValidation.test(param?.toString())
(param) => getMaxDecimalsValidation(MAX_DECIMALS).test(param?.toString())
)
.required('Required'),
weightOnDataToken: Yup.string().required('Required'),
@ -121,7 +118,7 @@ const validationPricing = {
.test(
'maxDigitsAfterDecimal',
`Must have maximum ${MAX_DECIMALS} decimal digits`,
(param) => maxDecimalsValidation.test(param?.toString())
(param) => getMaxDecimalsValidation(MAX_DECIMALS).test(param?.toString())
)
.required('Required')
}

View File

@ -10,20 +10,25 @@ import App from 'src/components/App'
import '@oceanprotocol/typographies/css/ocean-typo.css'
import '../stylesGlobal/styles.css'
import Decimal from 'decimal.js'
import MarketMetadataProvider from '@context/MarketMetadata'
function MyApp({ Component, pageProps }: AppProps): ReactElement {
Decimal.set({ rounding: 1 })
return (
<Web3Provider>
<UrqlProvider>
<UserPreferencesProvider>
<PricesProvider>
<ConsentProvider>
<App>
<Component {...pageProps} />
</App>
</ConsentProvider>
</PricesProvider>
</UserPreferencesProvider>
<MarketMetadataProvider>
<UserPreferencesProvider>
<PricesProvider>
<ConsentProvider>
<App>
<Component {...pageProps} />
</App>
</ConsentProvider>
</PricesProvider>
</UserPreferencesProvider>
</MarketMetadataProvider>
</UrqlProvider>
</Web3Provider>
)

View File

@ -1,17 +1,17 @@
import React, { ReactElement } from 'react'
import Home from '../components/Home'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import Page from '@shared/Page'
import { useRouter } from 'next/router'
import { useMarketMetadata } from '@context/MarketMetadata'
export default function PageHome(): ReactElement {
const { siteTitle, siteTagline } = useSiteMetadata()
const { siteContent } = useMarketMetadata()
const router = useRouter()
return (
<Page
title={siteTitle}
description={siteTagline}
title={siteContent?.siteTitle}
description={siteContent?.siteTagline}
uri={router.route}
headerCenter
>