Skip to content

Commit

Permalink
token tiers adjustments + refactor (#356)
Browse files Browse the repository at this point in the history
* fix

* fix

* add simulation

* fix

* improve decode logic for oderbook
  • Loading branch information
abrzezinski94 authored Dec 28, 2023
1 parent 60f2815 commit 6fb99db
Show file tree
Hide file tree
Showing 11 changed files with 278 additions and 260 deletions.
308 changes: 143 additions & 165 deletions components/governance/ListToken/ListToken.tsx

Large diffs are not rendered by default.

51 changes: 31 additions & 20 deletions components/modals/CreateSwitchboardOracleModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@ import Loading from '@components/shared/Loading'
import { WhirlpoolContext, buildWhirlpoolClient } from '@orca-so/whirlpools-sdk'
import { LIQUIDITY_STATE_LAYOUT_V4 } from '@raydium-io/raydium-sdk'
import { createComputeBudgetIx } from '@blockworks-foundation/mango-v4'
import { LISTING_PRESETS_KEY } from '@blockworks-foundation/mango-v4-settings/lib/helpers/listingTools'

const poolAddressError = 'no-pool-address-found'
const wrongTierPassedForCreation = 'Wrong tier passed for creation of oracle'

const SWITCHBOARD_PERMISSIONLESS_QUE =
'5JYwqvKkqp35w8Nq3ba4z1WYUeJQ1rB36V8XvaGp6zn1'
Expand All @@ -33,7 +35,7 @@ type BaseProps = ModalProps & {
openbookMarketPk: string
baseTokenPk: string
baseTokenName: string
tier: string
tierKey: LISTING_PRESETS_KEY
}

type RaydiumProps = BaseProps & {
Expand All @@ -53,49 +55,49 @@ const CreateSwitchboardOracleModal = ({
baseTokenName,
raydiumPoolAddress,
orcaPoolAddress,
tier,
tierKey,
}: RaydiumProps | OrcaProps) => {
const { t } = useTranslation(['governance'])
const connection = mangoStore((s) => s.connection)
const fee = mangoStore((s) => s.priorityFee)
const wallet = useWallet()
const quoteTokenName = 'USD'
const pythUsdOracle = 'Gnt27xtC473ZT2Mw5u8wZ68Z3gULkSTb5DuxJy7eJotD'
const tierToSwapValue: { [key: string]: string } = {
PREMIUM: '10000',
MID: '2000',
MEME: '500',
SHIT: '100',
const tierToSwapValue: { [key in LISTING_PRESETS_KEY]?: string } = {
asset_100: '10000',
asset_20: '2000',
liab_5: '500',
liab_1: '100',
UNTRUSTED: '100',
}

const tierSettings: {
[key: string]: {
[key in LISTING_PRESETS_KEY]?: {
fundAmount: number
batchSize: number
minRequiredOracleResults: number
minUpdateDelaySeconds: number
}
} = {
PREMIUM: {
asset_100: {
fundAmount: 5,
minRequiredOracleResults: 3,
minUpdateDelaySeconds: 6,
batchSize: 5,
},
MID: {
asset_20: {
fundAmount: 5,
minRequiredOracleResults: 1,
minUpdateDelaySeconds: 6,
batchSize: 2,
},
MEME: {
liab_5: {
fundAmount: 2,
minRequiredOracleResults: 1,
minUpdateDelaySeconds: 20,
batchSize: 2,
},
SHIT: {
liab_1: {
fundAmount: 2,
batchSize: 2,
minRequiredOracleResults: 1,
Expand Down Expand Up @@ -132,7 +134,7 @@ const CreateSwitchboardOracleModal = ({

const create = useCallback(async () => {
try {
const swapValue = tierToSwapValue[tier]
const swapValue = tierToSwapValue[tierKey]
setCreatingOracle(true)
const payer = wallet!.publicKey!
if (!orcaPoolAddress && !raydiumPoolAddress) {
Expand Down Expand Up @@ -185,20 +187,23 @@ const CreateSwitchboardOracleModal = ({
},
]
}

const settingFromLib = tierSettings[tierKey]
if (!settingFromLib) {
throw wrongTierPassedForCreation
}
const [aggregatorAccount, txArray1] =
await queueAccount.createFeedInstructions(payer, {
name: `${baseTokenName}/${quoteTokenName}`,
batchSize: tierSettings[tier].batchSize,
minRequiredOracleResults: tierSettings[tier].minRequiredOracleResults,
batchSize: settingFromLib.batchSize,
minRequiredOracleResults: settingFromLib.minRequiredOracleResults,
minRequiredJobResults: 2,
minUpdateDelaySeconds: tierSettings[tier].minUpdateDelaySeconds,
minUpdateDelaySeconds: settingFromLib.minUpdateDelaySeconds,
forceReportPeriod: 60 * 60,
withdrawAuthority: MANGO_DAO_WALLET,
authority: payer,
crankDataBuffer: crankAccount.dataBuffer?.publicKey,
crankPubkey: crankAccount.publicKey,
fundAmount: tierSettings[tier].fundAmount,
fundAmount: settingFromLib.fundAmount,
slidingWindow: true,
disableCrank: false,
maxPriorityFeeMultiplier: 5,
Expand Down Expand Up @@ -364,6 +369,12 @@ const CreateSwitchboardOracleModal = ({
description: 'No orca or raydium pool found for oracle',
type: 'error',
})
} else if (e === wrongTierPassedForCreation) {
notify({
title: 'Transaction failed',
description: 'Wrong tier passed for oracle creation',
type: 'error',
})
} else {
if (!isMangoError(e)) return
notify({
Expand All @@ -381,7 +392,7 @@ const CreateSwitchboardOracleModal = ({
onClose,
orcaPoolAddress,
raydiumPoolAddress,
tier,
tierKey,
tierToSwapValue,
wallet,
])
Expand All @@ -393,7 +404,7 @@ const CreateSwitchboardOracleModal = ({
{t('create-switch-oracle')} {baseTokenName}/USD
</p>
<p>
{t('estimated-oracle-cost')} {tierSettings[tier].fundAmount} SOL
{t('estimated-oracle-cost')} {tierSettings[tierKey]?.fundAmount} SOL
</p>
</div>

Expand Down
107 changes: 61 additions & 46 deletions components/modals/DashboardSuggestedValuesModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
OracleProvider,
PriceImpact,
} from '@blockworks-foundation/mango-v4'
import { AccountMeta } from '@solana/web3.js'
import { AccountMeta, Transaction } from '@solana/web3.js'
import { BN } from '@project-serum/anchor'
import {
MANGO_DAO_WALLET,
Expand All @@ -26,16 +26,19 @@ import Button from '@components/shared/Button'
import { compareObjectsAndGetDifferentKeys } from 'utils/governance/tools'
import { Disclosure } from '@headlessui/react'
import {
LISTING_PRESET,
LISTING_PRESETS,
LISTING_PRESETS_KEYS,
LISTING_PRESETS_PYTH,
ListingPreset,
LISTING_PRESETS_KEY,
MidPriceImpact,
getMidPriceImpacts,
getProposedTier,
getTierWithAdjustedNetBorrows,
getPresetWithAdjustedDepositLimit,
getPresetWithAdjustedNetBorrows,
getProposedKey,
getPythPresets,
getSwitchBoardPresets,
} from '@blockworks-foundation/mango-v4-settings/lib/helpers/listingTools'
import Select from '@components/forms/Select'
import Loading from '@components/shared/Loading'

const DashboardSuggestedValues = ({
isOpen,
Expand All @@ -58,11 +61,12 @@ const DashboardSuggestedValues = ({
const proposals = GovernanceStore((s) => s.proposals)
const PRESETS =
bank?.oracleProvider === OracleProvider.Pyth
? LISTING_PRESETS_PYTH
: LISTING_PRESETS
? getPythPresets(LISTING_PRESETS)
: getSwitchBoardPresets(LISTING_PRESETS)

const [suggestedTier, setSuggestedTier] =
useState<LISTING_PRESETS_KEYS>('SHIT')
useState<LISTING_PRESETS_KEY>('liab_1')
const [proposing, setProposing] = useState(false)

const getApiTokenName = (bankName: string) => {
if (bankName === 'ETH (Portal)') {
Expand Down Expand Up @@ -93,25 +97,19 @@ const DashboardSuggestedValues = ({
}, {})
const priceImpact = filteredResp[getApiTokenName(bank.name)]

const suggestedTier = getProposedTier(
PRESETS,
const suggestedTier = getProposedKey(
priceImpact?.target_amount,
bank.oracleProvider === OracleProvider.Pyth,
)

setSuggestedTier(suggestedTier as LISTING_PRESETS_KEYS)
}, [
PRESETS,
bank.name,
bank.oracleProvider,
JSON.stringify(priceImpactsFiltered),
])
setSuggestedTier(suggestedTier)
}, [bank.name, bank.oracleProvider, priceImpactsFiltered])

const proposeNewSuggestedValues = useCallback(
async (
bank: Bank,
invalidFieldsKeys: string[],
tokenTier: LISTING_PRESETS_KEYS,
tokenTier: LISTING_PRESETS_KEY,
) => {
const proposalTx = []
const mintInfo = group!.mintInfosMapByTokenIndex.get(bank.tokenIndex)!
Expand Down Expand Up @@ -228,7 +226,7 @@ const DashboardSuggestedValues = ({
false,
false,
getNullOrVal(fieldsToChange.depositLimit)
? new BN(fieldsToChange.depositLimit!)
? new BN(fieldsToChange.depositLimit!.toString())
: null,
)
.accounts({
Expand All @@ -248,36 +246,48 @@ const DashboardSuggestedValues = ({
proposalTx.push(ix)

const walletSigner = wallet as never

try {
const index = proposals ? Object.values(proposals).length : 0
const proposalAddress = await createProposal(
connection,
walletSigner,
MANGO_DAO_WALLET_GOVERNANCE,
voter.tokenOwnerRecord!,
`Edit token ${bank.name}`,
'Adjust settings to current liquidity',
index,
proposalTx,
vsrClient!,
fee,
)
window.open(
`https://dao.mango.markets/dao/MNGO/proposal/${proposalAddress.toBase58()}`,
'_blank',
)
setProposing(true)
const simTransaction = new Transaction({ feePayer: wallet.publicKey })
simTransaction.add(...proposalTx)
const simulation = await connection.simulateTransaction(simTransaction)

if (!simulation.value.err) {
const index = proposals ? Object.values(proposals).length : 0
const proposalAddress = await createProposal(
connection,
walletSigner,
MANGO_DAO_WALLET_GOVERNANCE,
voter.tokenOwnerRecord!,
`Edit token ${bank.name}`,
'Adjust settings to current liquidity',
index,
proposalTx,
vsrClient!,
fee,
)
window.open(
`https://dao.mango.markets/dao/MNGO/proposal/${proposalAddress.toBase58()}`,
'_blank',
)
} else {
throw simulation.value.logs
}
} catch (e) {
notify({
title: 'Error during proposal creation',
description: `${e}`,
type: 'error',
})
}
setProposing(false)
},
[
PRESETS,
client,
connection,
fee,
group,
proposals,
voter.tokenOwnerRecord,
Expand All @@ -294,16 +304,21 @@ const DashboardSuggestedValues = ({

const formattedBankValues = getFormattedBankValues(group, bank)

const suggestedVaules = getTierWithAdjustedNetBorrows(
PRESETS[suggestedTier as LISTING_PRESETS_KEYS] as ListingPreset,
bank.nativeDeposits().mul(bank.price).toNumber(),
const suggestedValues = getPresetWithAdjustedDepositLimit(
getPresetWithAdjustedNetBorrows(
PRESETS[suggestedTier as LISTING_PRESETS_KEY] as LISTING_PRESET,
bank.nativeDeposits().mul(bank.price).toNumber(),
),
bank.uiPrice,
bank.mintDecimals,
)
const suggestedFormattedPreset = formatSuggestedValues(suggestedVaules)

const suggestedFormattedPreset = formatSuggestedValues(suggestedValues)

type SuggestedFormattedPreset = typeof suggestedFormattedPreset

const invalidKeys: (keyof SuggestedFormattedPreset)[] = Object.keys(
suggestedVaules,
suggestedValues,
).length
? compareObjectsAndGetDifferentKeys<SuggestedFormattedPreset>(
formattedBankValues,
Expand Down Expand Up @@ -339,7 +354,7 @@ const DashboardSuggestedValues = ({
onChange={(tier) => setSuggestedTier(tier)}
className="w-full"
>
{Object.keys(LISTING_PRESETS)
{Object.keys(PRESETS)
.filter((x) => x !== 'UNTRUSTED')
.map((name) => (
<Select.Option key={name} value={name}>
Expand Down Expand Up @@ -630,12 +645,12 @@ const DashboardSuggestedValues = ({
proposeNewSuggestedValues(
bank,
invalidKeys,
suggestedTier as LISTING_PRESETS_KEYS,
suggestedTier as LISTING_PRESETS_KEY,
)
}
disabled={!wallet.connected}
disabled={!wallet.connected || proposing}
>
Propose new suggested values
{proposing ? <Loading></Loading> : 'Propose new suggested values'}
</Button>
</div>
)}
Expand Down
6 changes: 3 additions & 3 deletions components/trade/DepthChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -316,11 +316,11 @@ const DepthChart = () => {
</div>
</div>
<div
className={
className={`${
increaseHeight ? 'h-[570px]' : isTablet ? 'h-[538px]' : 'h-[482px]'
}
}`}
>
<ResponsiveContainer width="100%" height="100%">
<ResponsiveContainer width="100" height="100%">
<AreaChart
data={chartData}
layout="vertical"
Expand Down
Loading

1 comment on commit 6fb99db

@vercel
Copy link

@vercel vercel bot commented on 6fb99db Dec 28, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.