fix max add/remove liquidity (#1141)

* fix max add/remove liquidity

* fix graph liquidity

* small comment

* change liquidity graph to tvl, fix swap

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

* change label

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

* remove todo

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

* fix max remove liquidity
This commit is contained in:
mihaisc 2022-03-03 14:23:23 +02:00 committed by GitHub
parent 8a5bddbf6e
commit af60018500
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 47 additions and 37 deletions

View File

@ -41,6 +41,14 @@ export const poolDataQuery = gql`
baseTokenLiquidity
datatokenLiquidity
swapVolume
baseToken {
address
symbol
}
datatoken {
address
symbol
}
}
}
`

View File

@ -13,7 +13,7 @@ import DebugOutput from '@shared/DebugOutput'
import { useWeb3 } from '@context/Web3'
import { useAsset } from '@context/Asset'
import content from '../../../../../../content/price.json'
import { LoggerInstance, Pool } from '@oceanprotocol/lib'
import { calcMaxExactIn, LoggerInstance, Pool } from '@oceanprotocol/lib'
export interface FormAddLiquidity {
amount: string
@ -73,11 +73,12 @@ export default function Add({
try {
const poolInstance = new Pool(web3)
const amountMaxPool = await poolInstance.getReserve(
const poolReserve = await poolInstance.getReserve(
poolAddress,
tokenInAddress
)
const amountMaxPool = calcMaxExactIn(poolReserve)
const amountMax =
Number(balance.ocean) > Number(amountMaxPool)
? amountMaxPool
@ -100,7 +101,7 @@ export default function Add({
// Submit
async function handleAddLiquidity(amount: string, resetForm: () => void) {
const poolInstance = new Pool(web3)
const minPoolAmountOut = '0' // ? TODO: how to get?
const minPoolAmountOut = '0' // ? how to get? : you would get this value by using `calcPoolOutGivenSingleIn` and substracting slippage from that , like we don in trade. it is ok to be 0 here. We can change after we implement global slippage
try {
const result = await poolInstance.joinswapExternAmountIn(

View File

@ -13,9 +13,9 @@ import {
defaults
} from 'chart.js'
export declare type GraphType = 'liquidity' | 'price' | 'volume'
export declare type GraphType = 'tvl' | 'price' | 'volume'
export const graphTypes = ['Liquidity', 'Price', 'Volume']
export const graphTypes = ['TVL', 'Price', 'Volume']
// Chart.js global defaults
ChartJS.register(

View File

@ -13,6 +13,7 @@ import Nav from './Nav'
import { getOptions } from './_utils'
import { PoolData_poolSnapshots as PoolDataPoolSnapshots } from 'src/@types/subgraph/PoolData'
import { usePrices } from '@context/Prices'
import { MAX_DECIMALS } from '@utils/constants'
export default function Graph({
poolSnapshots
@ -24,7 +25,7 @@ export default function Graph({
const darkMode = useDarkMode(false, darkModeConfig)
const [options, setOptions] = useState<ChartOptions<any>>()
const [graphType, setGraphType] = useState<GraphType>('liquidity')
const [graphType, setGraphType] = useState<GraphType>('tvl')
const [graphData, setGraphData] = useState<ChartData<any>>()
//
@ -35,11 +36,7 @@ export default function Graph({
LoggerInstance.log('[pool graph] Fired getOptions().')
const symbol =
graphType === 'liquidity'
? currency
: // TODO: remove any once baseToken works
// see https://github.com/oceanprotocol/ocean-subgraph/issues/312
(poolSnapshots[0] as any)?.baseToken?.symbol
graphType === 'tvl' ? currency : poolSnapshots[0]?.baseToken?.symbol
const options = getOptions(locale, darkMode.value, symbol)
setOptions(options)
}, [locale, darkMode.value, graphType, currency, poolSnapshots])
@ -52,32 +49,25 @@ export default function Graph({
const timestamps = poolSnapshots.map((item) => {
const date = new Date(item.date * 1000)
return `${date.toLocaleDateString(locale)} ${date.toLocaleTimeString(
locale,
{ hour: '2-digit', minute: '2-digit' }
)}`
return `${date.toLocaleDateString(locale)}`
})
let baseTokenLiquidityCumulative = '0'
const liquidityHistory = poolSnapshots.map((item) => {
const tvlHistory = poolSnapshots.map((item) => {
const conversionSpotPrice = prices[currency.toLowerCase()]
baseTokenLiquidityCumulative = new Decimal(baseTokenLiquidityCumulative)
.add(item.baseTokenLiquidity)
.mul(2) // double baseTokenLiquidity as we have 50/50 weight
const tvl = new Decimal(item.baseTokenLiquidity)
.mul(2)
.mul(conversionSpotPrice) // convert to user currency
.toString()
return baseTokenLiquidityCumulative
return tvl
})
const priceHistory = poolSnapshots.map((item) => item.spotPrice)
let volumeCumulative = '0'
const volumeHistory = poolSnapshots.map((item) => {
volumeCumulative = new Decimal(volumeCumulative)
.add(item.swapVolume)
const volume = new Decimal(item.swapVolume)
.toDecimalPlaces(MAX_DECIMALS)
.toString()
return volumeCumulative
return volume
})
let data
@ -89,7 +79,7 @@ export default function Graph({
data = volumeHistory
break
default:
data = liquidityHistory
data = tvlHistory
break
}

View File

@ -9,11 +9,10 @@ import styles from './index.module.css'
import Header from '../Header'
import { toast } from 'react-toastify'
import Actions from '../Actions'
import { LoggerInstance, Pool } from '@oceanprotocol/lib'
import { LoggerInstance, Pool, calcMaxExactOut } from '@oceanprotocol/lib'
import Token from '../Token'
import FormHelp from '@shared/FormInput/Help'
import Button from '@shared/atoms/Button'
import { getMaxPercentRemove } from '../utils'
import debounce from 'lodash.debounce'
import UserLiquidity from '../../UserLiquidity'
import InputElement from '@shared/FormInput/InputElement'
@ -77,16 +76,27 @@ export default function Remove({
}
}
// TODO: Get and set max percentage
useEffect(() => {
if (!accountId || !poolTokens) return
async function getMax() {
// const amountMaxPercent = await getMaxPercentRemove(poolAddress, poolTokens)
// setAmountMaxPercent(amountMaxPercent)
const maxTokensToRemoveFromPool = calcMaxExactOut(totalPoolTokens)
const poolTokensDecimal = new Decimal(poolTokens)
const maxTokensToRemoveForUser = maxTokensToRemoveFromPool.greaterThan(
poolTokensDecimal
)
? poolTokensDecimal
: maxTokensToRemoveFromPool
const maxPercent = new Decimal(100)
.mul(maxTokensToRemoveForUser)
.div(poolTokensDecimal)
setAmountMaxPercent(
maxPercent.toDecimalPlaces(0, Decimal.ROUND_DOWN).toString()
)
}
getMax()
}, [accountId, poolAddress, poolTokens])
}, [accountId, poolAddress, poolTokens, totalPoolTokens])
const getValues = useRef(
debounce(async (newAmountPoolShares) => {
@ -188,7 +198,7 @@ export default function Remove({
</div> */}
</div>
<div className={styles.slippage}>
<strong>Expected price impact</strong>
<strong>Slippage Tolerance</strong>
<InputElement
name="slippage"
type="select"

View File

@ -94,7 +94,7 @@ export default function Pool(): ReactElement {
<TokenList
title={
<>
Your Liquidity
Your Value Locked
<Tooltip
content={content.pool.tooltips.liquidity.replace(
'SWAPFEE',

View File

@ -211,7 +211,8 @@ export async function createTokensAndPricing(
mpFeeAddress: appConfig.marketFeeAddress,
feeToken: config.oceanTokenAddress,
feeAmount: appConfig.publisherMarketOrderFee,
cap: '1000',
// max number
cap: '115792089237316195423570985008687907853269984665640564039457',
name: values.services[0].dataTokenOptions.name,
symbol: values.services[0].dataTokenOptions.symbol
}