perps: modify perps, update contracts, interest, realized profits (#783)

This commit is contained in:
Bob van der Helm 2024-02-08 15:25:41 +01:00 committed by GitHub
parent 9762aa7cd0
commit 6d5e7c7325
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 711 additions and 508 deletions

View File

@ -16,7 +16,7 @@ export default function DropDownButton(props: Props) {
content={<DropDown closeMenu={() => toggleIsOpen(false)} {...props} />}
type='info'
placement='bottom'
contentClassName='!bg-white/10 border border-white/20 backdrop-blur-xl !p-0'
contentClassName='!bg-white/10 backdrop-blur-xl !p-0'
interactive
hideArrow
visible={isOpen}

View File

@ -1,3 +1,4 @@
import { Row } from '@tanstack/react-table'
import { useMemo } from 'react'
import { FormattedNumber } from 'components/common/FormattedNumber'
@ -18,6 +19,10 @@ export const SIZE_META = {
),
}
export const sizeSortingFn = (a: Row<PerpPositionRow>, b: Row<PerpPositionRow>): number => {
return a.original.amount.abs().minus(b.original.amount.abs()).toNumber()
}
type Props = {
amount: BigNumber
asset: Asset
@ -27,7 +32,7 @@ export default function Size(props: Props) {
const price = usePrice(props.asset.denom)
const amount = useMemo(
() => demagnify(props.amount.toString(), props.asset),
() => demagnify(props.amount.abs().toString(), props.asset),
[props.asset, props.amount],
)
const value = useMemo(() => price.times(amount).toNumber(), [amount, price])

View File

@ -6,7 +6,7 @@ import Leverage, { LEVERAGE_META } from 'components/perps/BalancesTable/Columns/
import Manage, { MANAGE_META } from 'components/perps/BalancesTable/Columns/Manage'
import { PERP_NAME_META, PerpName } from 'components/perps/BalancesTable/Columns/PerpName'
import PnL, { PNL_META } from 'components/perps/BalancesTable/Columns/PnL'
import Size, { SIZE_META } from 'components/perps/BalancesTable/Columns/Size'
import Size, { SIZE_META, sizeSortingFn } from 'components/perps/BalancesTable/Columns/Size'
import TradeDirection, {
PERP_TYPE_META,
} from 'components/perps/BalancesTable/Columns/TradeDirection'
@ -25,6 +25,7 @@ export default function usePerpsBalancesTable() {
{
...SIZE_META,
cell: ({ row }) => <Size amount={row.original.amount} asset={row.original.asset} />,
sortingFn: sizeSortingFn,
},
{
...LEVERAGE_META,

View File

@ -132,6 +132,7 @@ export function PerpsModule() {
previousTradeDirection={previousTradeDirection}
previousLeverage={previousLeverage}
hasActivePosition={hasActivePosition}
onTxExecuted={() => setAmount(BN_ZERO)}
/>
</Card>
)

View File

@ -8,6 +8,7 @@ import SummaryLine from 'components/common/SummaryLine'
import Text from 'components/common/Text'
import TradeDirection from 'components/perps/BalancesTable/Columns/TradeDirection'
import OpeningFee from 'components/perps/Module/OpeningFee'
import { BN_ZERO } from 'constants/math'
import useCurrentAccount from 'hooks/accounts/useCurrentAccount'
import useStore from 'store'
import { BNCoin } from 'types/classes/BNCoin'
@ -18,37 +19,56 @@ type Props = {
amount: BigNumber
tradeDirection: TradeDirection
asset: Asset
previousAmount?: BigNumber
previousAmount?: BigNumber | null
previousTradeDirection?: 'long' | 'short'
previousLeverage?: number
previousLeverage?: number | null
hasActivePosition: boolean
onTxExecuted: () => void
}
export default function PerpsSummary(props: Props) {
const openPerpPosition = useStore((s) => s.openPerpPosition)
const modifyPerpPosition = useStore((s) => s.modifyPerpPosition)
const closePerpPosition = useStore((s) => s.closePerpPosition)
const currentAccount = useCurrentAccount()
const onConfirm = useCallback(async () => {
if (!currentAccount) return
await openPerpPosition({
accountId: currentAccount.id,
coin: BNCoin.fromDenomAndBigNumber(
props.asset.denom,
props.amount.times(props.tradeDirection === 'short' ? -1 : 1),
),
})
}, [currentAccount, openPerpPosition, props.amount, props.asset.denom, props.tradeDirection])
const disabled = useMemo(
() =>
(props.previousAmount && props.previousAmount.isEqualTo(props.amount)) ||
props.amount.isZero(),
const newAmount = useMemo(
() => (props.previousAmount ?? BN_ZERO).plus(props.amount),
[props.amount, props.previousAmount],
)
const onConfirm = useCallback(async () => {
if (!currentAccount) return
if (props.previousAmount && newAmount.isZero()) {
await closePerpPosition({
accountId: currentAccount.id,
denom: props.asset.denom,
})
return props.onTxExecuted()
}
if (props.previousAmount && newAmount) {
await modifyPerpPosition({
accountId: currentAccount.id,
coin: BNCoin.fromDenomAndBigNumber(props.asset.denom, newAmount),
changeDirection: props.previousAmount.isNegative() !== newAmount.isNegative(),
})
return props.onTxExecuted()
}
await openPerpPosition({
accountId: currentAccount.id,
coin: BNCoin.fromDenomAndBigNumber(props.asset.denom, props.amount),
})
return props.onTxExecuted()
}, [closePerpPosition, currentAccount, modifyPerpPosition, newAmount, openPerpPosition, props])
const disabled = useMemo(() => props.amount.isZero(), [props.amount])
return (
<div className='border border-white/10 rounded-sm bg-white/5'>
<ManageSummary {...props} />
<ManageSummary {...props} newAmount={newAmount} />
<div className='py-4 px-3 flex flex-col gap-1'>
<Text size='xs' className='font-bold mb-2'>
Summary
@ -67,9 +87,9 @@ export default function PerpsSummary(props: Props) {
)
}
function ManageSummary(props: Props) {
function ManageSummary(props: Props & { newAmount: BigNumber }) {
const showTradeDirection =
props.previousTradeDirection && props.previousTradeDirection !== props.tradeDirection
props.previousAmount && props.previousAmount.isNegative() !== props.newAmount.isNegative()
const showAmount = !props.amount.isZero() && props.previousAmount
const showLeverage =
props.previousLeverage &&
@ -84,7 +104,13 @@ function ManageSummary(props: Props) {
Your new position
</Text>
{showTradeDirection && props.previousTradeDirection && (
{props.newAmount.isZero() && (
<Text size='xs' className='text-white/40 mb-1'>
Your position will be closed
</Text>
)}
{showTradeDirection && props.previousTradeDirection && !props.newAmount.isZero() && (
<SummaryLine label='Side' contentClassName='flex gap-1'>
<TradeDirection tradeDirection={props.previousTradeDirection} />
<ArrowRight width={16} />
@ -92,13 +118,15 @@ function ManageSummary(props: Props) {
</SummaryLine>
)}
{showAmount && props.previousAmount && (
{showAmount && props.newAmount && props.previousAmount && !props.newAmount.isZero() && (
<SummaryLine label='Size' contentClassName='flex gap-1'>
<AssetAmount asset={props.asset} amount={props.previousAmount.abs().toNumber()} />
<ArrowRight
width={16}
className={classNames(
props.previousAmount.isGreaterThan(props.amount) ? 'text-error' : 'text-success',
props.previousAmount.abs().isGreaterThan(props.newAmount)
? 'text-error'
: 'text-success',
)}
/>
<AssetAmount

View File

@ -29,11 +29,7 @@ export default function usePerpsModule(amount: BigNumber | null) {
return getAccountNetValue(account, prices, assets)
}, [account, assets, prices])
const previousAmount = useMemo(
() =>
(perpPosition?.amount ?? BN_ZERO).times(perpPosition?.tradeDirection === 'short' ? -1 : 1),
[perpPosition?.amount, perpPosition?.tradeDirection],
)
const previousAmount = useMemo(() => perpPosition?.amount ?? BN_ZERO, [perpPosition?.amount])
const previousTradeDirection = useMemo(
() => perpPosition?.tradeDirection || 'long',
[perpPosition?.tradeDirection],
@ -41,18 +37,16 @@ export default function usePerpsModule(amount: BigNumber | null) {
const previousLeverage = useMemo(
() =>
price
.times(demagnify(previousAmount.abs(), perpsAsset))
.div(accountNetValue)
.plus(1)
.toNumber(),
previousAmount
? price.times(demagnify(previousAmount, perpsAsset)).div(accountNetValue).plus(1).toNumber()
: null,
[accountNetValue, perpsAsset, previousAmount, price],
)
const leverage = useMemo(
() =>
price
.times(demagnify(previousAmount.plus(amount ?? BN_ZERO).abs(), perpsAsset))
.times(demagnify(previousAmount.plus(amount ?? BN_ZERO), perpsAsset))
.div(accountNetValue)
.plus(1)
.toNumber(),

View File

@ -21,14 +21,14 @@ const Pion1: ChainConfig = {
id: ChainInfoID.Pion1,
name: 'Neutron Testnet',
contracts: {
redBank: 'neutron1u3fmnnd3q9dkx2sccjgs2hfdp7sndkw5f37ug64zj0zgdm6dgjxq4njrnc',
incentives: 'neutron18ere5chtsdswna8re75sldzhw0ccrmuff57cfh63060dnvflqswsxpzlm9',
oracle: 'neutron1nua7c2esr5d8f6jfkylsd4pjywwlf0snj8gtxkp6k6f5jxa32hxqq2lcm7',
swapper: 'neutron1me0pspfhkphe2mw7ja2f2fqnh0z5x30jj5t80jgd7p6y9swwk06snh7mun',
params: 'neutron1ku3eccj8a49atmgkv4g8r2zgy62l93xy224ls44lfvdexh5xfqds97rrz3',
creditManager: 'neutron1zjuschuar2e9cugj84hmun4r93mzkan6qy4x4ee5geguh3lmrdnsnq5s9z',
accountNft: 'neutron12wrdnp0edn7xqleak4khn265xrtkk732ext4d3yeyfz2gcup3e4scmmrj3',
perps: 'neutron1zlj4l4h55wmrctm3ete6sqjvucujgcpa7r9m0ex6pcgdngaqa0pss93jla',
redBank: 'neutron1gpv59ff87mfvx8s3fn5ku3l8dn94fkj4q37sruhwfl0zzgjsejqs3xejyj',
incentives: 'neutron1au78lscqqh77ghvl6eq2d58vy439q0gprhz0sc5q4r9svh63hquqtwlrsw',
oracle: 'neutron1z44naqtpn20z5yws7updsgcplm7tcfkcn67uejvc0l7n8hy6vupq0894qs',
swapper: 'neutron1td4dn53k7ythdj8ah3xv5p66swq3sy2a9jzq4yrue8aa4dvwacrs7dachf',
params: 'neutron16l9j74q6ht9ycd37qxt6tz83l3r3cwec4qu9r5mkd66kcve23ywspjqhjp',
creditManager: 'neutron1swud86k6acvpjfn68cv6tz3h7z72nz395d7y5e3yxknrc8yl9faqxn5jjw',
accountNft: 'neutron1apus79ka5v30wmwdxzzapprrzxxw6mz0hc0uk3g030t0m5f0asuq8x3ldf',
perps: 'neutron1ssnc38h40fu0d2et8f38z83ealgugh06r4anqa6dn6hlz6syqaqsmj6zcy',
pyth: 'neutron15ldst8t80982akgr8w8ekcytejzkmfpgdkeq4xgtge48qs7435jqp87u3t',
},
endpoints: {

View File

@ -1,6 +1,5 @@
import useSWR from 'swr'
import { BN_ZERO } from 'constants/math'
import usePerpsAsset from 'hooks/perps/usePerpsAsset'
import useChainConfig from 'hooks/useChainConfig'
import useClients from 'hooks/useClients'
@ -27,8 +26,8 @@ async function getPerpsMarket(clients: ContractClients, asset: Asset) {
fundingRate: BN(denomState.rate as any),
asset: asset,
openInterest: {
long: BN_ZERO,
short: BN_ZERO,
long: BN(denomState.long_oi),
short: BN(denomState.short_oi),
},
} as PerpsMarket
}

View File

@ -246,6 +246,11 @@ export function useUpdatedAccount(account?: Account) {
const simulatePerps = useCallback(
(position: PerpsPosition) => {
if (!account) return
if (position.amount.isZero()) {
return addPerps(undefined)
}
addPerps(position)
},
[account, addPerps],

View File

@ -126,11 +126,18 @@ export default function createBroadcastSlice(
})
break
case 'close-perp':
// TODO: [Perps] Elaborate on the message
toast.content.push({
coins: changes.deposits?.map((deposit) => deposit.toCoin()) ?? [],
coins: [],
text: 'Closed perp position',
})
break
case 'modify-perp':
toast.content.push({
coins: [],
text: 'Modified perp position',
})
break
case 'swap':
if (changes.debts) {
@ -995,6 +1002,57 @@ export default function createBroadcastSlice(
return response.then((response) => !!response.result)
},
modifyPerpPosition: async (options: {
accountId: string
coin: BNCoin
changeDirection: boolean
}) => {
const msg: CreditManagerExecuteMsg = {
update_credit_account: {
account_id: options.accountId,
actions: [
...(options.changeDirection
? [
{
close_perp: {
denom: options.coin.denom,
},
},
{
open_perp: options.coin.toSignedCoin(),
},
]
: [
{
modify_perp: {
denom: options.coin.denom,
new_size: options.coin.amount.toString() as any,
},
},
]),
],
},
}
const cmContract = get().chainConfig.contracts.creditManager
const response = get().executeMsg({
messages: [generateExecutionMessage(get().address, cmContract, msg, [])],
})
get().setToast({
response,
options: {
action: 'modify-perp',
target: 'account',
message: `Modified position to a ${formatAmountWithSymbol(options.coin.abs().toCoin(), get().chainConfig.assets)} ${options.coin.amount.isNegative() ? 'short' : 'long'}`,
accountId: options.accountId,
changes: { deposits: [options.coin] },
},
})
return response.then((response) => !!response.result)
},
getPythVaas: async () => {
const priceFeedIds = get()
.chainConfig.assets.filter((asset) => !!asset.pythPriceFeedId)

View File

@ -44,4 +44,8 @@ export class BNCoin {
size: this.amount.toString(),
}
}
abs() {
return BNCoin.fromDenomAndBigNumber(this.denom, this.amount.abs())
}
}

View File

@ -94,6 +94,12 @@ export type Action =
close_perp: {
denom: string
}
}
| {
modify_perp: {
denom: string
new_size: SignedDecimal
}
}
| {
enter_vault: {
@ -274,6 +280,13 @@ export type CallbackMsg =
account_id: string
denom: string
}
}
| {
modify_perp: {
account_id: string
denom: string
new_size: SignedDecimal
}
}
| {
enter_vault: {
@ -605,11 +618,21 @@ export interface DebtAmount {
export interface PerpPosition {
base_denom: string
closing_fee_rate: Decimal
current_exec_price: Decimal
current_price: Decimal
denom: string
entry_exec_price: Decimal
entry_price: Decimal
pnl: PositionPnl
realised_pnl: RealizedPnlAmounts
size: SignedDecimal
unrealised_pnl: PositionPnl
}
export interface RealizedPnlAmounts {
accrued_funding: SignedDecimal
closing_fee: SignedDecimal
opening_fee: SignedDecimal
pnl: SignedDecimal
price_pnl: SignedDecimal
}
export interface PositionPnl {
coins: PnlCoins

View File

@ -64,6 +64,13 @@ export type ExecuteMsg =
account_id: string
denom: string
}
}
| {
modify_position: {
account_id: string
denom: string
new_size: SignedDecimal
}
}
export type OwnerUpdate =
| {
@ -152,6 +159,20 @@ export type QueryMsg =
denom: string
size: SignedDecimal
}
}
| {
denom_accounting: {
denom: string
}
}
| {
total_accounting: {}
}
| {
denom_realized_pnl_for_account: {
account_id: string
denom: string
}
}
export interface ConfigForString {
base_denom: string
@ -164,6 +185,31 @@ export interface ConfigForString {
oracle: OracleBaseForString
params: ParamsBaseForString
}
export interface Accounting {
balance: Balance
cash_flow: CashFlow
withdrawal_balance: Balance
}
export interface Balance {
accrued_funding: SignedDecimal
closing_fee: SignedDecimal
opening_fee: SignedDecimal
price_pnl: SignedDecimal
total: SignedDecimal
}
export interface CashFlow {
accrued_funding: SignedDecimal
closing_fee: SignedDecimal
opening_fee: SignedDecimal
price_pnl: SignedDecimal
}
export interface RealizedPnlAmounts {
accrued_funding: SignedDecimal
closing_fee: SignedDecimal
opening_fee: SignedDecimal
pnl: SignedDecimal
price_pnl: SignedDecimal
}
export interface DenomStateResponse {
denom: string
enabled: boolean
@ -203,13 +249,16 @@ export interface OwnerResponse {
export interface PerpDenomState {
denom: string
enabled: boolean
long_oi: Decimal
pnl_values: DenomPnlValues
rate: SignedDecimal
short_oi: Decimal
total_entry_cost: SignedDecimal
total_entry_funding: SignedDecimal
}
export interface DenomPnlValues {
accrued_funding: SignedDecimal
closing_fees: SignedDecimal
pnl: SignedDecimal
price_pnl: SignedDecimal
}
@ -228,11 +277,14 @@ export interface PositionResponse {
export interface PerpPosition {
base_denom: string
closing_fee_rate: Decimal
current_exec_price: Decimal
current_price: Decimal
denom: string
entry_exec_price: Decimal
entry_price: Decimal
pnl: PositionPnl
realised_pnl: RealizedPnlAmounts
size: SignedDecimal
unrealised_pnl: PositionPnl
}
export interface PositionPnl {
coins: PnlCoins

View File

@ -11,7 +11,6 @@ interface PerpsPosition {
baseDenom: string
tradeDirection: TradeDirection
amount: BigNumber
closingFee: BNCoin
pnl: PerpsPnL
entryPrice: BigNumber
}
@ -34,3 +33,16 @@ interface PerpsPnLCoins {
net: BNCoin
price: BNCoin
}
interface PerpsPnL {
net: BNCoin
realized: PerpsPnLCoins
unrealized: PerpsPnLCoins
}
interface PerpsPnLCoins {
fees: BNCoin
funding: BNCoin
net: BNCoin
price: BNCoin
}

View File

@ -72,6 +72,7 @@ interface HandleResponseProps {
| 'hls-staking'
| 'open-perp'
| 'close-perp'
| 'modify-perp'
lend?: boolean
accountId?: string
changes?: {
@ -123,6 +124,11 @@ interface BroadcastSlice {
lend: (options: { accountId: string; coin: BNCoin; isMax?: boolean }) => Promise<boolean>
closePerpPosition: (options: { accountId: string; denom: string }) => Promise<boolean>
openPerpPosition: (options: { accountId: string; coin: BNCoin }) => Promise<boolean>
modifyPerpPosition: (options: {
accountId: string
coin: BNCoin
changeDirection: boolean
}) => Promise<boolean>
reclaim: (options: { accountId: string; coin: BNCoin; isMax?: boolean }) => Promise<boolean>
repay: (options: {
accountId: string

View File

@ -248,7 +248,6 @@ export function cloneAccount(account: Account): Account {
perps: account.perps.map((perpPosition) => ({
...perpPosition,
amount: perpPosition.amount,
closingFee: perpPosition.closingFee,
pnl: perpPosition.pnl,
entryPrice: perpPosition.entryPrice,
tradeDirection: perpPosition.tradeDirection,

View File

@ -108,7 +108,7 @@ export function resolvePerpsPositions(
perpPositions: Positions['perps'],
prices: BNCoin[],
): PerpsPosition[] {
if (!perpPositions) return []
if (!perpPositions.length) return []
const basePrice =
prices.find((price) => price.denom === perpPositions[0].base_denom)?.amount ?? BN_ZERO
@ -116,36 +116,52 @@ export function resolvePerpsPositions(
return {
denom: position.denom,
baseDenom: position.base_denom,
amount: BN(position.size as any).abs(),
amount: BN(position.size as any), // Amount is negative for SHORT positions
tradeDirection: BN(position.size as any).isNegative() ? 'short' : 'long',
closingFee: BNCoin.fromCoin(position.pnl.coins.closing_fee),
// closingFee: BNCoin.fromCoin(position.pnl.coins.closing_fee),
pnl: {
net: BNCoin.fromDenomAndBigNumber(
position.base_denom,
BN(position.pnl.values.pnl as any).plus(BN_ZERO),
BN(position.unrealised_pnl.values.pnl as any)
.div(basePrice)
.plus(position.realised_pnl.pnl as any),
),
realized: {
net: BNCoin.fromDenomAndBigNumber(position.base_denom, BN_ZERO),
price: BNCoin.fromDenomAndBigNumber(position.base_denom, BN_ZERO),
funding: BNCoin.fromDenomAndBigNumber(position.base_denom, BN_ZERO),
fees: BNCoin.fromDenomAndBigNumber(position.base_denom, BN_ZERO.times(-1)),
net: BNCoin.fromDenomAndBigNumber(
position.base_denom,
BN(position.realised_pnl.pnl as any),
),
price: BNCoin.fromDenomAndBigNumber(
position.base_denom,
BN(position.realised_pnl.price_pnl as any),
),
funding: BNCoin.fromDenomAndBigNumber(
position.base_denom,
BN(position.realised_pnl.accrued_funding as any),
),
fees: BNCoin.fromDenomAndBigNumber(
position.base_denom,
BN(position.realised_pnl.closing_fee as any).plus(
position.realised_pnl.opening_fee as any,
),
),
},
unrealized: {
net: BNCoin.fromDenomAndBigNumber(
position.base_denom,
BN(position.pnl.values.pnl as any),
BN(position.unrealised_pnl.values.pnl as any).div(basePrice),
),
price: BNCoin.fromDenomAndBigNumber(
position.base_denom,
BN(position.pnl.values.price_pnl as any),
BN(position.unrealised_pnl.values.price_pnl as any).div(basePrice),
),
funding: BNCoin.fromDenomAndBigNumber(
position.base_denom,
BN(position.pnl.values.accrued_funding as any),
BN(position.unrealised_pnl.values.accrued_funding as any).div(basePrice),
),
fees: BNCoin.fromDenomAndBigNumber(
position.base_denom,
BN(position.pnl.values.closing_fee as any).times(-1),
BN(position.unrealised_pnl.values.closing_fee as any).div(basePrice),
),
},
},