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

migrate most components using GraphQL queries

This commit is contained in:
Matthias Kretschmann 2022-01-13 22:03:36 +00:00
parent d78676fa3b
commit 68ad4cc160
Signed by: m
GPG Key ID: 606EEEF3C479A91F
7 changed files with 94 additions and 106 deletions

View File

@ -226,7 +226,7 @@ function ProfileProvider({
for (let i = 0; i < tokenOrders?.length; i++) { for (let i = 0; i < tokenOrders?.length; i++) {
const did = web3.utils const did = web3.utils
.toChecksumAddress(tokenOrders[i].datatokenId.address) .toChecksumAddress(tokenOrders[i].token.address)
.replace('0x', 'did:op:') .replace('0x', 'did:op:')
didList.push(did) didList.push(did)
} }

View File

@ -6,7 +6,7 @@ import {
import { AssetSelectionAsset } from '@shared/FormFields/AssetSelection' import { AssetSelectionAsset } from '@shared/FormFields/AssetSelection'
import { PriceList, getAssetsPriceList } from './subgraph' import { PriceList, getAssetsPriceList } from './subgraph'
import axios, { CancelToken, AxiosResponse } from 'axios' import axios, { CancelToken, AxiosResponse } from 'axios'
import { OrdersData_tokenOrders as OrdersData } from '../@types/apollo/OrdersData' import { OrdersData_orders as OrdersData } from '../@types/apollo/OrdersData'
import { metadataCacheUri } from '../../app.config' import { metadataCacheUri } from '../../app.config'
import { import {
SortDirectionOptions, SortDirectionOptions,
@ -348,16 +348,16 @@ export async function getDownloadAssets(
const downloadedAssets: DownloadedAsset[] = result.results const downloadedAssets: DownloadedAsset[] = result.results
.map((ddo) => { .map((ddo) => {
const order = tokenOrders.find( const order = tokenOrders.find(
({ datatokenId }) => ({ token }) =>
datatokenId?.address.toLowerCase() === token?.address.toLowerCase() ===
ddo.services[0].datatokenAddress.toLowerCase() ddo.services[0].datatokenAddress.toLowerCase()
) )
return { return {
ddo, ddo,
networkId: ddo.chainId, networkId: ddo.chainId,
dtSymbol: order?.datatokenId?.symbol, dtSymbol: order?.token?.symbol,
timestamp: order?.timestamp timestamp: order?.createdTimestamp
} }
}) })
.sort((a, b) => b.timestamp - a.timestamp) .sort((a, b) => b.timestamp - a.timestamp)

View File

@ -5,62 +5,65 @@ import ExplorerLink from '@shared/ExplorerLink'
import { formatPrice } from '@shared/Price/PriceUnit' import { formatPrice } from '@shared/Price/PriceUnit'
import styles from './Title.module.css' import styles from './Title.module.css'
async function getTitle(row: PoolTransaction, locale: string) { // TODO: it seems we are missing a way in PoolTransaction to figure out
let title = '' // if e.g. in a swap token got in or out of the pool.
switch (row.event) {
case 'swap': {
const inToken = row.tokens.filter((x) => x.type === 'in')[0]
const inTokenSymbol = inToken?.poolToken.symbol
const outToken = row.tokens.filter((x) => x.type === 'out')[0]
const outTokenSymbol = outToken?.poolToken.symbol
title += `Swap ${formatPrice(
Math.abs(inToken?.value).toString(),
locale
)}${inTokenSymbol} for ${formatPrice(
Math.abs(outToken?.value).toString(),
locale
)}${outTokenSymbol}`
break // async function getTitle(row: PoolTransaction, locale: string) {
} // let title = ''
case 'setup': { // switch (row.type) {
const firstToken = row.tokens.filter( // case 'SWAP': {
(x) => // const inToken = row.tokens.filter((x) => x.type === 'in')[0]
x.tokenAddress.toLowerCase() !== // const inTokenSymbol = inToken?.poolToken.symbol
row.poolAddress.datatokenAddress.toLowerCase() // const outToken = row.tokens.filter((x) => x.type === 'out')[0]
)[0] // const outTokenSymbol = outToken?.poolToken.symbol
const firstTokenSymbol = firstToken?.poolToken.symbol // title += `Swap ${formatPrice(
const secondToken = row.tokens.filter( // Math.abs(inToken?.value).toString(),
(x) => // locale
x.tokenAddress.toLowerCase() === // )}${inTokenSymbol} for ${formatPrice(
row.poolAddress.datatokenAddress.toLowerCase() // Math.abs(outToken?.value).toString(),
)[0] // locale
const secondTokenSymbol = secondToken?.poolToken.symbol // )}${outTokenSymbol}`
title += `Create pool with ${formatPrice(
Math.abs(firstToken?.value).toString(),
locale
)}${firstTokenSymbol} and ${formatPrice(
Math.abs(secondToken?.value).toString(),
locale
)}${secondTokenSymbol}`
break
}
case 'join':
case 'exit': {
for (let i = 0; i < row.tokens.length; i++) {
const tokenSymbol = row.tokens[i].poolToken.symbol
if (i > 0) title += '\n'
title += `${row.event === 'join' ? 'Add' : 'Remove'} ${formatPrice(
Math.abs(row.tokens[i].value).toString(),
locale
)}${tokenSymbol}`
}
break
}
}
return title // break
} // }
// case 'SETUP': {
// const firstToken = row.tokens.filter(
// (x) =>
// x.tokenAddress.toLowerCase() !==
// row.pool.id.datatoken.address.toLowerCase()
// )[0]
// const firstTokenSymbol = firstToken?.poolToken.symbol
// const secondToken = row.tokens.filter(
// (x) =>
// x.tokenAddress.toLowerCase() ===
// row.pool.id.datatokenAddress.toLowerCase()
// )[0]
// const secondTokenSymbol = secondToken?.poolToken.symbol
// title += `Create pool with ${formatPrice(
// Math.abs(firstToken?.value).toString(),
// locale
// )}${firstTokenSymbol} and ${formatPrice(
// Math.abs(secondToken?.value).toString(),
// locale
// )}${secondTokenSymbol}`
// break
// }
// case 'JOIN':
// case 'EXIT': {
// for (let i = 0; i < row.tokens.length; i++) {
// const tokenSymbol = row.tokens[i].poolToken.symbol
// if (i > 0) title += '\n'
// title += `${row.type === 'JOIN' ? 'Add' : 'Remove'} ${formatPrice(
// Math.abs(row.tokens[i].value).toString(),
// locale
// )}${tokenSymbol}`
// }
// break
// }
// }
// return title
// }
export default function Title({ row }: { row: PoolTransaction }): ReactElement { export default function Title({ row }: { row: PoolTransaction }): ReactElement {
const [title, setTitle] = useState<string>() const [title, setTitle] = useState<string>()
@ -70,8 +73,8 @@ export default function Title({ row }: { row: PoolTransaction }): ReactElement {
if (!locale || !row) return if (!locale || !row) return
async function init() { async function init() {
const title = await getTitle(row, locale) // const title = await getTitle(row, locale)
setTitle(title) // setTitle(title)
} }
init() init()
}, [row, locale]) }, [row, locale])

View File

@ -133,7 +133,7 @@ export default function Pool(): ReactElement {
queryVariables, queryVariables,
queryContext queryContext
) )
return queryResult?.data.pool.shares[0]?.balance return queryResult?.data.pool.shares[0]?.shares
} }
function refetchLiquidity() { function refetchLiquidity() {

View File

@ -3,7 +3,7 @@ import { useAsset } from '@context/Asset'
import ExplorerLink from '@shared/ExplorerLink' import ExplorerLink from '@shared/ExplorerLink'
import Time from '@shared/atoms/Time' import Time from '@shared/atoms/Time'
import { gql, OperationContext, useQuery } from 'urql' import { gql, OperationContext, useQuery } from 'urql'
import { ReceiptData_datatokens_updates as ReceiptData } from '../../../@types/apollo/ReceiptData' import { ReceiptData_nftUpdates as ReceiptData } from '../../../@types/apollo/ReceiptData'
import { getQueryContext } from '@utils/subgraph' import { getQueryContext } from '@utils/subgraph'
import styles from './EditHistory.module.css' import styles from './EditHistory.module.css'

View File

@ -116,7 +116,7 @@ export default function MarketStats(): ReactElement {
setMainChainIds(mainChainIdsList) setMainChainIds(mainChainIdsList)
let newTotalValueLockedSum = 0 let newTotalValueLockedSum = 0
let newTotalOceanLiquiditySum = 0 // let newTotalOceanLiquiditySum = 0
let newPoolCountSum = 0 let newPoolCountSum = 0
for (const chainId of mainChainIdsList) { for (const chainId of mainChainIdsList) {
@ -141,26 +141,27 @@ export default function MarketStats(): ReactElement {
await setTotalValueLocked((prevState) => ({ await setTotalValueLocked((prevState) => ({
...prevState, ...prevState,
[chainId]: totalValueLocked [chainId]: totalLiquidity.value
}))
await setTotalOceanLiquidity((prevState) => ({
...prevState,
[chainId]: totalOceanLiquidity
})) }))
// TODO: how to get total OCEAN liquidity?
// await setTotalOceanLiquidity((prevState) => ({
// ...prevState,
// [chainId]: totalLiquidity
// }))
await setPoolCount((prevState) => ({ await setPoolCount((prevState) => ({
...prevState, ...prevState,
[chainId]: poolCount [chainId]: poolCount
})) }))
newTotalValueLockedSum += parseInt(totalValueLocked) newTotalValueLockedSum += parseInt(totalLiquidity.value)
newTotalOceanLiquiditySum += parseInt(totalOceanLiquidity) // newTotalOceanLiquiditySum += parseInt(totalOceanLiquidity)
newPoolCountSum += parseInt(poolCount) newPoolCountSum += parseInt(poolCount)
} catch (error) { } catch (error) {
LoggerInstance.error('Error fetchData: ', error.message) LoggerInstance.error('Error fetchData: ', error.message)
} }
} }
setTotalValueLockedSum(`${newTotalValueLockedSum}`) setTotalValueLockedSum(`${newTotalValueLockedSum}`)
setTotalOceanLiquiditySum(`${newTotalOceanLiquiditySum}`) // setTotalOceanLiquiditySum(`${newTotalOceanLiquiditySum}`)
setPoolCountSum(`${newPoolCountSum}`) setPoolCountSum(`${newPoolCountSum}`)
} }

View File

@ -3,10 +3,7 @@ import Table from '@shared/atoms/Table'
import Conversion from '@shared/Price/Conversion' import Conversion from '@shared/Price/Conversion'
import styles from './PoolShares.module.css' import styles from './PoolShares.module.css'
import AssetTitle from '@shared/AssetList/AssetListTitle' import AssetTitle from '@shared/AssetList/AssetListTitle'
import { import { PoolShares_poolShares as PoolShare } from '../../../@types/apollo/PoolShares'
PoolShares_poolShares as PoolShare,
PoolShares_poolShares_poolId_tokens as PoolSharePoolIdTokens
} from '../../../@types/apollo/PoolShares'
import web3 from 'web3' import web3 from 'web3'
import Token from '../../Asset/AssetActions/Pool/Token' import Token from '../../Asset/AssetActions/Pool/Token'
import { calculateUserLiquidity } from '@utils/subgraph' import { calculateUserLiquidity } from '@utils/subgraph'
@ -33,46 +30,33 @@ interface AssetPoolShare {
ddo: Asset ddo: Asset
} }
function findTokenByType(tokens: PoolSharePoolIdTokens[], type: string) {
const { symbol } = tokens.find((token) =>
type === 'datatoken'
? token.isDatatoken === true
: token.isDatatoken === false
)
return symbol
}
function Symbol({ tokens }: { tokens: PoolSharePoolIdTokens[] }) {
return <>{findTokenByType(tokens, 'datatoken')}</>
}
function Liquidity({ row, type }: { row: AssetPoolShare; type: string }) { function Liquidity({ row, type }: { row: AssetPoolShare; type: string }) {
let price = `` let price = ``
let oceanTokenBalance = '' let oceanTokenBalance = ''
let dataTokenBalance = '' let dataTokenBalance = ''
if (type === 'user') { if (type === 'user') {
price = `${row.userLiquidity}` price = `${row.userLiquidity}`
const userShare = row.poolShare.balance / row.poolShare.poolId.totalShares const userShare = row.poolShare.shares / row.poolShare.pool.totalShares
oceanTokenBalance = ( oceanTokenBalance = (
userShare * row.poolShare.poolId.oceanReserve userShare * row.poolShare.pool.baseTokenLiquidity
).toString() ).toString()
dataTokenBalance = ( dataTokenBalance = (
userShare * row.poolShare.poolId.datatokenReserve userShare * row.poolShare.pool.datatokenLiquidity
).toString() ).toString()
} }
if (type === 'pool') { if (type === 'pool') {
price = price =
isValidNumber(row.poolShare.poolId.oceanReserve) && isValidNumber(row.poolShare.pool.baseTokenLiquidity) &&
isValidNumber(row.poolShare.poolId.datatokenReserve) && isValidNumber(row.poolShare.pool.datatokenLiquidity) &&
isValidNumber(row.poolShare.poolId.spotPrice) isValidNumber(row.poolShare.pool.spotPrice)
? new Decimal(row.poolShare.poolId.datatokenReserve) ? new Decimal(row.poolShare.pool.datatokenLiquidity)
.mul(new Decimal(row.poolShare.poolId.spotPrice)) .mul(new Decimal(row.poolShare.pool.spotPrice))
.plus(row.poolShare.poolId.oceanReserve) .plus(row.poolShare.pool.baseTokenLiquidity)
.toString() .toString()
: '0' : '0'
oceanTokenBalance = row.poolShare.poolId.oceanReserve.toString() oceanTokenBalance = row.poolShare.pool.baseTokenLiquidity.toString()
dataTokenBalance = row.poolShare.poolId.datatokenReserve.toString() dataTokenBalance = row.poolShare.pool.datatokenLiquidity.toString()
} }
return ( return (
<div className={styles.userLiquidity}> <div className={styles.userLiquidity}>
@ -82,12 +66,12 @@ function Liquidity({ row, type }: { row: AssetPoolShare; type: string }) {
hideApproximateSymbol hideApproximateSymbol
/> />
<Token <Token
symbol={findTokenByType(row.poolShare.poolId.tokens, 'ocean')} symbol={row.poolShare.pool.baseToken.symbol}
balance={oceanTokenBalance} balance={oceanTokenBalance}
noIcon noIcon
/> />
<Token <Token
symbol={findTokenByType(row.poolShare.poolId.tokens, 'datatoken')} symbol={row.poolShare.pool.datatoken.symbol}
balance={dataTokenBalance} balance={dataTokenBalance}
noIcon noIcon
/> />
@ -112,7 +96,7 @@ const columns = [
{ {
name: 'Datatoken', name: 'Datatoken',
selector: function getSymbol(row: AssetPoolShare) { selector: function getSymbol(row: AssetPoolShare) {
return <Symbol tokens={row.poolShare.poolId.tokens} /> return <>{row.poolShare.pool.datatoken.symbol}</>
} }
}, },
{ {
@ -143,7 +127,7 @@ async function getPoolSharesAssets(
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
const did = web3.utils const did = web3.utils
.toChecksumAddress(data[i].poolId.datatokenAddress) .toChecksumAddress(data[i].pool.datatoken.address)
.replace('0x', 'did:op:') .replace('0x', 'did:op:')
didList.push(did) didList.push(did)
} }
@ -155,7 +139,7 @@ async function getPoolSharesAssets(
poolShare: data[i], poolShare: data[i],
userLiquidity: userLiquidity, userLiquidity: userLiquidity,
networkId: ddoList[i].chainId, networkId: ddoList[i].chainId,
createTime: data[i].poolId.createTime, createTime: data[i].pool.createdTimestamp,
ddo: ddoList[i] ddo: ddoList[i]
}) })
} }