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

@ -28,374 +28,387 @@ export interface InstantiateMsg {
}
export type ExecuteMsg =
| {
create_credit_account: AccountKind
}
create_credit_account: AccountKind
}
| {
update_credit_account: {
account_id: string
actions: Action[]
}
}
update_credit_account: {
account_id: string
actions: Action[]
}
}
| {
repay_from_wallet: {
account_id: string
}
}
repay_from_wallet: {
account_id: string
}
}
| {
update_config: {
updates: ConfigUpdates
}
}
update_config: {
updates: ConfigUpdates
}
}
| {
update_owner: OwnerUpdate
}
update_owner: OwnerUpdate
}
| {
update_nft_config: {
config?: NftConfigUpdates | null
ownership?: Action2 | null
}
}
update_nft_config: {
config?: NftConfigUpdates | null
ownership?: Action2 | null
}
}
| {
callback: CallbackMsg
}
callback: CallbackMsg
}
export type AccountKind = 'default' | 'high_levered_strategy'
export type Action =
| {
deposit: Coin
}
deposit: Coin
}
| {
withdraw: ActionCoin
}
withdraw: ActionCoin
}
| {
borrow: Coin
}
borrow: Coin
}
| {
lend: ActionCoin
}
lend: ActionCoin
}
| {
reclaim: ActionCoin
}
reclaim: ActionCoin
}
| {
claim_rewards: {}
}
claim_rewards: {}
}
| {
repay: {
coin: ActionCoin
recipient_account_id?: string | null
}
}
repay: {
coin: ActionCoin
recipient_account_id?: string | null
}
}
| {
open_perp: {
denom: string
size: SignedDecimal
}
}
open_perp: {
denom: string
size: SignedDecimal
}
}
| {
close_perp: {
denom: string
}
}
close_perp: {
denom: string
}
}
| {
enter_vault: {
coin: ActionCoin
vault: VaultBaseForString
}
}
modify_perp: {
denom: string
new_size: SignedDecimal
}
}
| {
exit_vault: {
amount: Uint128
vault: VaultBaseForString
}
}
enter_vault: {
coin: ActionCoin
vault: VaultBaseForString
}
}
| {
request_vault_unlock: {
amount: Uint128
vault: VaultBaseForString
}
}
exit_vault: {
amount: Uint128
vault: VaultBaseForString
}
}
| {
exit_vault_unlocked: {
id: number
vault: VaultBaseForString
}
}
request_vault_unlock: {
amount: Uint128
vault: VaultBaseForString
}
}
| {
liquidate: {
debt_coin: Coin
liquidatee_account_id: string
request: LiquidateRequestForVaultBaseForString
}
}
exit_vault_unlocked: {
id: number
vault: VaultBaseForString
}
}
| {
swap_exact_in: {
coin_in: ActionCoin
denom_out: string
slippage: Decimal
}
}
liquidate: {
debt_coin: Coin
liquidatee_account_id: string
request: LiquidateRequestForVaultBaseForString
}
}
| {
provide_liquidity: {
coins_in: ActionCoin[]
lp_token_out: string
slippage: Decimal
}
}
swap_exact_in: {
coin_in: ActionCoin
denom_out: string
slippage: Decimal
}
}
| {
withdraw_liquidity: {
lp_token: ActionCoin
slippage: Decimal
}
}
provide_liquidity: {
coins_in: ActionCoin[]
lp_token_out: string
slippage: Decimal
}
}
| {
refund_all_coin_balances: {}
}
withdraw_liquidity: {
lp_token: ActionCoin
slippage: Decimal
}
}
| {
refund_all_coin_balances: {}
}
export type ActionAmount =
| 'account_balance'
| {
exact: Uint128
}
exact: Uint128
}
export type LiquidateRequestForVaultBaseForString =
| {
deposit: string
}
deposit: string
}
| {
lend: string
}
lend: string
}
| {
vault: {
position_type: VaultPositionType
request_vault: VaultBaseForString
}
}
vault: {
position_type: VaultPositionType
request_vault: VaultBaseForString
}
}
export type VaultPositionType = 'u_n_l_o_c_k_e_d' | 'l_o_c_k_e_d' | 'u_n_l_o_c_k_i_n_g'
export type AccountNftBaseForString = string
export type PerpsBaseForString = string
export type OwnerUpdate =
| {
propose_new_owner: {
proposed: string
}
}
propose_new_owner: {
proposed: string
}
}
| 'clear_proposed'
| 'accept_proposed'
| 'abolish_owner_role'
| {
set_emergency_owner: {
emergency_owner: string
}
}
set_emergency_owner: {
emergency_owner: string
}
}
| 'clear_emergency_owner'
export type Action2 =
| {
transfer_ownership: {
expiry?: Expiration | null
new_owner: string
}
}
transfer_ownership: {
expiry?: Expiration | null
new_owner: string
}
}
| 'accept_ownership'
| 'renounce_ownership'
export type Expiration =
| {
at_height: number
}
at_height: number
}
| {
at_time: Timestamp
}
at_time: Timestamp
}
| {
never: {}
}
never: {}
}
export type Timestamp = Uint64
export type Uint64 = string
export type CallbackMsg =
| {
withdraw: {
account_id: string
coin: ActionCoin
recipient: Addr
}
}
withdraw: {
account_id: string
coin: ActionCoin
recipient: Addr
}
}
| {
borrow: {
account_id: string
coin: Coin
}
}
borrow: {
account_id: string
coin: Coin
}
}
| {
repay: {
account_id: string
coin: ActionCoin
}
}
repay: {
account_id: string
coin: ActionCoin
}
}
| {
repay_for_recipient: {
benefactor_account_id: string
coin: ActionCoin
recipient_account_id: string
}
}
repay_for_recipient: {
benefactor_account_id: string
coin: ActionCoin
recipient_account_id: string
}
}
| {
lend: {
account_id: string
coin: ActionCoin
}
}
lend: {
account_id: string
coin: ActionCoin
}
}
| {
reclaim: {
account_id: string
coin: ActionCoin
}
}
reclaim: {
account_id: string
coin: ActionCoin
}
}
| {
claim_rewards: {
account_id: string
recipient: Addr
}
}
claim_rewards: {
account_id: string
recipient: Addr
}
}
| {
assert_max_ltv: {
account_id: string
prev_health_state: HealthState
}
}
assert_max_ltv: {
account_id: string
prev_health_state: HealthState
}
}
| {
assert_deposit_caps: {
denoms: string[]
}
}
assert_deposit_caps: {
denoms: string[]
}
}
| {
open_perp: {
account_id: string
denom: string
size: SignedDecimal
}
}
open_perp: {
account_id: string
denom: string
size: SignedDecimal
}
}
| {
close_perp: {
account_id: string
denom: string
}
}
close_perp: {
account_id: string
denom: string
}
}
| {
enter_vault: {
account_id: string
coin: ActionCoin
vault: VaultBaseForAddr
}
}
modify_perp: {
account_id: string
denom: string
new_size: SignedDecimal
}
}
| {
exit_vault: {
account_id: string
amount: Uint128
vault: VaultBaseForAddr
}
}
enter_vault: {
account_id: string
coin: ActionCoin
vault: VaultBaseForAddr
}
}
| {
update_vault_coin_balance: {
account_id: string
previous_total_balance: Uint128
vault: VaultBaseForAddr
}
}
exit_vault: {
account_id: string
amount: Uint128
vault: VaultBaseForAddr
}
}
| {
request_vault_unlock: {
account_id: string
amount: Uint128
vault: VaultBaseForAddr
}
}
update_vault_coin_balance: {
account_id: string
previous_total_balance: Uint128
vault: VaultBaseForAddr
}
}
| {
exit_vault_unlocked: {
account_id: string
position_id: number
vault: VaultBaseForAddr
}
}
request_vault_unlock: {
account_id: string
amount: Uint128
vault: VaultBaseForAddr
}
}
| {
liquidate: {
debt_coin: Coin
liquidatee_account_id: string
liquidator_account_id: string
request: LiquidateRequestForVaultBaseForAddr
}
}
exit_vault_unlocked: {
account_id: string
position_id: number
vault: VaultBaseForAddr
}
}
| {
swap_exact_in: {
account_id: string
coin_in: ActionCoin
denom_out: string
slippage: Decimal
}
}
liquidate: {
debt_coin: Coin
liquidatee_account_id: string
liquidator_account_id: string
request: LiquidateRequestForVaultBaseForAddr
}
}
| {
update_coin_balance: {
account_id: string
change: ChangeExpected
previous_balance: Coin
}
}
swap_exact_in: {
account_id: string
coin_in: ActionCoin
denom_out: string
slippage: Decimal
}
}
| {
update_coin_balance_after_vault_liquidation: {
account_id: string
previous_balance: Coin
protocol_fee: Decimal
}
}
update_coin_balance: {
account_id: string
change: ChangeExpected
previous_balance: Coin
}
}
| {
provide_liquidity: {
account_id: string
coins_in: ActionCoin[]
lp_token_out: string
slippage: Decimal
}
}
update_coin_balance_after_vault_liquidation: {
account_id: string
previous_balance: Coin
protocol_fee: Decimal
}
}
| {
withdraw_liquidity: {
account_id: string
lp_token: ActionCoin
slippage: Decimal
}
}
provide_liquidity: {
account_id: string
coins_in: ActionCoin[]
lp_token_out: string
slippage: Decimal
}
}
| {
refund_all_coin_balances: {
account_id: string
}
}
withdraw_liquidity: {
account_id: string
lp_token: ActionCoin
slippage: Decimal
}
}
| {
assert_hls_rules: {
account_id: string
}
}
refund_all_coin_balances: {
account_id: string
}
}
| {
remove_reentrancy_guard: {}
}
assert_hls_rules: {
account_id: string
}
}
| {
send_rewards_to_addr: {
account_id: string
previous_balances: Coin[]
recipient: Addr
}
}
remove_reentrancy_guard: {}
}
| {
send_rewards_to_addr: {
account_id: string
previous_balances: Coin[]
recipient: Addr
}
}
export type Addr = string
export type HealthState =
| 'healthy'
| {
unhealthy: {
max_ltv_health_factor: Decimal
}
}
unhealthy: {
max_ltv_health_factor: Decimal
}
}
export type LiquidateRequestForVaultBaseForAddr =
| {
deposit: string
}
deposit: string
}
| {
lend: string
}
lend: string
}
| {
vault: {
position_type: VaultPositionType
request_vault: VaultBaseForAddr
}
}
vault: {
position_type: VaultPositionType
request_vault: VaultBaseForAddr
}
}
export type ChangeExpected = 'increase' | 'decrease'
export interface Coin {
amount: Uint128
@ -438,80 +451,80 @@ export interface VaultBaseForAddr {
}
export type QueryMsg =
| {
account_kind: {
account_id: string
}
}
account_kind: {
account_id: string
}
}
| {
accounts: {
limit?: number | null
owner: string
start_after?: string | null
}
}
accounts: {
limit?: number | null
owner: string
start_after?: string | null
}
}
| {
config: {}
}
config: {}
}
| {
vault_utilization: {
vault: VaultBaseForString
}
}
vault_utilization: {
vault: VaultBaseForString
}
}
| {
positions: {
account_id: string
}
}
positions: {
account_id: string
}
}
| {
all_coin_balances: {
limit?: number | null
start_after?: [string, string] | null
}
}
all_coin_balances: {
limit?: number | null
start_after?: [string, string] | null
}
}
| {
all_debt_shares: {
limit?: number | null
start_after?: [string, string] | null
}
}
all_debt_shares: {
limit?: number | null
start_after?: [string, string] | null
}
}
| {
total_debt_shares: string
}
total_debt_shares: string
}
| {
all_total_debt_shares: {
limit?: number | null
start_after?: string | null
}
}
all_total_debt_shares: {
limit?: number | null
start_after?: string | null
}
}
| {
all_vault_positions: {
limit?: number | null
start_after?: [string, string] | null
}
}
all_vault_positions: {
limit?: number | null
start_after?: [string, string] | null
}
}
| {
estimate_provide_liquidity: {
coins_in: Coin[]
lp_token_out: string
}
}
estimate_provide_liquidity: {
coins_in: Coin[]
lp_token_out: string
}
}
| {
estimate_withdraw_liquidity: {
lp_token: Coin
}
}
estimate_withdraw_liquidity: {
lp_token: Coin
}
}
| {
vault_position_value: {
vault_position: VaultPosition
}
}
vault_position_value: {
vault_position: VaultPosition
}
}
export type VaultPositionAmount =
| {
unlocked: VaultAmount
}
unlocked: VaultAmount
}
| {
locking: LockingVaultAmount
}
locking: LockingVaultAmount
}
export type VaultAmount = string
export type VaultAmount1 = string
export type UnlockingPositions = VaultUnlockingPosition[]
@ -584,11 +597,11 @@ export type ArrayOfCoin = Coin[]
export type PnL =
| 'break_even'
| {
profit: Coin
}
profit: Coin
}
| {
loss: Coin
}
loss: Coin
}
export interface Positions {
account_id: string
debts: DebtAmount[]
@ -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

@ -22,63 +22,70 @@ export interface InstantiateMsg {
}
export type ExecuteMsg =
| {
update_owner: OwnerUpdate
}
update_owner: OwnerUpdate
}
| {
init_denom: {
denom: string
max_funding_velocity: Decimal
skew_scale: Decimal
}
}
init_denom: {
denom: string
max_funding_velocity: Decimal
skew_scale: Decimal
}
}
| {
enable_denom: {
denom: string
}
}
enable_denom: {
denom: string
}
}
| {
disable_denom: {
denom: string
}
}
disable_denom: {
denom: string
}
}
| {
deposit: {}
}
deposit: {}
}
| {
unlock: {
shares: Uint128
}
}
unlock: {
shares: Uint128
}
}
| {
withdraw: {}
}
withdraw: {}
}
| {
open_position: {
account_id: string
denom: string
size: SignedDecimal
}
}
open_position: {
account_id: string
denom: string
size: SignedDecimal
}
}
| {
close_position: {
account_id: string
denom: string
}
}
close_position: {
account_id: string
denom: string
}
}
| {
modify_position: {
account_id: string
denom: string
new_size: SignedDecimal
}
}
export type OwnerUpdate =
| {
propose_new_owner: {
proposed: string
}
}
propose_new_owner: {
proposed: string
}
}
| 'clear_proposed'
| 'accept_proposed'
| 'abolish_owner_role'
| {
set_emergency_owner: {
emergency_owner: string
}
}
set_emergency_owner: {
emergency_owner: string
}
}
| 'clear_emergency_owner'
export interface SignedDecimal {
abs: Decimal
@ -87,72 +94,86 @@ export interface SignedDecimal {
}
export type QueryMsg =
| {
owner: {}
}
owner: {}
}
| {
config: {}
}
config: {}
}
| {
vault_state: {}
}
vault_state: {}
}
| {
denom_state: {
denom: string
}
}
denom_state: {
denom: string
}
}
| {
perp_denom_state: {
denom: string
}
}
perp_denom_state: {
denom: string
}
}
| {
denom_states: {
limit?: number | null
start_after?: string | null
}
}
denom_states: {
limit?: number | null
start_after?: string | null
}
}
| {
deposit: {
depositor: string
}
}
deposit: {
depositor: string
}
}
| {
deposits: {
limit?: number | null
start_after?: string | null
}
}
deposits: {
limit?: number | null
start_after?: string | null
}
}
| {
unlocks: {
depositor: string
}
}
unlocks: {
depositor: string
}
}
| {
position: {
account_id: string
denom: string
}
}
position: {
account_id: string
denom: string
}
}
| {
positions: {
limit?: number | null
start_after?: [string, string] | null
}
}
positions: {
limit?: number | null
start_after?: [string, string] | null
}
}
| {
positions_by_account: {
account_id: string
}
}
positions_by_account: {
account_id: string
}
}
| {
total_pnl: {}
}
total_pnl: {}
}
| {
opening_fee: {
denom: string
size: SignedDecimal
}
}
opening_fee: {
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
closing_fee_rate: Decimal
@ -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,24 +249,27 @@ 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
}
export type PnL =
| 'break_even'
| {
profit: Coin
}
profit: Coin
}
| {
loss: Coin
}
loss: Coin
}
export interface PositionResponse {
account_id: string
position: PerpPosition
@ -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),
),
},
},