Skip to content

Instantly share code, notes, and snippets.

@yornaath
Last active September 29, 2022 19:19
Show Gist options
  • Save yornaath/d887699333e414b6f27affc98a6c59ef to your computer and use it in GitHub Desktop.
Save yornaath/d887699333e414b6f27affc98a6c59ef to your computer and use it in GitHub Desktop.
import { Context, isIndexedData, isRpcData, isRpcSdk, Sdk } from '@zeitgeistpm/sdk'
import { RpcPoolPrices } from '@zeitgeistpm/sdk/dist/model/assets'
import { Pool } from '@zeitgeistpm/sdk/dist/model/swaps/pool'
import { Market } from '@zeitgeistpm/sdk/dist/model/types'
import { throws } from '@zeitgeistpm/utility/dist/error'
import { useEffect, useState } from 'react'
export const MarketComponent: React.FC<{ marketId: number; sdk: Partial<Sdk<Context>> }> = ({
sdk,
marketId,
}) => {
const [market, setMarket] = useState<Market<Context>>()
const [pool, setPool] = useState<Pool<Context>>()
const [prices, setPrices] = useState<RpcPoolPrices>([])
useEffect(() => {
if (isRpcSdk(sdk)) {
const marketsub = sdk.model.markets.get.$({ marketId }).subscribe(setMarket)
const poolsub = sdk.model.swaps.getPool.$({ marketId }).subscribe(setPool)
return () => {
marketsub.unsubscribe()
poolsub.unsubscribe()
}
}
}, [sdk])
useEffect(() => {
if (isRpcData(market)) {
market
.expand()
.then(market => market.unrightOr(throws))
.then(setMarket)
.catch(() => console.debug(`Missing metadata for market: ${market.marketId}`))
} else {
setMarket(market)
}
}, [market])
useEffect(() => {
if (pool && isRpcSdk(sdk)) {
const pricecessub = sdk.model.assets.poolPrices
.$({
pool: pool.poolId,
tail: new Date(Date.now() - ms('24 hours')),
})
.subscribe(setPrices)
return () => pricecessub.unsubscribe()
}
}, [market])
return (
<div style={{ display: 'grid', columnGap: '50px' }}>
{/*
Market and Pool can be either rpc data or indexed data.
Render accordingly.
*/}
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment