repo_id
stringclasses 563
values | file_path
stringlengths 40
166
| content
stringlengths 1
2.94M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
solana_public_repos/drift-labs/protocol-v2/sdk
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/adminClient.ts
|
import {
PublicKey,
SystemProgram,
SYSVAR_RENT_PUBKEY,
TransactionInstruction,
TransactionSignature,
} from '@solana/web3.js';
import {
FeeStructure,
OracleGuardRails,
OracleSource,
ExchangeStatus,
MarketStatus,
ContractTier,
AssetTier,
SpotFulfillmentConfigStatus,
} from './types';
import { DEFAULT_MARKET_NAME, encodeName } from './userName';
import { BN } from '@coral-xyz/anchor';
import * as anchor from '@coral-xyz/anchor';
import {
getDriftStateAccountPublicKeyAndNonce,
getSpotMarketPublicKey,
getSpotMarketVaultPublicKey,
getPerpMarketPublicKey,
getInsuranceFundVaultPublicKey,
getSerumOpenOrdersPublicKey,
getSerumFulfillmentConfigPublicKey,
getPhoenixFulfillmentConfigPublicKey,
getProtocolIfSharesTransferConfigPublicKey,
getPrelaunchOraclePublicKey,
getOpenbookV2FulfillmentConfigPublicKey,
getPythPullOraclePublicKey,
getUserStatsAccountPublicKey,
getHighLeverageModeConfigPublicKey,
getPythLazerOraclePublicKey,
} from './addresses/pda';
import { squareRootBN } from './math/utils';
import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
import { DriftClient } from './driftClient';
import {
PEG_PRECISION,
QUOTE_SPOT_MARKET_INDEX,
ZERO,
ONE,
BASE_PRECISION,
PRICE_PRECISION,
} from './constants/numericConstants';
import { calculateTargetPriceTrade } from './math/trade';
import { calculateAmmReservesAfterSwap, getSwapDirection } from './math/amm';
import { PROGRAM_ID as PHOENIX_PROGRAM_ID } from '@ellipsis-labs/phoenix-sdk';
import { DRIFT_ORACLE_RECEIVER_ID } from './config';
import { getFeedIdUint8Array } from './util/pythOracleUtils';
const OPENBOOK_PROGRAM_ID = new PublicKey(
'opnb2LAfJYbRMAHHvqjCwQxanZn7ReEHp1k81EohpZb'
);
export class AdminClient extends DriftClient {
public async initialize(
usdcMint: PublicKey,
_adminControlsPrices: boolean
): Promise<[TransactionSignature]> {
const stateAccountRPCResponse = await this.connection.getParsedAccountInfo(
await this.getStatePublicKey()
);
if (stateAccountRPCResponse.value !== null) {
throw new Error('Clearing house already initialized');
}
const [driftStatePublicKey] = await getDriftStateAccountPublicKeyAndNonce(
this.program.programId
);
const initializeIx = await this.program.instruction.initialize({
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: driftStatePublicKey,
quoteAssetMint: usdcMint,
rent: SYSVAR_RENT_PUBKEY,
driftSigner: this.getSignerPublicKey(),
systemProgram: anchor.web3.SystemProgram.programId,
tokenProgram: TOKEN_PROGRAM_ID,
},
});
const tx = await this.buildTransaction(initializeIx);
const { txSig } = await super.sendTransaction(tx, [], this.opts);
return [txSig];
}
public async initializeSpotMarket(
mint: PublicKey,
optimalUtilization: number,
optimalRate: number,
maxRate: number,
oracle: PublicKey,
oracleSource: OracleSource,
initialAssetWeight: number,
maintenanceAssetWeight: number,
initialLiabilityWeight: number,
maintenanceLiabilityWeight: number,
imfFactor = 0,
liquidatorFee = 0,
ifLiquidationFee = 0,
activeStatus = true,
assetTier = AssetTier.COLLATERAL,
scaleInitialAssetWeightStart = ZERO,
withdrawGuardThreshold = ZERO,
orderTickSize = ONE,
orderStepSize = ONE,
ifTotalFactor = 0,
name = DEFAULT_MARKET_NAME,
marketIndex?: number
): Promise<TransactionSignature> {
const spotMarketIndex =
marketIndex ?? this.getStateAccount().numberOfSpotMarkets;
const initializeIx = await this.getInitializeSpotMarketIx(
mint,
optimalUtilization,
optimalRate,
maxRate,
oracle,
oracleSource,
initialAssetWeight,
maintenanceAssetWeight,
initialLiabilityWeight,
maintenanceLiabilityWeight,
imfFactor,
liquidatorFee,
ifLiquidationFee,
activeStatus,
assetTier,
scaleInitialAssetWeightStart,
withdrawGuardThreshold,
orderTickSize,
orderStepSize,
ifTotalFactor,
name,
marketIndex
);
const tx = await this.buildTransaction(initializeIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
await this.accountSubscriber.addSpotMarket(spotMarketIndex);
await this.accountSubscriber.addOracle({
source: oracleSource,
publicKey: oracle,
});
await this.accountSubscriber.setSpotOracleMap();
return txSig;
}
public async getInitializeSpotMarketIx(
mint: PublicKey,
optimalUtilization: number,
optimalRate: number,
maxRate: number,
oracle: PublicKey,
oracleSource: OracleSource,
initialAssetWeight: number,
maintenanceAssetWeight: number,
initialLiabilityWeight: number,
maintenanceLiabilityWeight: number,
imfFactor = 0,
liquidatorFee = 0,
ifLiquidationFee = 0,
activeStatus = true,
assetTier = AssetTier.COLLATERAL,
scaleInitialAssetWeightStart = ZERO,
withdrawGuardThreshold = ZERO,
orderTickSize = ONE,
orderStepSize = ONE,
ifTotalFactor = 0,
name = DEFAULT_MARKET_NAME,
marketIndex?: number
): Promise<TransactionInstruction> {
const spotMarketIndex =
marketIndex ?? this.getStateAccount().numberOfSpotMarkets;
const spotMarket = await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
);
const spotMarketVault = await getSpotMarketVaultPublicKey(
this.program.programId,
spotMarketIndex
);
const insuranceFundVault = await getInsuranceFundVaultPublicKey(
this.program.programId,
spotMarketIndex
);
const tokenProgram = (await this.connection.getAccountInfo(mint)).owner;
const nameBuffer = encodeName(name);
const initializeIx = await this.program.instruction.initializeSpotMarket(
optimalUtilization,
optimalRate,
maxRate,
oracleSource,
initialAssetWeight,
maintenanceAssetWeight,
initialLiabilityWeight,
maintenanceLiabilityWeight,
imfFactor,
liquidatorFee,
ifLiquidationFee,
activeStatus,
assetTier,
scaleInitialAssetWeightStart,
withdrawGuardThreshold,
orderTickSize,
orderStepSize,
ifTotalFactor,
nameBuffer,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket,
spotMarketVault,
insuranceFundVault,
driftSigner: this.getSignerPublicKey(),
spotMarketMint: mint,
oracle,
rent: SYSVAR_RENT_PUBKEY,
systemProgram: anchor.web3.SystemProgram.programId,
tokenProgram,
},
}
);
return initializeIx;
}
public async deleteInitializedSpotMarket(
marketIndex: number
): Promise<TransactionSignature> {
const deleteInitializeMarketIx =
await this.getDeleteInitializedSpotMarketIx(marketIndex);
const tx = await this.buildTransaction(deleteInitializeMarketIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getDeleteInitializedSpotMarketIx(
marketIndex: number
): Promise<TransactionInstruction> {
const spotMarketPublicKey = await getSpotMarketPublicKey(
this.program.programId,
marketIndex
);
const spotMarketVaultPublicKey = await getSpotMarketVaultPublicKey(
this.program.programId,
marketIndex
);
const insuranceFundVaultPublicKey = await getInsuranceFundVaultPublicKey(
this.program.programId,
marketIndex
);
return await this.program.instruction.deleteInitializedSpotMarket(
marketIndex,
{
accounts: {
state: await this.getStatePublicKey(),
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
spotMarket: spotMarketPublicKey,
spotMarketVault: spotMarketVaultPublicKey,
insuranceFundVault: insuranceFundVaultPublicKey,
driftSigner: this.getSignerPublicKey(),
tokenProgram: TOKEN_PROGRAM_ID,
},
}
);
}
public async initializeSerumFulfillmentConfig(
marketIndex: number,
serumMarket: PublicKey,
serumProgram: PublicKey
): Promise<TransactionSignature> {
const initializeIx = await this.getInitializeSerumFulfillmentConfigIx(
marketIndex,
serumMarket,
serumProgram
);
const tx = await this.buildTransaction(initializeIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getInitializeSerumFulfillmentConfigIx(
marketIndex: number,
serumMarket: PublicKey,
serumProgram: PublicKey
): Promise<TransactionInstruction> {
const serumOpenOrders = getSerumOpenOrdersPublicKey(
this.program.programId,
serumMarket
);
const serumFulfillmentConfig = getSerumFulfillmentConfigPublicKey(
this.program.programId,
serumMarket
);
return await this.program.instruction.initializeSerumFulfillmentConfig(
marketIndex,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
baseSpotMarket: this.getSpotMarketAccount(marketIndex).pubkey,
quoteSpotMarket: this.getQuoteSpotMarketAccount().pubkey,
driftSigner: this.getSignerPublicKey(),
serumProgram,
serumMarket,
serumOpenOrders,
rent: SYSVAR_RENT_PUBKEY,
systemProgram: anchor.web3.SystemProgram.programId,
serumFulfillmentConfig,
},
}
);
}
public async initializePhoenixFulfillmentConfig(
marketIndex: number,
phoenixMarket: PublicKey
): Promise<TransactionSignature> {
const initializeIx = await this.getInitializePhoenixFulfillmentConfigIx(
marketIndex,
phoenixMarket
);
const tx = await this.buildTransaction(initializeIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getInitializePhoenixFulfillmentConfigIx(
marketIndex: number,
phoenixMarket: PublicKey
): Promise<TransactionInstruction> {
const phoenixFulfillmentConfig = getPhoenixFulfillmentConfigPublicKey(
this.program.programId,
phoenixMarket
);
return await this.program.instruction.initializePhoenixFulfillmentConfig(
marketIndex,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
baseSpotMarket: this.getSpotMarketAccount(marketIndex).pubkey,
quoteSpotMarket: this.getQuoteSpotMarketAccount().pubkey,
driftSigner: this.getSignerPublicKey(),
phoenixMarket: phoenixMarket,
phoenixProgram: PHOENIX_PROGRAM_ID,
rent: SYSVAR_RENT_PUBKEY,
systemProgram: anchor.web3.SystemProgram.programId,
phoenixFulfillmentConfig,
},
}
);
}
public async initializeOpenbookV2FulfillmentConfig(
marketIndex: number,
openbookMarket: PublicKey
): Promise<TransactionSignature> {
const initializeIx = await this.getInitializeOpenbookV2FulfillmentConfigIx(
marketIndex,
openbookMarket
);
const tx = await this.buildTransaction(initializeIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getInitializeOpenbookV2FulfillmentConfigIx(
marketIndex: number,
openbookMarket: PublicKey
): Promise<TransactionInstruction> {
const openbookFulfillmentConfig = getOpenbookV2FulfillmentConfigPublicKey(
this.program.programId,
openbookMarket
);
return this.program.instruction.initializeOpenbookV2FulfillmentConfig(
marketIndex,
{
accounts: {
baseSpotMarket: this.getSpotMarketAccount(marketIndex).pubkey,
quoteSpotMarket: this.getQuoteSpotMarketAccount().pubkey,
state: await this.getStatePublicKey(),
openbookV2Program: OPENBOOK_PROGRAM_ID,
openbookV2Market: openbookMarket,
driftSigner: this.getSignerPublicKey(),
openbookV2FulfillmentConfig: openbookFulfillmentConfig,
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
rent: SYSVAR_RENT_PUBKEY,
systemProgram: anchor.web3.SystemProgram.programId,
},
}
);
}
public async initializePerpMarket(
marketIndex: number,
priceOracle: PublicKey,
baseAssetReserve: BN,
quoteAssetReserve: BN,
periodicity: BN,
pegMultiplier: BN = PEG_PRECISION,
oracleSource: OracleSource = OracleSource.PYTH,
contractTier: ContractTier = ContractTier.SPECULATIVE,
marginRatioInitial = 2000,
marginRatioMaintenance = 500,
liquidatorFee = 0,
ifLiquidatorFee = 10000,
imfFactor = 0,
activeStatus = true,
baseSpread = 0,
maxSpread = 142500,
maxOpenInterest = ZERO,
maxRevenueWithdrawPerPeriod = ZERO,
quoteMaxInsurance = ZERO,
orderStepSize = BASE_PRECISION.divn(10000),
orderTickSize = PRICE_PRECISION.divn(100000),
minOrderSize = BASE_PRECISION.divn(10000),
concentrationCoefScale = ONE,
curveUpdateIntensity = 0,
ammJitIntensity = 0,
name = DEFAULT_MARKET_NAME
): Promise<TransactionSignature> {
const currentPerpMarketIndex = this.getStateAccount().numberOfMarkets;
const initializeMarketIx = await this.getInitializePerpMarketIx(
marketIndex,
priceOracle,
baseAssetReserve,
quoteAssetReserve,
periodicity,
pegMultiplier,
oracleSource,
contractTier,
marginRatioInitial,
marginRatioMaintenance,
liquidatorFee,
ifLiquidatorFee,
imfFactor,
activeStatus,
baseSpread,
maxSpread,
maxOpenInterest,
maxRevenueWithdrawPerPeriod,
quoteMaxInsurance,
orderStepSize,
orderTickSize,
minOrderSize,
concentrationCoefScale,
curveUpdateIntensity,
ammJitIntensity,
name
);
const tx = await this.buildTransaction(initializeMarketIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
while (this.getStateAccount().numberOfMarkets <= currentPerpMarketIndex) {
await this.fetchAccounts();
}
await this.accountSubscriber.addPerpMarket(marketIndex);
await this.accountSubscriber.addOracle({
source: oracleSource,
publicKey: priceOracle,
});
await this.accountSubscriber.setPerpOracleMap();
return txSig;
}
public async getInitializePerpMarketIx(
marketIndex: number,
priceOracle: PublicKey,
baseAssetReserve: BN,
quoteAssetReserve: BN,
periodicity: BN,
pegMultiplier: BN = PEG_PRECISION,
oracleSource: OracleSource = OracleSource.PYTH,
contractTier: ContractTier = ContractTier.SPECULATIVE,
marginRatioInitial = 2000,
marginRatioMaintenance = 500,
liquidatorFee = 0,
ifLiquidatorFee = 10000,
imfFactor = 0,
activeStatus = true,
baseSpread = 0,
maxSpread = 142500,
maxOpenInterest = ZERO,
maxRevenueWithdrawPerPeriod = ZERO,
quoteMaxInsurance = ZERO,
orderStepSize = BASE_PRECISION.divn(10000),
orderTickSize = PRICE_PRECISION.divn(100000),
minOrderSize = BASE_PRECISION.divn(10000),
concentrationCoefScale = ONE,
curveUpdateIntensity = 0,
ammJitIntensity = 0,
name = DEFAULT_MARKET_NAME
): Promise<TransactionInstruction> {
const perpMarketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
marketIndex
);
const nameBuffer = encodeName(name);
return await this.program.instruction.initializePerpMarket(
marketIndex,
baseAssetReserve,
quoteAssetReserve,
periodicity,
pegMultiplier,
oracleSource,
contractTier,
marginRatioInitial,
marginRatioMaintenance,
liquidatorFee,
ifLiquidatorFee,
imfFactor,
activeStatus,
baseSpread,
maxSpread,
maxOpenInterest,
maxRevenueWithdrawPerPeriod,
quoteMaxInsurance,
orderStepSize,
orderTickSize,
minOrderSize,
concentrationCoefScale,
curveUpdateIntensity,
ammJitIntensity,
nameBuffer,
{
accounts: {
state: await this.getStatePublicKey(),
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
oracle: priceOracle,
perpMarket: perpMarketPublicKey,
rent: SYSVAR_RENT_PUBKEY,
systemProgram: anchor.web3.SystemProgram.programId,
},
}
);
}
public async initializePredictionMarket(
perpMarketIndex: number
): Promise<TransactionSignature> {
const updatePerpMarketConcentrationCoefIx =
await this.getInitializePredictionMarketIx(perpMarketIndex);
const tx = await this.buildTransaction(updatePerpMarketConcentrationCoefIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getInitializePredictionMarketIx(
perpMarketIndex: number
): Promise<TransactionInstruction> {
return await this.program.instruction.initializePredictionMarket({
accounts: {
state: await this.getStatePublicKey(),
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
});
}
public async deleteInitializedPerpMarket(
marketIndex: number
): Promise<TransactionSignature> {
const deleteInitializeMarketIx =
await this.getDeleteInitializedPerpMarketIx(marketIndex);
const tx = await this.buildTransaction(deleteInitializeMarketIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getDeleteInitializedPerpMarketIx(
marketIndex: number
): Promise<TransactionInstruction> {
const perpMarketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
marketIndex
);
return await this.program.instruction.deleteInitializedPerpMarket(
marketIndex,
{
accounts: {
state: await this.getStatePublicKey(),
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
perpMarket: perpMarketPublicKey,
},
}
);
}
public async moveAmmPrice(
perpMarketIndex: number,
baseAssetReserve: BN,
quoteAssetReserve: BN,
sqrtK?: BN
): Promise<TransactionSignature> {
const moveAmmPriceIx = await this.getMoveAmmPriceIx(
perpMarketIndex,
baseAssetReserve,
quoteAssetReserve,
sqrtK
);
const tx = await this.buildTransaction(moveAmmPriceIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getMoveAmmPriceIx(
perpMarketIndex: number,
baseAssetReserve: BN,
quoteAssetReserve: BN,
sqrtK?: BN
): Promise<TransactionInstruction> {
const marketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
);
if (sqrtK == undefined) {
sqrtK = squareRootBN(baseAssetReserve.mul(quoteAssetReserve));
}
return await this.program.instruction.moveAmmPrice(
baseAssetReserve,
quoteAssetReserve,
sqrtK,
{
accounts: {
state: await this.getStatePublicKey(),
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
perpMarket: marketPublicKey,
},
}
);
}
public async updateK(
perpMarketIndex: number,
sqrtK: BN
): Promise<TransactionSignature> {
const updateKIx = await this.getUpdateKIx(perpMarketIndex, sqrtK);
const tx = await this.buildTransaction(updateKIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateKIx(
perpMarketIndex: number,
sqrtK: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updateK(sqrtK, {
accounts: {
state: await this.getStatePublicKey(),
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
oracle: this.getPerpMarketAccount(perpMarketIndex).amm.oracle,
},
});
}
public async recenterPerpMarketAmm(
perpMarketIndex: number,
pegMultiplier: BN,
sqrtK: BN
): Promise<TransactionSignature> {
const recenterPerpMarketAmmIx = await this.getRecenterPerpMarketAmmIx(
perpMarketIndex,
pegMultiplier,
sqrtK
);
const tx = await this.buildTransaction(recenterPerpMarketAmmIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getRecenterPerpMarketAmmIx(
perpMarketIndex: number,
pegMultiplier: BN,
sqrtK: BN
): Promise<TransactionInstruction> {
const marketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
);
return await this.program.instruction.recenterPerpMarketAmm(
pegMultiplier,
sqrtK,
{
accounts: {
state: await this.getStatePublicKey(),
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
perpMarket: marketPublicKey,
},
}
);
}
public async updatePerpMarketConcentrationScale(
perpMarketIndex: number,
concentrationScale: BN
): Promise<TransactionSignature> {
const updatePerpMarketConcentrationCoefIx =
await this.getUpdatePerpMarketConcentrationScaleIx(
perpMarketIndex,
concentrationScale
);
const tx = await this.buildTransaction(updatePerpMarketConcentrationCoefIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketConcentrationScaleIx(
perpMarketIndex: number,
concentrationScale: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketConcentrationCoef(
concentrationScale,
{
accounts: {
state: await this.getStatePublicKey(),
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async moveAmmToPrice(
perpMarketIndex: number,
targetPrice: BN
): Promise<TransactionSignature> {
const moveAmmPriceIx = await this.getMoveAmmToPriceIx(
perpMarketIndex,
targetPrice
);
const tx = await this.buildTransaction(moveAmmPriceIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getMoveAmmToPriceIx(
perpMarketIndex: number,
targetPrice: BN
): Promise<TransactionInstruction> {
const perpMarket = this.getPerpMarketAccount(perpMarketIndex);
const [direction, tradeSize, _] = calculateTargetPriceTrade(
perpMarket,
targetPrice,
new BN(1000),
'quote',
undefined //todo
);
const [newQuoteAssetAmount, newBaseAssetAmount] =
calculateAmmReservesAfterSwap(
perpMarket.amm,
'quote',
tradeSize,
getSwapDirection('quote', direction)
);
const perpMarketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
);
return await this.program.instruction.moveAmmPrice(
newBaseAssetAmount,
newQuoteAssetAmount,
perpMarket.amm.sqrtK,
{
accounts: {
state: await this.getStatePublicKey(),
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
perpMarket: perpMarketPublicKey,
},
}
);
}
public async repegAmmCurve(
newPeg: BN,
perpMarketIndex: number
): Promise<TransactionSignature> {
const repegAmmCurveIx = await this.getRepegAmmCurveIx(
newPeg,
perpMarketIndex
);
const tx = await this.buildTransaction(repegAmmCurveIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getRepegAmmCurveIx(
newPeg: BN,
perpMarketIndex: number
): Promise<TransactionInstruction> {
const perpMarketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
);
const ammData = this.getPerpMarketAccount(perpMarketIndex).amm;
return await this.program.instruction.repegAmmCurve(newPeg, {
accounts: {
state: await this.getStatePublicKey(),
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
oracle: ammData.oracle,
perpMarket: perpMarketPublicKey,
},
});
}
public async updatePerpMarketAmmOracleTwap(
perpMarketIndex: number
): Promise<TransactionSignature> {
const updatePerpMarketAmmOracleTwapIx =
await this.getUpdatePerpMarketAmmOracleTwapIx(perpMarketIndex);
const tx = await this.buildTransaction(updatePerpMarketAmmOracleTwapIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketAmmOracleTwapIx(
perpMarketIndex: number
): Promise<TransactionInstruction> {
const ammData = this.getPerpMarketAccount(perpMarketIndex).amm;
const perpMarketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
);
return await this.program.instruction.updatePerpMarketAmmOracleTwap({
accounts: {
state: await this.getStatePublicKey(),
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
oracle: ammData.oracle,
perpMarket: perpMarketPublicKey,
},
});
}
public async resetPerpMarketAmmOracleTwap(
perpMarketIndex: number
): Promise<TransactionSignature> {
const resetPerpMarketAmmOracleTwapIx =
await this.getResetPerpMarketAmmOracleTwapIx(perpMarketIndex);
const tx = await this.buildTransaction(resetPerpMarketAmmOracleTwapIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getResetPerpMarketAmmOracleTwapIx(
perpMarketIndex: number
): Promise<TransactionInstruction> {
const ammData = this.getPerpMarketAccount(perpMarketIndex).amm;
const perpMarketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
);
return await this.program.instruction.resetPerpMarketAmmOracleTwap({
accounts: {
state: await this.getStatePublicKey(),
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
oracle: ammData.oracle,
perpMarket: perpMarketPublicKey,
},
});
}
public async depositIntoPerpMarketFeePool(
perpMarketIndex: number,
amount: BN,
sourceVault: PublicKey
): Promise<TransactionSignature> {
const depositIntoPerpMarketFeePoolIx =
await this.getDepositIntoPerpMarketFeePoolIx(
perpMarketIndex,
amount,
sourceVault
);
const tx = await this.buildTransaction(depositIntoPerpMarketFeePoolIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getDepositIntoPerpMarketFeePoolIx(
perpMarketIndex: number,
amount: BN,
sourceVault: PublicKey
): Promise<TransactionInstruction> {
const spotMarket = this.getQuoteSpotMarketAccount();
return await this.program.instruction.depositIntoPerpMarketFeePool(amount, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
sourceVault,
driftSigner: this.getSignerPublicKey(),
quoteSpotMarket: spotMarket.pubkey,
spotMarketVault: spotMarket.vault,
tokenProgram: TOKEN_PROGRAM_ID,
},
});
}
public async depositIntoSpotMarketVault(
spotMarketIndex: number,
amount: BN,
sourceVault: PublicKey
): Promise<TransactionSignature> {
const depositIntoPerpMarketFeePoolIx =
await this.getDepositIntoSpotMarketVaultIx(
spotMarketIndex,
amount,
sourceVault
);
const tx = await this.buildTransaction(depositIntoPerpMarketFeePoolIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getDepositIntoSpotMarketVaultIx(
spotMarketIndex: number,
amount: BN,
sourceVault: PublicKey
): Promise<TransactionInstruction> {
const spotMarket = this.getSpotMarketAccount(spotMarketIndex);
const remainingAccounts = [];
this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
const tokenProgram = this.getTokenProgramForSpotMarket(spotMarket);
return await this.program.instruction.depositIntoSpotMarketVault(amount, {
accounts: {
admin: this.wallet.publicKey,
state: await this.getStatePublicKey(),
sourceVault,
spotMarket: spotMarket.pubkey,
spotMarketVault: spotMarket.vault,
tokenProgram,
},
remainingAccounts,
});
}
public async updateAdmin(admin: PublicKey): Promise<TransactionSignature> {
const updateAdminIx = await this.getUpdateAdminIx(admin);
const tx = await this.buildTransaction(updateAdminIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateAdminIx(
admin: PublicKey
): Promise<TransactionInstruction> {
return await this.program.instruction.updateAdmin(admin, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
});
}
public async updatePerpMarketCurveUpdateIntensity(
perpMarketIndex: number,
curveUpdateIntensity: number
): Promise<TransactionSignature> {
const updatePerpMarketCurveUpdateIntensityIx =
await this.getUpdatePerpMarketCurveUpdateIntensityIx(
perpMarketIndex,
curveUpdateIntensity
);
const tx = await this.buildTransaction(
updatePerpMarketCurveUpdateIntensityIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketCurveUpdateIntensityIx(
perpMarketIndex: number,
curveUpdateIntensity: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketCurveUpdateIntensity(
curveUpdateIntensity,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updatePerpMarketTargetBaseAssetAmountPerLp(
perpMarketIndex: number,
targetBaseAssetAmountPerLP: number
): Promise<TransactionSignature> {
const updatePerpMarketTargetBaseAssetAmountPerLpIx =
await this.getUpdatePerpMarketTargetBaseAssetAmountPerLpIx(
perpMarketIndex,
targetBaseAssetAmountPerLP
);
const tx = await this.buildTransaction(
updatePerpMarketTargetBaseAssetAmountPerLpIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async updatePerpMarketAmmSummaryStats(
perpMarketIndex: number,
updateAmmSummaryStats?: boolean,
quoteAssetAmountWithUnsettledLp?: BN,
netUnsettledFundingPnl?: BN
): Promise<TransactionSignature> {
const updatePerpMarketMarginRatioIx =
await this.getUpdatePerpMarketAmmSummaryStatsIx(
perpMarketIndex,
updateAmmSummaryStats,
quoteAssetAmountWithUnsettledLp,
netUnsettledFundingPnl
);
const tx = await this.buildTransaction(updatePerpMarketMarginRatioIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketAmmSummaryStatsIx(
perpMarketIndex: number,
updateAmmSummaryStats?: boolean,
quoteAssetAmountWithUnsettledLp?: BN,
netUnsettledFundingPnl?: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketAmmSummaryStats(
{
updateAmmSummaryStats: updateAmmSummaryStats ?? null,
quoteAssetAmountWithUnsettledLp:
quoteAssetAmountWithUnsettledLp ?? null,
netUnsettledFundingPnl: netUnsettledFundingPnl ?? null,
},
{
accounts: {
admin: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
QUOTE_SPOT_MARKET_INDEX
),
oracle: this.getPerpMarketAccount(perpMarketIndex).amm.oracle,
},
}
);
}
public async getUpdatePerpMarketTargetBaseAssetAmountPerLpIx(
perpMarketIndex: number,
targetBaseAssetAmountPerLP: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketTargetBaseAssetAmountPerLp(
targetBaseAssetAmountPerLP,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updatePerpMarketMarginRatio(
perpMarketIndex: number,
marginRatioInitial: number,
marginRatioMaintenance: number
): Promise<TransactionSignature> {
const updatePerpMarketMarginRatioIx =
await this.getUpdatePerpMarketMarginRatioIx(
perpMarketIndex,
marginRatioInitial,
marginRatioMaintenance
);
const tx = await this.buildTransaction(updatePerpMarketMarginRatioIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketMarginRatioIx(
perpMarketIndex: number,
marginRatioInitial: number,
marginRatioMaintenance: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketMarginRatio(
marginRatioInitial,
marginRatioMaintenance,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updatePerpMarketHighLeverageMarginRatio(
perpMarketIndex: number,
marginRatioInitial: number,
marginRatioMaintenance: number
): Promise<TransactionSignature> {
const updatePerpMarketHighLeverageMarginRatioIx =
await this.getUpdatePerpMarketHighLeverageMarginRatioIx(
perpMarketIndex,
marginRatioInitial,
marginRatioMaintenance
);
const tx = await this.buildTransaction(
updatePerpMarketHighLeverageMarginRatioIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketHighLeverageMarginRatioIx(
perpMarketIndex: number,
marginRatioInitial: number,
marginRatioMaintenance: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketHighLeverageMarginRatio(
marginRatioInitial,
marginRatioMaintenance,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updatePerpMarketImfFactor(
perpMarketIndex: number,
imfFactor: number,
unrealizedPnlImfFactor: number
): Promise<TransactionSignature> {
const updatePerpMarketImfFactorIx =
await this.getUpdatePerpMarketImfFactorIx(
perpMarketIndex,
imfFactor,
unrealizedPnlImfFactor
);
const tx = await this.buildTransaction(updatePerpMarketImfFactorIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketImfFactorIx(
perpMarketIndex: number,
imfFactor: number,
unrealizedPnlImfFactor: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketImfFactor(
imfFactor,
unrealizedPnlImfFactor,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updatePerpMarketBaseSpread(
perpMarketIndex: number,
baseSpread: number
): Promise<TransactionSignature> {
const updatePerpMarketBaseSpreadIx =
await this.getUpdatePerpMarketBaseSpreadIx(perpMarketIndex, baseSpread);
const tx = await this.buildTransaction(updatePerpMarketBaseSpreadIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketBaseSpreadIx(
perpMarketIndex: number,
baseSpread: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketBaseSpread(
baseSpread,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updateAmmJitIntensity(
perpMarketIndex: number,
ammJitIntensity: number
): Promise<TransactionSignature> {
const updateAmmJitIntensityIx = await this.getUpdateAmmJitIntensityIx(
perpMarketIndex,
ammJitIntensity
);
const tx = await this.buildTransaction(updateAmmJitIntensityIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateAmmJitIntensityIx(
perpMarketIndex: number,
ammJitIntensity: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateAmmJitIntensity(
ammJitIntensity,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updatePerpMarketName(
perpMarketIndex: number,
name: string
): Promise<TransactionSignature> {
const updatePerpMarketNameIx = await this.getUpdatePerpMarketNameIx(
perpMarketIndex,
name
);
const tx = await this.buildTransaction(updatePerpMarketNameIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketNameIx(
perpMarketIndex: number,
name: string
): Promise<TransactionInstruction> {
const nameBuffer = encodeName(name);
return await this.program.instruction.updatePerpMarketName(nameBuffer, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
});
}
public async updateSpotMarketName(
spotMarketIndex: number,
name: string
): Promise<TransactionSignature> {
const updateSpotMarketNameIx = await this.getUpdateSpotMarketNameIx(
spotMarketIndex,
name
);
const tx = await this.buildTransaction(updateSpotMarketNameIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketNameIx(
spotMarketIndex: number,
name: string
): Promise<TransactionInstruction> {
const nameBuffer = encodeName(name);
return await this.program.instruction.updateSpotMarketName(nameBuffer, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
});
}
public async updateSpotMarketPoolId(
spotMarketIndex: number,
poolId: number
): Promise<TransactionSignature> {
const updateSpotMarketPoolIdIx = await this.getUpdateSpotMarketPoolIdIx(
spotMarketIndex,
poolId
);
const tx = await this.buildTransaction(updateSpotMarketPoolIdIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketPoolIdIx(
spotMarketIndex: number,
poolId: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketPoolId(poolId, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
});
}
public async updatePerpMarketPerLpBase(
perpMarketIndex: number,
perLpBase: number
): Promise<TransactionSignature> {
const updatePerpMarketPerLpBaseIx =
await this.getUpdatePerpMarketPerLpBaseIx(perpMarketIndex, perLpBase);
const tx = await this.buildTransaction(updatePerpMarketPerLpBaseIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketPerLpBaseIx(
perpMarketIndex: number,
perLpBase: number
): Promise<TransactionInstruction> {
const perpMarketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
);
return await this.program.instruction.updatePerpMarketPerLpBase(perLpBase, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: perpMarketPublicKey,
},
});
}
public async updatePerpMarketMaxSpread(
perpMarketIndex: number,
maxSpread: number
): Promise<TransactionSignature> {
const updatePerpMarketMaxSpreadIx =
await this.getUpdatePerpMarketMaxSpreadIx(perpMarketIndex, maxSpread);
const tx = await this.buildTransaction(updatePerpMarketMaxSpreadIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketMaxSpreadIx(
perpMarketIndex: number,
maxSpread: number
): Promise<TransactionInstruction> {
const perpMarketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
);
return await this.program.instruction.updatePerpMarketMaxSpread(maxSpread, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: perpMarketPublicKey,
},
});
}
public async updatePerpFeeStructure(
feeStructure: FeeStructure
): Promise<TransactionSignature> {
const updatePerpFeeStructureIx = await this.getUpdatePerpFeeStructureIx(
feeStructure
);
const tx = await this.buildTransaction(updatePerpFeeStructureIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpFeeStructureIx(
feeStructure: FeeStructure
): Promise<TransactionInstruction> {
return this.program.instruction.updatePerpFeeStructure(feeStructure, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
});
}
public async updateSpotFeeStructure(
feeStructure: FeeStructure
): Promise<TransactionSignature> {
const updateSpotFeeStructureIx = await this.getUpdateSpotFeeStructureIx(
feeStructure
);
const tx = await this.buildTransaction(updateSpotFeeStructureIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotFeeStructureIx(
feeStructure: FeeStructure
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotFeeStructure(feeStructure, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
});
}
public async updateInitialPctToLiquidate(
initialPctToLiquidate: number
): Promise<TransactionSignature> {
const updateInitialPctToLiquidateIx =
await this.getUpdateInitialPctToLiquidateIx(initialPctToLiquidate);
const tx = await this.buildTransaction(updateInitialPctToLiquidateIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateInitialPctToLiquidateIx(
initialPctToLiquidate: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateInitialPctToLiquidate(
initialPctToLiquidate,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
}
);
}
public async updateLiquidationDuration(
liquidationDuration: number
): Promise<TransactionSignature> {
const updateLiquidationDurationIx =
await this.getUpdateLiquidationDurationIx(liquidationDuration);
const tx = await this.buildTransaction(updateLiquidationDurationIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateLiquidationDurationIx(
liquidationDuration: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateLiquidationDuration(
liquidationDuration,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
}
);
}
public async updateLiquidationMarginBufferRatio(
updateLiquidationMarginBufferRatio: number
): Promise<TransactionSignature> {
const updateLiquidationMarginBufferRatioIx =
await this.getUpdateLiquidationMarginBufferRatioIx(
updateLiquidationMarginBufferRatio
);
const tx = await this.buildTransaction(
updateLiquidationMarginBufferRatioIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateLiquidationMarginBufferRatioIx(
updateLiquidationMarginBufferRatio: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateLiquidationMarginBufferRatio(
updateLiquidationMarginBufferRatio,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
}
);
}
public async updateOracleGuardRails(
oracleGuardRails: OracleGuardRails
): Promise<TransactionSignature> {
const updateOracleGuardRailsIx = await this.getUpdateOracleGuardRailsIx(
oracleGuardRails
);
const tx = await this.buildTransaction(updateOracleGuardRailsIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateOracleGuardRailsIx(
oracleGuardRails: OracleGuardRails
): Promise<TransactionInstruction> {
return await this.program.instruction.updateOracleGuardRails(
oracleGuardRails,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
}
);
}
public async updateStateSettlementDuration(
settlementDuration: number
): Promise<TransactionSignature> {
const updateStateSettlementDurationIx =
await this.getUpdateStateSettlementDurationIx(settlementDuration);
const tx = await this.buildTransaction(updateStateSettlementDurationIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateStateSettlementDurationIx(
settlementDuration: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateStateSettlementDuration(
settlementDuration,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
}
);
}
public async updateStateMaxNumberOfSubAccounts(
maxNumberOfSubAccounts: number
): Promise<TransactionSignature> {
const updateStateMaxNumberOfSubAccountsIx =
await this.getUpdateStateMaxNumberOfSubAccountsIx(maxNumberOfSubAccounts);
const tx = await this.buildTransaction(updateStateMaxNumberOfSubAccountsIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateStateMaxNumberOfSubAccountsIx(
maxNumberOfSubAccounts: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateStateMaxNumberOfSubAccounts(
maxNumberOfSubAccounts,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
}
);
}
public async updateStateMaxInitializeUserFee(
maxInitializeUserFee: number
): Promise<TransactionSignature> {
const updateStateMaxInitializeUserFeeIx =
await this.getUpdateStateMaxInitializeUserFeeIx(maxInitializeUserFee);
const tx = await this.buildTransaction(updateStateMaxInitializeUserFeeIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateStateMaxInitializeUserFeeIx(
maxInitializeUserFee: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateStateMaxInitializeUserFee(
maxInitializeUserFee,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
}
);
}
public async updateWithdrawGuardThreshold(
spotMarketIndex: number,
withdrawGuardThreshold: BN
): Promise<TransactionSignature> {
const updateWithdrawGuardThresholdIx =
await this.getUpdateWithdrawGuardThresholdIx(
spotMarketIndex,
withdrawGuardThreshold
);
const tx = await this.buildTransaction(updateWithdrawGuardThresholdIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateWithdrawGuardThresholdIx(
spotMarketIndex: number,
withdrawGuardThreshold: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updateWithdrawGuardThreshold(
withdrawGuardThreshold,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updateSpotMarketIfFactor(
spotMarketIndex: number,
userIfFactor: BN,
totalIfFactor: BN
): Promise<TransactionSignature> {
const updateSpotMarketIfFactorIx = await this.getUpdateSpotMarketIfFactorIx(
spotMarketIndex,
userIfFactor,
totalIfFactor
);
const tx = await this.buildTransaction(updateSpotMarketIfFactorIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketIfFactorIx(
spotMarketIndex: number,
userIfFactor: BN,
totalIfFactor: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketIfFactor(
spotMarketIndex,
userIfFactor,
totalIfFactor,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updateSpotMarketRevenueSettlePeriod(
spotMarketIndex: number,
revenueSettlePeriod: BN
): Promise<TransactionSignature> {
const updateSpotMarketRevenueSettlePeriodIx =
await this.getUpdateSpotMarketRevenueSettlePeriodIx(
spotMarketIndex,
revenueSettlePeriod
);
const tx = await this.buildTransaction(
updateSpotMarketRevenueSettlePeriodIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketRevenueSettlePeriodIx(
spotMarketIndex: number,
revenueSettlePeriod: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketRevenueSettlePeriod(
revenueSettlePeriod,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updateSpotMarketMaxTokenDeposits(
spotMarketIndex: number,
maxTokenDeposits: BN
): Promise<TransactionSignature> {
const updateSpotMarketMaxTokenDepositsIx =
await this.getUpdateSpotMarketMaxTokenDepositsIx(
spotMarketIndex,
maxTokenDeposits
);
const tx = await this.buildTransaction(updateSpotMarketMaxTokenDepositsIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketMaxTokenDepositsIx(
spotMarketIndex: number,
maxTokenDeposits: BN
): Promise<TransactionInstruction> {
return this.program.instruction.updateSpotMarketMaxTokenDeposits(
maxTokenDeposits,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updateSpotMarketMaxTokenBorrows(
spotMarketIndex: number,
maxTokenBorrowsFraction: number
): Promise<TransactionSignature> {
const updateSpotMarketMaxTokenBorrowsIx =
await this.getUpdateSpotMarketMaxTokenBorrowsIx(
spotMarketIndex,
maxTokenBorrowsFraction
);
const tx = await this.buildTransaction(updateSpotMarketMaxTokenBorrowsIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketMaxTokenBorrowsIx(
spotMarketIndex: number,
maxTokenBorrowsFraction: number
): Promise<TransactionInstruction> {
return this.program.instruction.updateSpotMarketMaxTokenBorrows(
maxTokenBorrowsFraction,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updateSpotMarketScaleInitialAssetWeightStart(
spotMarketIndex: number,
scaleInitialAssetWeightStart: BN
): Promise<TransactionSignature> {
const updateSpotMarketScaleInitialAssetWeightStartIx =
await this.getUpdateSpotMarketScaleInitialAssetWeightStartIx(
spotMarketIndex,
scaleInitialAssetWeightStart
);
const tx = await this.buildTransaction(
updateSpotMarketScaleInitialAssetWeightStartIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketScaleInitialAssetWeightStartIx(
spotMarketIndex: number,
scaleInitialAssetWeightStart: BN
): Promise<TransactionInstruction> {
return this.program.instruction.updateSpotMarketScaleInitialAssetWeightStart(
scaleInitialAssetWeightStart,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updateInsuranceFundUnstakingPeriod(
spotMarketIndex: number,
insuranceWithdrawEscrowPeriod: BN
): Promise<TransactionSignature> {
const updateInsuranceFundUnstakingPeriodIx =
await this.getUpdateInsuranceFundUnstakingPeriodIx(
spotMarketIndex,
insuranceWithdrawEscrowPeriod
);
const tx = await this.buildTransaction(
updateInsuranceFundUnstakingPeriodIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateInsuranceFundUnstakingPeriodIx(
spotMarketIndex: number,
insuranceWithdrawEscrowPeriod: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updateInsuranceFundUnstakingPeriod(
insuranceWithdrawEscrowPeriod,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updateLpCooldownTime(
cooldownTime: BN
): Promise<TransactionSignature> {
const updateLpCooldownTimeIx = await this.getUpdateLpCooldownTimeIx(
cooldownTime
);
const tx = await this.buildTransaction(updateLpCooldownTimeIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateLpCooldownTimeIx(
cooldownTime: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updateLpCooldownTime(cooldownTime, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
});
}
public async updatePerpMarketOracle(
perpMarketIndex: number,
oracle: PublicKey,
oracleSource: OracleSource
): Promise<TransactionSignature> {
const updatePerpMarketOracleIx = await this.getUpdatePerpMarketOracleIx(
perpMarketIndex,
oracle,
oracleSource
);
const tx = await this.buildTransaction(updatePerpMarketOracleIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketOracleIx(
perpMarketIndex: number,
oracle: PublicKey,
oracleSource: OracleSource
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketOracle(
oracle,
oracleSource,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
oracle: oracle,
},
}
);
}
public async updatePerpMarketStepSizeAndTickSize(
perpMarketIndex: number,
stepSize: BN,
tickSize: BN
): Promise<TransactionSignature> {
const updatePerpMarketStepSizeAndTickSizeIx =
await this.getUpdatePerpMarketStepSizeAndTickSizeIx(
perpMarketIndex,
stepSize,
tickSize
);
const tx = await this.buildTransaction(
updatePerpMarketStepSizeAndTickSizeIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketStepSizeAndTickSizeIx(
perpMarketIndex: number,
stepSize: BN,
tickSize: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketStepSizeAndTickSize(
stepSize,
tickSize,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updatePerpMarketMinOrderSize(
perpMarketIndex: number,
orderSize: BN
): Promise<TransactionSignature> {
const updatePerpMarketMinOrderSizeIx =
await this.getUpdatePerpMarketMinOrderSizeIx(perpMarketIndex, orderSize);
const tx = await this.buildTransaction(updatePerpMarketMinOrderSizeIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketMinOrderSizeIx(
perpMarketIndex: number,
orderSize: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketMinOrderSize(
orderSize,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updateSpotMarketStepSizeAndTickSize(
spotMarketIndex: number,
stepSize: BN,
tickSize: BN
): Promise<TransactionSignature> {
const updateSpotMarketStepSizeAndTickSizeIx =
await this.getUpdateSpotMarketStepSizeAndTickSizeIx(
spotMarketIndex,
stepSize,
tickSize
);
const tx = await this.buildTransaction(
updateSpotMarketStepSizeAndTickSizeIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketStepSizeAndTickSizeIx(
spotMarketIndex: number,
stepSize: BN,
tickSize: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketStepSizeAndTickSize(
stepSize,
tickSize,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updateSpotMarketMinOrderSize(
spotMarketIndex: number,
orderSize: BN
): Promise<TransactionSignature> {
const updateSpotMarketMinOrderSizeIx =
await this.program.instruction.updateSpotMarketMinOrderSize(orderSize, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
});
const tx = await this.buildTransaction(updateSpotMarketMinOrderSizeIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketMinOrderSizeIx(
spotMarketIndex: number,
orderSize: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketMinOrderSize(
orderSize,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updatePerpMarketExpiry(
perpMarketIndex: number,
expiryTs: BN
): Promise<TransactionSignature> {
const updatePerpMarketExpiryIx = await this.getUpdatePerpMarketExpiryIx(
perpMarketIndex,
expiryTs
);
const tx = await this.buildTransaction(updatePerpMarketExpiryIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketExpiryIx(
perpMarketIndex: number,
expiryTs: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketExpiry(expiryTs, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
});
}
public async updateSpotMarketOracle(
spotMarketIndex: number,
oracle: PublicKey,
oracleSource: OracleSource
): Promise<TransactionSignature> {
const updateSpotMarketOracleIx = await this.getUpdateSpotMarketOracleIx(
spotMarketIndex,
oracle,
oracleSource
);
const tx = await this.buildTransaction(updateSpotMarketOracleIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketOracleIx(
spotMarketIndex: number,
oracle: PublicKey,
oracleSource: OracleSource
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketOracle(
oracle,
oracleSource,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
oracle: oracle,
},
}
);
}
public async updateSpotMarketOrdersEnabled(
spotMarketIndex: number,
ordersEnabled: boolean
): Promise<TransactionSignature> {
const updateSpotMarketOrdersEnabledIx =
await this.getUpdateSpotMarketOrdersEnabledIx(
spotMarketIndex,
ordersEnabled
);
const tx = await this.buildTransaction(updateSpotMarketOrdersEnabledIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketOrdersEnabledIx(
spotMarketIndex: number,
ordersEnabled: boolean
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketOrdersEnabled(
ordersEnabled,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updateSpotMarketIfPausedOperations(
spotMarketIndex: number,
pausedOperations: number
): Promise<TransactionSignature> {
const updateSpotMarketIfStakingDisabledIx =
await this.getUpdateSpotMarketIfPausedOperationsIx(
spotMarketIndex,
pausedOperations
);
const tx = await this.buildTransaction(updateSpotMarketIfStakingDisabledIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketIfPausedOperationsIx(
spotMarketIndex: number,
pausedOperations: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketIfPausedOperations(
pausedOperations,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updateSerumFulfillmentConfigStatus(
serumFulfillmentConfig: PublicKey,
status: SpotFulfillmentConfigStatus
): Promise<TransactionSignature> {
const updateSerumFulfillmentConfigStatusIx =
await this.getUpdateSerumFulfillmentConfigStatusIx(
serumFulfillmentConfig,
status
);
const tx = await this.buildTransaction(
updateSerumFulfillmentConfigStatusIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSerumFulfillmentConfigStatusIx(
serumFulfillmentConfig: PublicKey,
status: SpotFulfillmentConfigStatus
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSerumFulfillmentConfigStatus(
status,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
serumFulfillmentConfig,
},
}
);
}
public async updatePhoenixFulfillmentConfigStatus(
phoenixFulfillmentConfig: PublicKey,
status: SpotFulfillmentConfigStatus
): Promise<TransactionSignature> {
const updatePhoenixFulfillmentConfigStatusIx =
await this.program.instruction.phoenixFulfillmentConfigStatus(status, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
phoenixFulfillmentConfig,
},
});
const tx = await this.buildTransaction(
updatePhoenixFulfillmentConfigStatusIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePhoenixFulfillmentConfigStatusIx(
phoenixFulfillmentConfig: PublicKey,
status: SpotFulfillmentConfigStatus
): Promise<TransactionInstruction> {
return await this.program.instruction.phoenixFulfillmentConfigStatus(
status,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
phoenixFulfillmentConfig,
},
}
);
}
public async updateSpotMarketExpiry(
spotMarketIndex: number,
expiryTs: BN
): Promise<TransactionSignature> {
const updateSpotMarketExpiryIx = await this.getUpdateSpotMarketExpiryIx(
spotMarketIndex,
expiryTs
);
const tx = await this.buildTransaction(updateSpotMarketExpiryIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketExpiryIx(
spotMarketIndex: number,
expiryTs: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketExpiry(expiryTs, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
});
}
public async updateWhitelistMint(
whitelistMint?: PublicKey
): Promise<TransactionSignature> {
const updateWhitelistMintIx = await this.getUpdateWhitelistMintIx(
whitelistMint
);
const tx = await this.buildTransaction(updateWhitelistMintIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateWhitelistMintIx(
whitelistMint?: PublicKey
): Promise<TransactionInstruction> {
return await this.program.instruction.updateWhitelistMint(whitelistMint, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
});
}
public async updateDiscountMint(
discountMint: PublicKey
): Promise<TransactionSignature> {
const updateDiscountMintIx = await this.getUpdateDiscountMintIx(
discountMint
);
const tx = await this.buildTransaction(updateDiscountMintIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateDiscountMintIx(
discountMint: PublicKey
): Promise<TransactionInstruction> {
return await this.program.instruction.updateDiscountMint(discountMint, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
});
}
public async updateSpotMarketMarginWeights(
spotMarketIndex: number,
initialAssetWeight: number,
maintenanceAssetWeight: number,
initialLiabilityWeight: number,
maintenanceLiabilityWeight: number,
imfFactor = 0
): Promise<TransactionSignature> {
const updateSpotMarketMarginWeightsIx =
await this.getUpdateSpotMarketMarginWeightsIx(
spotMarketIndex,
initialAssetWeight,
maintenanceAssetWeight,
initialLiabilityWeight,
maintenanceLiabilityWeight,
imfFactor
);
const tx = await this.buildTransaction(updateSpotMarketMarginWeightsIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketMarginWeightsIx(
spotMarketIndex: number,
initialAssetWeight: number,
maintenanceAssetWeight: number,
initialLiabilityWeight: number,
maintenanceLiabilityWeight: number,
imfFactor = 0
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketMarginWeights(
initialAssetWeight,
maintenanceAssetWeight,
initialLiabilityWeight,
maintenanceLiabilityWeight,
imfFactor,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updateSpotMarketBorrowRate(
spotMarketIndex: number,
optimalUtilization: number,
optimalBorrowRate: number,
optimalMaxRate: number,
minBorrowRate?: number | undefined
): Promise<TransactionSignature> {
const updateSpotMarketBorrowRateIx =
await this.getUpdateSpotMarketBorrowRateIx(
spotMarketIndex,
optimalUtilization,
optimalBorrowRate,
optimalMaxRate,
minBorrowRate
);
const tx = await this.buildTransaction(updateSpotMarketBorrowRateIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketBorrowRateIx(
spotMarketIndex: number,
optimalUtilization: number,
optimalBorrowRate: number,
optimalMaxRate: number,
minBorrowRate?: number | undefined
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketBorrowRate(
optimalUtilization,
optimalBorrowRate,
optimalMaxRate,
minBorrowRate,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updateSpotMarketAssetTier(
spotMarketIndex: number,
assetTier: AssetTier
): Promise<TransactionSignature> {
const updateSpotMarketAssetTierIx =
await this.getUpdateSpotMarketAssetTierIx(spotMarketIndex, assetTier);
const tx = await this.buildTransaction(updateSpotMarketAssetTierIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketAssetTierIx(
spotMarketIndex: number,
assetTier: AssetTier
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketAssetTier(assetTier, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
});
}
public async updateSpotMarketStatus(
spotMarketIndex: number,
marketStatus: MarketStatus
): Promise<TransactionSignature> {
const updateSpotMarketStatusIx = await this.getUpdateSpotMarketStatusIx(
spotMarketIndex,
marketStatus
);
const tx = await this.buildTransaction(updateSpotMarketStatusIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketStatusIx(
spotMarketIndex: number,
marketStatus: MarketStatus
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketStatus(marketStatus, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
});
}
public async updateSpotMarketPausedOperations(
spotMarketIndex: number,
pausedOperations: number
): Promise<TransactionSignature> {
const updateSpotMarketPausedOperationsIx =
await this.getUpdateSpotMarketPausedOperationsIx(
spotMarketIndex,
pausedOperations
);
const tx = await this.buildTransaction(updateSpotMarketPausedOperationsIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketPausedOperationsIx(
spotMarketIndex: number,
pausedOperations: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketPausedOperations(
pausedOperations,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updatePerpMarketStatus(
perpMarketIndex: number,
marketStatus: MarketStatus
): Promise<TransactionSignature> {
const updatePerpMarketStatusIx = await this.getUpdatePerpMarketStatusIx(
perpMarketIndex,
marketStatus
);
const tx = await this.buildTransaction(updatePerpMarketStatusIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketStatusIx(
perpMarketIndex: number,
marketStatus: MarketStatus
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketStatus(marketStatus, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
});
}
public async updatePerpMarketPausedOperations(
perpMarketIndex: number,
pausedOperations: number
): Promise<TransactionSignature> {
const updatePerpMarketPausedOperationsIx =
await this.getUpdatePerpMarketPausedOperationsIx(
perpMarketIndex,
pausedOperations
);
const tx = await this.buildTransaction(updatePerpMarketPausedOperationsIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketPausedOperationsIx(
perpMarketIndex: number,
pausedOperations: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketPausedOperations(
pausedOperations,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updatePerpMarketContractTier(
perpMarketIndex: number,
contractTier: ContractTier
): Promise<TransactionSignature> {
const updatePerpMarketContractTierIx =
await this.getUpdatePerpMarketContractTierIx(
perpMarketIndex,
contractTier
);
const tx = await this.buildTransaction(updatePerpMarketContractTierIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketContractTierIx(
perpMarketIndex: number,
contractTier: ContractTier
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketContractTier(
contractTier,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updateExchangeStatus(
exchangeStatus: ExchangeStatus
): Promise<TransactionSignature> {
const updateExchangeStatusIx = await this.getUpdateExchangeStatusIx(
exchangeStatus
);
const tx = await this.buildTransaction(updateExchangeStatusIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateExchangeStatusIx(
exchangeStatus: ExchangeStatus
): Promise<TransactionInstruction> {
return await this.program.instruction.updateExchangeStatus(exchangeStatus, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
});
}
public async updatePerpAuctionDuration(
minDuration: BN | number
): Promise<TransactionSignature> {
const updatePerpAuctionDurationIx =
await this.getUpdatePerpAuctionDurationIx(minDuration);
const tx = await this.buildTransaction(updatePerpAuctionDurationIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpAuctionDurationIx(
minDuration: BN | number
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpAuctionDuration(
typeof minDuration === 'number' ? minDuration : minDuration.toNumber(),
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
}
);
}
public async updateSpotAuctionDuration(
defaultAuctionDuration: number
): Promise<TransactionSignature> {
const updateSpotAuctionDurationIx =
await this.getUpdateSpotAuctionDurationIx(defaultAuctionDuration);
const tx = await this.buildTransaction(updateSpotAuctionDurationIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotAuctionDurationIx(
defaultAuctionDuration: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotAuctionDuration(
defaultAuctionDuration,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
}
);
}
public async updatePerpMarketMaxFillReserveFraction(
perpMarketIndex: number,
maxBaseAssetAmountRatio: number
): Promise<TransactionSignature> {
const updatePerpMarketMaxFillReserveFractionIx =
await this.getUpdatePerpMarketMaxFillReserveFractionIx(
perpMarketIndex,
maxBaseAssetAmountRatio
);
const tx = await this.buildTransaction(
updatePerpMarketMaxFillReserveFractionIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketMaxFillReserveFractionIx(
perpMarketIndex: number,
maxBaseAssetAmountRatio: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketMaxFillReserveFraction(
maxBaseAssetAmountRatio,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updateMaxSlippageRatio(
perpMarketIndex: number,
maxSlippageRatio: number
): Promise<TransactionSignature> {
const updateMaxSlippageRatioIx = await this.getUpdateMaxSlippageRatioIx(
perpMarketIndex,
maxSlippageRatio
);
const tx = await this.buildTransaction(updateMaxSlippageRatioIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateMaxSlippageRatioIx(
perpMarketIndex: number,
maxSlippageRatio: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateMaxSlippageRatio(
maxSlippageRatio,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: this.getPerpMarketAccount(perpMarketIndex).pubkey,
},
}
);
}
public async updatePerpMarketUnrealizedAssetWeight(
perpMarketIndex: number,
unrealizedInitialAssetWeight: number,
unrealizedMaintenanceAssetWeight: number
): Promise<TransactionSignature> {
const updatePerpMarketUnrealizedAssetWeightIx =
await this.getUpdatePerpMarketUnrealizedAssetWeightIx(
perpMarketIndex,
unrealizedInitialAssetWeight,
unrealizedMaintenanceAssetWeight
);
const tx = await this.buildTransaction(
updatePerpMarketUnrealizedAssetWeightIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketUnrealizedAssetWeightIx(
perpMarketIndex: number,
unrealizedInitialAssetWeight: number,
unrealizedMaintenanceAssetWeight: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketUnrealizedAssetWeight(
unrealizedInitialAssetWeight,
unrealizedMaintenanceAssetWeight,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updatePerpMarketMaxImbalances(
perpMarketIndex: number,
unrealizedMaxImbalance: BN,
maxRevenueWithdrawPerPeriod: BN,
quoteMaxInsurance: BN
): Promise<TransactionSignature> {
const updatePerpMarketMaxImabalancesIx =
await this.getUpdatePerpMarketMaxImbalancesIx(
perpMarketIndex,
unrealizedMaxImbalance,
maxRevenueWithdrawPerPeriod,
quoteMaxInsurance
);
const tx = await this.buildTransaction(updatePerpMarketMaxImabalancesIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketMaxImbalancesIx(
perpMarketIndex: number,
unrealizedMaxImbalance: BN,
maxRevenueWithdrawPerPeriod: BN,
quoteMaxInsurance: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketMaxImbalances(
unrealizedMaxImbalance,
maxRevenueWithdrawPerPeriod,
quoteMaxInsurance,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updatePerpMarketMaxOpenInterest(
perpMarketIndex: number,
maxOpenInterest: BN
): Promise<TransactionSignature> {
const updatePerpMarketMaxOpenInterestIx =
await this.getUpdatePerpMarketMaxOpenInterestIx(
perpMarketIndex,
maxOpenInterest
);
const tx = await this.buildTransaction(updatePerpMarketMaxOpenInterestIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketMaxOpenInterestIx(
perpMarketIndex: number,
maxOpenInterest: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketMaxOpenInterest(
maxOpenInterest,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updatePerpMarketNumberOfUser(
perpMarketIndex: number,
numberOfUsers?: number,
numberOfUsersWithBase?: number
): Promise<TransactionSignature> {
const updatepPerpMarketFeeAdjustmentIx =
await this.getUpdatePerpMarketNumberOfUsersIx(
perpMarketIndex,
numberOfUsers,
numberOfUsersWithBase
);
const tx = await this.buildTransaction(updatepPerpMarketFeeAdjustmentIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketNumberOfUsersIx(
perpMarketIndex: number,
numberOfUsers?: number,
numberOfUsersWithBase?: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketNumberOfUsers(
numberOfUsers,
numberOfUsersWithBase,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updatePerpMarketFeeAdjustment(
perpMarketIndex: number,
feeAdjustment: number
): Promise<TransactionSignature> {
const updatepPerpMarketFeeAdjustmentIx =
await this.getUpdatePerpMarketFeeAdjustmentIx(
perpMarketIndex,
feeAdjustment
);
const tx = await this.buildTransaction(updatepPerpMarketFeeAdjustmentIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketFeeAdjustmentIx(
perpMarketIndex: number,
feeAdjustment: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketFeeAdjustment(
feeAdjustment,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updateSpotMarketFeeAdjustment(
perpMarketIndex: number,
feeAdjustment: number
): Promise<TransactionSignature> {
const updateSpotMarketFeeAdjustmentIx =
await this.getUpdateSpotMarketFeeAdjustmentIx(
perpMarketIndex,
feeAdjustment
);
const tx = await this.buildTransaction(updateSpotMarketFeeAdjustmentIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketFeeAdjustmentIx(
spotMarketIndex: number,
feeAdjustment: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketFeeAdjustment(
feeAdjustment,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async updateSerumVault(
srmVault: PublicKey
): Promise<TransactionSignature> {
const updateSerumVaultIx = await this.getUpdateSerumVaultIx(srmVault);
const tx = await this.buildTransaction(updateSerumVaultIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSerumVaultIx(
srmVault: PublicKey
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSerumVault(srmVault, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
srmVault: srmVault,
},
});
}
public async updatePerpMarketLiquidationFee(
perpMarketIndex: number,
liquidatorFee: number,
ifLiquidationFee: number
): Promise<TransactionSignature> {
const updatePerpMarketLiquidationFeeIx =
await this.getUpdatePerpMarketLiquidationFeeIx(
perpMarketIndex,
liquidatorFee,
ifLiquidationFee
);
const tx = await this.buildTransaction(updatePerpMarketLiquidationFeeIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketLiquidationFeeIx(
perpMarketIndex: number,
liquidatorFee: number,
ifLiquidationFee: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updatePerpMarketLiquidationFee(
liquidatorFee,
ifLiquidationFee,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
),
},
}
);
}
public async updateSpotMarketLiquidationFee(
spotMarketIndex: number,
liquidatorFee: number,
ifLiquidationFee: number
): Promise<TransactionSignature> {
const updateSpotMarketLiquidationFeeIx =
await this.getUpdateSpotMarketLiquidationFeeIx(
spotMarketIndex,
liquidatorFee,
ifLiquidationFee
);
const tx = await this.buildTransaction(updateSpotMarketLiquidationFeeIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketLiquidationFeeIx(
spotMarketIndex: number,
liquidatorFee: number,
ifLiquidationFee: number
): Promise<TransactionInstruction> {
return await this.program.instruction.updateSpotMarketLiquidationFee(
liquidatorFee,
ifLiquidationFee,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
),
},
}
);
}
public async initializeProtocolIfSharesTransferConfig(): Promise<TransactionSignature> {
const initializeProtocolIfSharesTransferConfigIx =
await this.getInitializeProtocolIfSharesTransferConfigIx();
const tx = await this.buildTransaction(
initializeProtocolIfSharesTransferConfigIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getInitializeProtocolIfSharesTransferConfigIx(): Promise<TransactionInstruction> {
return await this.program.instruction.initializeProtocolIfSharesTransferConfig(
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
rent: SYSVAR_RENT_PUBKEY,
systemProgram: anchor.web3.SystemProgram.programId,
protocolIfSharesTransferConfig:
getProtocolIfSharesTransferConfigPublicKey(this.program.programId),
},
}
);
}
public async updateProtocolIfSharesTransferConfig(
whitelistedSigners?: PublicKey[],
maxTransferPerEpoch?: BN
): Promise<TransactionSignature> {
const updateProtocolIfSharesTransferConfigIx =
await this.getUpdateProtocolIfSharesTransferConfigIx(
whitelistedSigners,
maxTransferPerEpoch
);
const tx = await this.buildTransaction(
updateProtocolIfSharesTransferConfigIx
);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateProtocolIfSharesTransferConfigIx(
whitelistedSigners?: PublicKey[],
maxTransferPerEpoch?: BN
): Promise<TransactionInstruction> {
return await this.program.instruction.updateProtocolIfSharesTransferConfig(
whitelistedSigners || null,
maxTransferPerEpoch,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
protocolIfSharesTransferConfig:
getProtocolIfSharesTransferConfigPublicKey(this.program.programId),
},
}
);
}
public async initializePrelaunchOracle(
perpMarketIndex: number,
price?: BN,
maxPrice?: BN
): Promise<TransactionSignature> {
const initializePrelaunchOracleIx =
await this.getInitializePrelaunchOracleIx(
perpMarketIndex,
price,
maxPrice
);
const tx = await this.buildTransaction(initializePrelaunchOracleIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getInitializePrelaunchOracleIx(
perpMarketIndex: number,
price?: BN,
maxPrice?: BN
): Promise<TransactionInstruction> {
const params = {
perpMarketIndex,
price: price || null,
maxPrice: maxPrice || null,
};
return await this.program.instruction.initializePrelaunchOracle(params, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
prelaunchOracle: await getPrelaunchOraclePublicKey(
this.program.programId,
perpMarketIndex
),
rent: SYSVAR_RENT_PUBKEY,
systemProgram: anchor.web3.SystemProgram.programId,
},
});
}
public async updatePrelaunchOracleParams(
perpMarketIndex: number,
price?: BN,
maxPrice?: BN
): Promise<TransactionSignature> {
const updatePrelaunchOracleParamsIx =
await this.getUpdatePrelaunchOracleParamsIx(
perpMarketIndex,
price,
maxPrice
);
const tx = await this.buildTransaction(updatePrelaunchOracleParamsIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePrelaunchOracleParamsIx(
perpMarketIndex: number,
price?: BN,
maxPrice?: BN
): Promise<TransactionInstruction> {
const params = {
perpMarketIndex,
price: price || null,
maxPrice: maxPrice || null,
};
const perpMarketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
);
return await this.program.instruction.updatePrelaunchOracleParams(params, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: perpMarketPublicKey,
prelaunchOracle: await getPrelaunchOraclePublicKey(
this.program.programId,
perpMarketIndex
),
},
});
}
public async deletePrelaunchOracle(
perpMarketIndex: number
): Promise<TransactionSignature> {
const deletePrelaunchOracleIx = await this.getDeletePrelaunchOracleIx(
perpMarketIndex
);
const tx = await this.buildTransaction(deletePrelaunchOracleIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getDeletePrelaunchOracleIx(
perpMarketIndex: number,
price?: BN,
maxPrice?: BN
): Promise<TransactionInstruction> {
const params = {
perpMarketIndex,
price: price || null,
maxPrice: maxPrice || null,
};
const perpMarketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
);
return await this.program.instruction.deletePrelaunchOracle(params, {
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: perpMarketPublicKey,
prelaunchOracle: await getPrelaunchOraclePublicKey(
this.program.programId,
perpMarketIndex
),
},
});
}
public async updateSpotMarketFuel(
spotMarketIndex: number,
fuelBoostDeposits?: number,
fuelBoostBorrows?: number,
fuelBoostTaker?: number,
fuelBoostMaker?: number,
fuelBoostInsurance?: number
): Promise<TransactionSignature> {
const updateSpotMarketFuelIx = await this.getUpdateSpotMarketFuelIx(
spotMarketIndex,
fuelBoostDeposits || null,
fuelBoostBorrows || null,
fuelBoostTaker || null,
fuelBoostMaker || null,
fuelBoostInsurance || null
);
const tx = await this.buildTransaction(updateSpotMarketFuelIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateSpotMarketFuelIx(
spotMarketIndex: number,
fuelBoostDeposits?: number,
fuelBoostBorrows?: number,
fuelBoostTaker?: number,
fuelBoostMaker?: number,
fuelBoostInsurance?: number
): Promise<TransactionInstruction> {
const spotMarketPublicKey = await getSpotMarketPublicKey(
this.program.programId,
spotMarketIndex
);
return await this.program.instruction.updateSpotMarketFuel(
fuelBoostDeposits || null,
fuelBoostBorrows || null,
fuelBoostTaker || null,
fuelBoostMaker || null,
fuelBoostInsurance || null,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
spotMarket: spotMarketPublicKey,
},
}
);
}
public async updatePerpMarketFuel(
perpMarketIndex: number,
fuelBoostTaker?: number,
fuelBoostMaker?: number,
fuelBoostPosition?: number
): Promise<TransactionSignature> {
const updatePerpMarketFuelIx = await this.getUpdatePerpMarketFuelIx(
perpMarketIndex,
fuelBoostTaker || null,
fuelBoostMaker || null,
fuelBoostPosition || null
);
const tx = await this.buildTransaction(updatePerpMarketFuelIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdatePerpMarketFuelIx(
perpMarketIndex: number,
fuelBoostTaker?: number,
fuelBoostMaker?: number,
fuelBoostPosition?: number
): Promise<TransactionInstruction> {
const perpMarketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
);
return await this.program.instruction.updatePerpMarketFuel(
fuelBoostTaker || null,
fuelBoostMaker || null,
fuelBoostPosition || null,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
perpMarket: perpMarketPublicKey,
},
}
);
}
public async initUserFuel(
user: PublicKey,
authority: PublicKey,
fuelBonusDeposits?: number,
fuelBonusBorrows?: number,
fuelBonusTaker?: number,
fuelBonusMaker?: number,
fuelBonusInsurance?: number
): Promise<TransactionSignature> {
const updatePerpMarketFuelIx = await this.getInitUserFuelIx(
user,
authority,
fuelBonusDeposits,
fuelBonusBorrows,
fuelBonusTaker,
fuelBonusMaker,
fuelBonusInsurance
);
const tx = await this.buildTransaction(updatePerpMarketFuelIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getInitUserFuelIx(
user: PublicKey,
authority: PublicKey,
fuelBonusDeposits?: number,
fuelBonusBorrows?: number,
fuelBonusTaker?: number,
fuelBonusMaker?: number,
fuelBonusInsurance?: number
): Promise<TransactionInstruction> {
const userStats = await getUserStatsAccountPublicKey(
this.program.programId,
authority
);
return await this.program.instruction.initUserFuel(
fuelBonusDeposits || null,
fuelBonusBorrows || null,
fuelBonusTaker || null,
fuelBonusMaker || null,
fuelBonusInsurance || null,
{
accounts: {
admin: this.wallet.publicKey,
state: await this.getStatePublicKey(),
user,
userStats,
},
}
);
}
public async initializePythPullOracle(
feedId: string,
isAdmin = false
): Promise<TransactionSignature> {
const initializePythPullOracleIx = await this.getInitializePythPullOracleIx(
feedId,
isAdmin
);
const tx = await this.buildTransaction(initializePythPullOracleIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getInitializePythPullOracleIx(
feedId: string,
isAdmin = false
): Promise<TransactionInstruction> {
const feedIdBuffer = getFeedIdUint8Array(feedId);
return await this.program.instruction.initializePythPullOracle(
feedIdBuffer,
{
accounts: {
admin: isAdmin ? this.getStateAccount().admin : this.wallet.publicKey,
state: await this.getStatePublicKey(),
systemProgram: SystemProgram.programId,
priceFeed: getPythPullOraclePublicKey(
this.program.programId,
feedIdBuffer
),
pythSolanaReceiver: DRIFT_ORACLE_RECEIVER_ID,
},
}
);
}
public async initializePythLazerOracle(
feedId: number,
isAdmin = false
): Promise<TransactionSignature> {
const initializePythPullOracleIx =
await this.getInitializePythLazerOracleIx(feedId, isAdmin);
const tx = await this.buildTransaction(initializePythPullOracleIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getInitializePythLazerOracleIx(
feedId: number,
isAdmin = false
): Promise<TransactionInstruction> {
return await this.program.instruction.initializePythLazerOracle(feedId, {
accounts: {
admin: isAdmin ? this.getStateAccount().admin : this.wallet.publicKey,
state: await this.getStatePublicKey(),
systemProgram: SystemProgram.programId,
lazerOracle: getPythLazerOraclePublicKey(
this.program.programId,
feedId
),
rent: SYSVAR_RENT_PUBKEY,
},
});
}
public async initializeHighLeverageModeConfig(
maxUsers: number
): Promise<TransactionSignature> {
const initializeHighLeverageModeConfigIx =
await this.getInitializeHighLeverageModeConfigIx(maxUsers);
const tx = await this.buildTransaction(initializeHighLeverageModeConfigIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getInitializeHighLeverageModeConfigIx(
maxUsers: number
): Promise<TransactionInstruction> {
return await this.program.instruction.initializeHighLeverageModeConfig(
maxUsers,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
rent: SYSVAR_RENT_PUBKEY,
systemProgram: anchor.web3.SystemProgram.programId,
highLeverageModeConfig: getHighLeverageModeConfigPublicKey(
this.program.programId
),
},
}
);
}
public async updateUpdateHighLeverageModeConfig(
maxUsers: number,
reduceOnly: boolean
): Promise<TransactionSignature> {
const updateHighLeverageModeConfigIx =
await this.getUpdateHighLeverageModeConfigIx(maxUsers, reduceOnly);
const tx = await this.buildTransaction(updateHighLeverageModeConfigIx);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
public async getUpdateHighLeverageModeConfigIx(
maxUsers: number,
reduceOnly: boolean
): Promise<TransactionInstruction> {
return await this.program.instruction.updateHighLeverageModeConfig(
maxUsers,
reduceOnly,
{
accounts: {
admin: this.isSubscribed
? this.getStateAccount().admin
: this.wallet.publicKey,
state: await this.getStatePublicKey(),
highLeverageModeConfig: getHighLeverageModeConfigPublicKey(
this.program.programId
),
},
}
);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/index.ts
|
import { BN } from '@coral-xyz/anchor';
import { PublicKey } from '@solana/web3.js';
import pyth from '@pythnetwork/client';
export * from './tokenFaucet';
export * from './oracles/types';
export * from './oracles/pythClient';
export * from './oracles/strictOraclePrice';
export * from './types';
export * from './constants/perpMarkets';
export * from './accounts/fetch';
export * from './accounts/webSocketDriftClientAccountSubscriber';
export * from './accounts/webSocketInsuranceFundStakeAccountSubscriber';
export * from './accounts/webSocketHighLeverageModeConfigAccountSubscriber';
export * from './accounts/bulkAccountLoader';
export * from './accounts/bulkUserSubscription';
export * from './accounts/bulkUserStatsSubscription';
export * from './accounts/pollingDriftClientAccountSubscriber';
export * from './accounts/pollingOracleAccountSubscriber';
export * from './accounts/pollingTokenAccountSubscriber';
export * from './accounts/pollingUserAccountSubscriber';
export * from './accounts/pollingUserStatsAccountSubscriber';
export * from './accounts/pollingInsuranceFundStakeAccountSubscriber';
export * from './accounts/pollingHighLeverageModeConfigAccountSubscriber';
export * from './accounts/basicUserAccountSubscriber';
export * from './accounts/oneShotUserAccountSubscriber';
export * from './accounts/types';
export * from './addresses/pda';
export * from './adminClient';
export * from './assert/assert';
export * from './testClient';
export * from './user';
export * from './userConfig';
export * from './userStats';
export * from './userName';
export * from './userStatsConfig';
export * from './decode/user';
export * from './driftClient';
export * from './factory/oracleClient';
export * from './factory/bigNum';
export * from './events/types';
export * from './events/eventSubscriber';
export * from './events/fetchLogs';
export * from './events/txEventCache';
export * from './events/webSocketLogProvider';
export * from './events/parse';
export * from './events/pollingLogProvider';
export * from './jupiter/jupiterClient';
export * from './math/auction';
export * from './math/spotMarket';
export * from './math/conversion';
export * from './math/exchangeStatus';
export * from './math/funding';
export * from './math/market';
export * from './math/position';
export * from './math/oracles';
export * from './math/amm';
export * from './math/trade';
export * from './math/orders';
export * from './math/repeg';
export * from './math/margin';
export * from './math/insurance';
export * from './math/superStake';
export * from './math/spotPosition';
export * from './math/state';
export * from './math/tiers';
export * from './marinade';
export * from './orderParams';
export * from './slot/SlotSubscriber';
export * from './slot/SlothashSubscriber';
export * from './wallet';
export * from './keypair';
export * from './types';
export * from './math/utils';
export * from './math/fuel';
export * from './config';
export * from './constants/numericConstants';
export * from './serum/serumSubscriber';
export * from './serum/serumFulfillmentConfigMap';
export * from './phoenix/phoenixSubscriber';
export * from './priorityFee';
export * from './phoenix/phoenixFulfillmentConfigMap';
export * from './openbook/openbookV2Subscriber';
export * from './openbook/openbookV2FulfillmentConfigMap';
export * from './oracles/pythClient';
export * from './oracles/pythPullClient';
export * from './oracles/pythLazerClient';
export * from './oracles/switchboardOnDemandClient';
export * from './tx/fastSingleTxSender';
export * from './tx/retryTxSender';
export * from './tx/whileValidTxSender';
export * from './tx/priorityFeeCalculator';
export * from './tx/forwardOnlyTxSender';
export * from './tx/types';
export * from './tx/txHandler';
export * from './util/computeUnits';
export * from './util/digest';
export * from './util/tps';
export * from './util/promiseTimeout';
export * from './util/pythOracleUtils';
export * from './math/spotBalance';
export * from './constants/spotMarkets';
export * from './driftClientConfig';
export * from './dlob/DLOB';
export * from './dlob/DLOBNode';
export * from './dlob/NodeList';
export * from './dlob/DLOBSubscriber';
export * from './dlob/types';
export * from './dlob/orderBookLevels';
export * from './userMap/userMap';
export * from './userMap/referrerMap';
export * from './userMap/userStatsMap';
export * from './userMap/userMapConfig';
export * from './math/bankruptcy';
export * from './orderSubscriber';
export * from './orderSubscriber/types';
export * from './auctionSubscriber';
export * from './auctionSubscriber/types';
export * from './memcmp';
export * from './decode/user';
export * from './blockhashSubscriber';
export * from './util/chainClock';
export * from './util/TransactionConfirmationManager';
export * from './clock/clockSubscriber';
export * from './math/userStatus';
export { BN, PublicKey, pyth };
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/driftClientConfig.ts
|
import {
Commitment,
ConfirmOptions,
Connection,
PublicKey,
TransactionVersion,
} from '@solana/web3.js';
import { IWallet, TxParams } from './types';
import { OracleInfo } from './oracles/types';
import { BulkAccountLoader } from './accounts/bulkAccountLoader';
import { DriftEnv } from './config';
import { TxSender } from './tx/types';
import { TxHandler, TxHandlerConfig } from './tx/txHandler';
import { DelistedMarketSetting, GrpcConfigs } from './accounts/types';
export type DriftClientConfig = {
connection: Connection;
wallet: IWallet;
env?: DriftEnv;
programID?: PublicKey;
swiftID?: PublicKey;
accountSubscription?: DriftClientSubscriptionConfig;
opts?: ConfirmOptions;
txSender?: TxSender;
txHandler?: TxHandler;
subAccountIds?: number[];
activeSubAccountId?: number;
perpMarketIndexes?: number[];
spotMarketIndexes?: number[];
marketLookupTable?: PublicKey;
oracleInfos?: OracleInfo[];
userStats?: boolean;
authority?: PublicKey; // explicitly pass an authority if signer is delegate
includeDelegates?: boolean; // flag for whether to load delegate accounts as well
authoritySubAccountMap?: Map<string, number[]>; // if passed this will override subAccountIds and includeDelegates
skipLoadUsers?: boolean; // if passed to constructor, no user accounts will be loaded. they will load if updateWallet is called afterwards.
txVersion?: TransactionVersion; // which tx version to use
txParams?: TxParams; // default tx params to use
enableMetricsEvents?: boolean;
txHandlerConfig?: TxHandlerConfig;
delistedMarketSetting?: DelistedMarketSetting;
};
export type DriftClientSubscriptionConfig =
| {
type: 'grpc';
grpcConfigs: GrpcConfigs;
resubTimeoutMs?: number;
logResubMessages?: boolean;
}
| {
type: 'websocket';
resubTimeoutMs?: number;
logResubMessages?: boolean;
commitment?: Commitment;
}
| {
type: 'polling';
accountLoader: BulkAccountLoader;
};
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/userStats.ts
|
import { DriftClient } from './driftClient';
import { PublicKey } from '@solana/web3.js';
import { DataAndSlot, UserStatsAccountSubscriber } from './accounts/types';
import { UserStatsConfig } from './userStatsConfig';
import { PollingUserStatsAccountSubscriber } from './accounts/pollingUserStatsAccountSubscriber';
import { WebSocketUserStatsAccountSubscriber } from './accounts/webSocketUserStatsAccountSubsriber';
import { ReferrerInfo, SpotMarketAccount, UserStatsAccount } from './types';
import {
getUserAccountPublicKeySync,
getUserStatsAccountPublicKey,
} from './addresses/pda';
import { grpcUserStatsAccountSubscriber } from './accounts/grpcUserStatsAccountSubscriber';
import { FUEL_START_TS } from './constants/numericConstants';
import { ZERO } from './constants/numericConstants';
import {
GOV_SPOT_MARKET_INDEX,
QUOTE_SPOT_MARKET_INDEX,
} from './constants/numericConstants';
import { BN } from '@coral-xyz/anchor';
import { calculateInsuranceFuelBonus } from './math/fuel';
export class UserStats {
driftClient: DriftClient;
userStatsAccountPublicKey: PublicKey;
accountSubscriber: UserStatsAccountSubscriber;
isSubscribed: boolean;
public constructor(config: UserStatsConfig) {
this.driftClient = config.driftClient;
this.userStatsAccountPublicKey = config.userStatsAccountPublicKey;
if (config.accountSubscription?.type === 'polling') {
this.accountSubscriber = new PollingUserStatsAccountSubscriber(
config.driftClient.program,
config.userStatsAccountPublicKey,
config.accountSubscription.accountLoader
);
} else if (config.accountSubscription?.type === 'grpc') {
this.accountSubscriber = new grpcUserStatsAccountSubscriber(
config.accountSubscription.grpcConfigs,
config.driftClient.program,
config.userStatsAccountPublicKey,
{
resubTimeoutMs: config.accountSubscription?.resubTimeoutMs,
logResubMessages: config.accountSubscription?.logResubMessages,
}
);
} else if (config.accountSubscription?.type === 'websocket') {
this.accountSubscriber = new WebSocketUserStatsAccountSubscriber(
config.driftClient.program,
config.userStatsAccountPublicKey,
{
resubTimeoutMs: config.accountSubscription?.resubTimeoutMs,
logResubMessages: config.accountSubscription?.logResubMessages,
},
config.accountSubscription.commitment
);
} else {
throw new Error(
`Unknown user stats account subscription type: ${config.accountSubscription?.type}`
);
}
}
public async subscribe(
userStatsAccount?: UserStatsAccount
): Promise<boolean> {
this.isSubscribed = await this.accountSubscriber.subscribe(
userStatsAccount
);
return this.isSubscribed;
}
public async fetchAccounts(): Promise<void> {
await this.accountSubscriber.fetch();
}
public async unsubscribe(): Promise<void> {
await this.accountSubscriber.unsubscribe();
this.isSubscribed = false;
}
public getAccountAndSlot(): DataAndSlot<UserStatsAccount> {
return this.accountSubscriber.getUserStatsAccountAndSlot();
}
public getAccount(): UserStatsAccount {
return this.accountSubscriber.getUserStatsAccountAndSlot().data;
}
public getInsuranceFuelBonus(
now: BN,
includeSettled = true,
includeUnsettled = true
): BN {
const userStats: UserStatsAccount = this.getAccount();
let insuranceFuel = ZERO;
if (includeSettled) {
insuranceFuel = insuranceFuel.add(new BN(userStats.fuelInsurance));
}
if (includeUnsettled) {
// todo: get real time ifStakedGovTokenAmount using ifStakeAccount
if (userStats.ifStakedGovTokenAmount.gt(ZERO)) {
const spotMarketAccount: SpotMarketAccount =
this.driftClient.getSpotMarketAccount(GOV_SPOT_MARKET_INDEX);
const fuelBonusNumeratorUserStats = BN.max(
now.sub(
BN.max(new BN(userStats.lastFuelIfBonusUpdateTs), FUEL_START_TS)
),
ZERO
);
insuranceFuel = insuranceFuel.add(
calculateInsuranceFuelBonus(
spotMarketAccount,
userStats.ifStakedGovTokenAmount,
fuelBonusNumeratorUserStats
)
);
}
if (userStats.ifStakedQuoteAssetAmount.gt(ZERO)) {
const spotMarketAccount: SpotMarketAccount =
this.driftClient.getSpotMarketAccount(QUOTE_SPOT_MARKET_INDEX);
const fuelBonusNumeratorUserStats = BN.max(
now.sub(
BN.max(new BN(userStats.lastFuelIfBonusUpdateTs), FUEL_START_TS)
),
ZERO
);
insuranceFuel = insuranceFuel.add(
calculateInsuranceFuelBonus(
spotMarketAccount,
userStats.ifStakedQuoteAssetAmount,
fuelBonusNumeratorUserStats
)
);
}
}
return insuranceFuel;
}
public getReferrerInfo(): ReferrerInfo | undefined {
if (this.getAccount().referrer.equals(PublicKey.default)) {
return undefined;
} else {
return {
referrer: getUserAccountPublicKeySync(
this.driftClient.program.programId,
this.getAccount().referrer,
0
),
referrerStats: getUserStatsAccountPublicKey(
this.driftClient.program.programId,
this.getAccount().referrer
),
};
}
}
public static getOldestActionTs(account: UserStatsAccount): number {
return Math.min(
account.lastFillerVolume30DTs.toNumber(),
account.lastMakerVolume30DTs.toNumber(),
account.lastTakerVolume30DTs.toNumber()
);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/config.ts
|
import { ConfirmOptions } from '@solana/web3.js';
import { PerpMarketAccount, PublicKey, SpotMarketAccount } from '.';
import {
DevnetPerpMarkets,
MainnetPerpMarkets,
PerpMarketConfig,
PerpMarkets,
} from './constants/perpMarkets';
import {
SpotMarketConfig,
SpotMarkets,
DevnetSpotMarkets,
MainnetSpotMarkets,
} from './constants/spotMarkets';
import { OracleInfo } from './oracles/types';
import { Program, ProgramAccount } from '@coral-xyz/anchor';
import {
ON_DEMAND_DEVNET_PID,
ON_DEMAND_MAINNET_PID,
} from '@switchboard-xyz/on-demand';
import { getOracleId } from './oracles/oracleId';
type DriftConfig = {
ENV: DriftEnv;
PYTH_ORACLE_MAPPING_ADDRESS: string;
DRIFT_PROGRAM_ID: string;
JIT_PROXY_PROGRAM_ID?: string;
DRIFT_ORACLE_RECEIVER_ID: string;
USDC_MINT_ADDRESS: string;
SERUM_V3: string;
PHOENIX: string;
OPENBOOK: string;
V2_ALPHA_TICKET_MINT_ADDRESS: string;
PERP_MARKETS: PerpMarketConfig[];
SPOT_MARKETS: SpotMarketConfig[];
MARKET_LOOKUP_TABLE: string;
SERUM_LOOKUP_TABLE?: string;
PYTH_PULL_ORACLE_LOOKUP_TABLE?: string;
SB_ON_DEMAND_PID: PublicKey;
};
export type DriftEnv = 'devnet' | 'mainnet-beta';
export const DRIFT_PROGRAM_ID = 'dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH';
export const DRIFT_ORACLE_RECEIVER_ID =
'G6EoTTTgpkNBtVXo96EQp2m6uwwVh2Kt6YidjkmQqoha';
export const SWIFT_ID = 'SW1fThqrxLzVprnCMpiybiqYQfoNCdduC5uWsSUKChS';
export const ANCHOR_TEST_SWIFT_ID =
'DpaEdAPW3ZX67fnczT14AoX12Lx9VMkxvtT81nCHy3Nv';
export const PTYH_LAZER_PROGRAM_ID =
'pytd2yyk641x7ak7mkaasSJVXh6YYZnC7wTmtgAyxPt';
export const PYTH_LAZER_STORAGE_ACCOUNT_KEY = new PublicKey(
'3rdJbqfnagQ4yx9HXJViD4zc4xpiSqmFsKpPuSCQVyQL'
);
export const DEFAULT_CONFIRMATION_OPTS: ConfirmOptions = {
preflightCommitment: 'confirmed',
commitment: 'confirmed',
};
export const configs: { [key in DriftEnv]: DriftConfig } = {
devnet: {
ENV: 'devnet',
PYTH_ORACLE_MAPPING_ADDRESS: 'BmA9Z6FjioHJPpjT39QazZyhDRUdZy2ezwx4GiDdE2u2',
DRIFT_PROGRAM_ID,
JIT_PROXY_PROGRAM_ID: 'J1TnP8zvVxbtF5KFp5xRmWuvG9McnhzmBd9XGfCyuxFP',
USDC_MINT_ADDRESS: '8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2',
SERUM_V3: 'DESVgJVGajEgKGXhb6XmqDHGz3VjdgP7rEVESBgxmroY',
PHOENIX: 'PhoeNiXZ8ByJGLkxNfZRnkUfjvmuYqLR89jjFHGqdXY',
OPENBOOK: 'opnb2LAfJYbRMAHHvqjCwQxanZn7ReEHp1k81EohpZb',
V2_ALPHA_TICKET_MINT_ADDRESS:
'DeEiGWfCMP9psnLGkxGrBBMEAW5Jv8bBGMN8DCtFRCyB',
PERP_MARKETS: DevnetPerpMarkets,
SPOT_MARKETS: DevnetSpotMarkets,
MARKET_LOOKUP_TABLE: 'FaMS3U4uBojvGn5FSDEPimddcXsCfwkKsFgMVVnDdxGb',
DRIFT_ORACLE_RECEIVER_ID,
SB_ON_DEMAND_PID: ON_DEMAND_DEVNET_PID,
},
'mainnet-beta': {
ENV: 'mainnet-beta',
PYTH_ORACLE_MAPPING_ADDRESS: 'AHtgzX45WTKfkPG53L6WYhGEXwQkN1BVknET3sVsLL8J',
DRIFT_PROGRAM_ID,
JIT_PROXY_PROGRAM_ID: 'J1TnP8zvVxbtF5KFp5xRmWuvG9McnhzmBd9XGfCyuxFP',
USDC_MINT_ADDRESS: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
SERUM_V3: 'srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX',
PHOENIX: 'PhoeNiXZ8ByJGLkxNfZRnkUfjvmuYqLR89jjFHGqdXY',
OPENBOOK: 'opnb2LAfJYbRMAHHvqjCwQxanZn7ReEHp1k81EohpZb',
V2_ALPHA_TICKET_MINT_ADDRESS:
'Cmvhycb6LQvvzaShGw4iDHRLzeSSryioAsU98DSSkMNa',
PERP_MARKETS: MainnetPerpMarkets,
SPOT_MARKETS: MainnetSpotMarkets,
MARKET_LOOKUP_TABLE: 'Fpys8GRa5RBWfyeN7AaDUwFGD1zkDCA4z3t4CJLV8dfL',
SERUM_LOOKUP_TABLE: 'GPZkp76cJtNL2mphCvT6FXkJCVPpouidnacckR6rzKDN',
DRIFT_ORACLE_RECEIVER_ID,
SB_ON_DEMAND_PID: ON_DEMAND_MAINNET_PID,
},
};
let currentConfig: DriftConfig = configs.devnet;
export const getConfig = (): DriftConfig => currentConfig;
/**
* Allows customization of the SDK's environment and endpoints. You can pass individual settings to override the settings with your own presets.
*
* Defaults to master environment if you don't use this function.
* @param props
* @returns
*/
export const initialize = (props: {
env: DriftEnv;
overrideEnv?: Partial<DriftConfig>;
}): DriftConfig => {
//@ts-ignore
if (props.env === 'master')
return { ...configs['devnet'], ...(props.overrideEnv ?? {}) };
currentConfig = { ...configs[props.env], ...(props.overrideEnv ?? {}) };
return currentConfig;
};
export function getMarketsAndOraclesForSubscription(
env: DriftEnv,
perpMarkets?: PerpMarketConfig[],
spotMarkets?: SpotMarketConfig[]
): {
perpMarketIndexes: number[];
spotMarketIndexes: number[];
oracleInfos: OracleInfo[];
} {
const perpMarketsToUse =
perpMarkets?.length > 0 ? perpMarkets : PerpMarkets[env];
const spotMarketsToUse =
spotMarkets?.length > 0 ? spotMarkets : SpotMarkets[env];
const perpMarketIndexes = [];
const spotMarketIndexes = [];
const oracleInfos = new Map<string, OracleInfo>();
for (const market of perpMarketsToUse) {
perpMarketIndexes.push(market.marketIndex);
oracleInfos.set(getOracleId(market.oracle, market.oracleSource), {
publicKey: market.oracle,
source: market.oracleSource,
});
}
for (const spotMarket of spotMarketsToUse) {
spotMarketIndexes.push(spotMarket.marketIndex);
oracleInfos.set(getOracleId(spotMarket.oracle, spotMarket.oracleSource), {
publicKey: spotMarket.oracle,
source: spotMarket.oracleSource,
});
}
return {
perpMarketIndexes: perpMarketIndexes,
spotMarketIndexes: spotMarketIndexes,
oracleInfos: Array.from(oracleInfos.values()),
};
}
export async function findAllMarketAndOracles(program: Program): Promise<{
perpMarketIndexes: number[];
perpMarketAccounts: PerpMarketAccount[];
spotMarketIndexes: number[];
oracleInfos: OracleInfo[];
spotMarketAccounts: SpotMarketAccount[];
}> {
const perpMarketIndexes = [];
const spotMarketIndexes = [];
const oracleInfos = new Map<string, OracleInfo>();
const perpMarketProgramAccounts =
(await program.account.perpMarket.all()) as ProgramAccount<PerpMarketAccount>[];
const spotMarketProgramAccounts =
(await program.account.spotMarket.all()) as ProgramAccount<SpotMarketAccount>[];
for (const perpMarketProgramAccount of perpMarketProgramAccounts) {
const perpMarket = perpMarketProgramAccount.account as PerpMarketAccount;
perpMarketIndexes.push(perpMarket.marketIndex);
oracleInfos.set(
getOracleId(perpMarket.amm.oracle, perpMarket.amm.oracleSource),
{
publicKey: perpMarket.amm.oracle,
source: perpMarket.amm.oracleSource,
}
);
}
for (const spotMarketProgramAccount of spotMarketProgramAccounts) {
const spotMarket = spotMarketProgramAccount.account as SpotMarketAccount;
spotMarketIndexes.push(spotMarket.marketIndex);
oracleInfos.set(getOracleId(spotMarket.oracle, spotMarket.oracleSource), {
publicKey: spotMarket.oracle,
source: spotMarket.oracleSource,
});
}
return {
perpMarketIndexes,
perpMarketAccounts: perpMarketProgramAccounts.map(
(account) => account.account
),
spotMarketIndexes,
spotMarketAccounts: spotMarketProgramAccounts.map(
(account) => account.account
),
oracleInfos: Array.from(oracleInfos.values()),
};
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/user.ts
|
import { PublicKey } from '@solana/web3.js';
import { EventEmitter } from 'events';
import StrictEventEmitter from 'strict-event-emitter-types';
import { DriftClient } from './driftClient';
import {
HealthComponent,
HealthComponents,
isVariant,
MarginCategory,
Order,
PerpMarketAccount,
PerpPosition,
SpotPosition,
UserAccount,
UserStatus,
UserStatsAccount,
} from './types';
import {
calculateEntryPrice,
calculateUnsettledFundingPnl,
positionIsAvailable,
} from './math/position';
import {
AMM_RESERVE_PRECISION,
AMM_RESERVE_PRECISION_EXP,
AMM_TO_QUOTE_PRECISION_RATIO,
BASE_PRECISION,
BN_MAX,
DUST_POSITION_SIZE,
FIVE_MINUTE,
MARGIN_PRECISION,
ONE,
OPEN_ORDER_MARGIN_REQUIREMENT,
PRICE_PRECISION,
QUOTE_PRECISION,
QUOTE_PRECISION_EXP,
QUOTE_SPOT_MARKET_INDEX,
SPOT_MARKET_WEIGHT_PRECISION,
TEN,
TEN_THOUSAND,
TWO,
ZERO,
FUEL_START_TS,
} from './constants/numericConstants';
import {
DataAndSlot,
UserAccountEvents,
UserAccountSubscriber,
} from './accounts/types';
import {
BigNum,
BN,
calculateBaseAssetValue,
calculateMarketMarginRatio,
calculatePerpLiabilityValue,
calculatePositionPNL,
calculateReservePrice,
calculateSpotMarketMarginRatio,
calculateUnrealizedAssetWeight,
calculateWorstCasePerpLiabilityValue,
divCeil,
getBalance,
getSignedTokenAmount,
getStrictTokenValue,
getTokenValue,
getUser30dRollingVolumeEstimate,
MarketType,
PositionDirection,
sigNum,
SpotBalanceType,
SpotMarketAccount,
standardizeBaseAssetAmount,
} from '.';
import {
calculateAssetWeight,
calculateLiabilityWeight,
calculateWithdrawLimit,
getTokenAmount,
} from './math/spotBalance';
import { calculateMarketOpenBidAsk } from './math/amm';
import {
calculateBaseAssetValueWithOracle,
calculateCollateralDepositRequiredForTrade,
calculateMarginUSDCRequiredForTrade,
calculateWorstCaseBaseAssetAmount,
} from './math/margin';
import { OraclePriceData } from './oracles/types';
import { UserConfig } from './userConfig';
import { PollingUserAccountSubscriber } from './accounts/pollingUserAccountSubscriber';
import { WebSocketUserAccountSubscriber } from './accounts/webSocketUserAccountSubscriber';
import {
calculateWeightedTokenValue,
getWorstCaseTokenAmounts,
isSpotPositionAvailable,
} from './math/spotPosition';
import { calculateLiveOracleTwap } from './math/oracles';
import { getPerpMarketTierNumber, getSpotMarketTierNumber } from './math/tiers';
import { StrictOraclePrice } from './oracles/strictOraclePrice';
import { calculateSpotFuelBonus, calculatePerpFuelBonus } from './math/fuel';
import { grpcUserAccountSubscriber } from './accounts/grpcUserAccountSubscriber';
export class User {
driftClient: DriftClient;
userAccountPublicKey: PublicKey;
accountSubscriber: UserAccountSubscriber;
_isSubscribed = false;
eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
public get isSubscribed() {
return this._isSubscribed && this.accountSubscriber.isSubscribed;
}
public set isSubscribed(val: boolean) {
this._isSubscribed = val;
}
public constructor(config: UserConfig) {
this.driftClient = config.driftClient;
this.userAccountPublicKey = config.userAccountPublicKey;
if (config.accountSubscription?.type === 'polling') {
this.accountSubscriber = new PollingUserAccountSubscriber(
config.driftClient.connection,
config.userAccountPublicKey,
config.accountSubscription.accountLoader,
this.driftClient.program.account.user.coder.accounts.decodeUnchecked.bind(
this.driftClient.program.account.user.coder.accounts
)
);
} else if (config.accountSubscription?.type === 'custom') {
this.accountSubscriber = config.accountSubscription.userAccountSubscriber;
} else if (config.accountSubscription?.type === 'grpc') {
this.accountSubscriber = new grpcUserAccountSubscriber(
config.accountSubscription.grpcConfigs,
config.driftClient.program,
config.userAccountPublicKey,
{
resubTimeoutMs: config.accountSubscription?.resubTimeoutMs,
logResubMessages: config.accountSubscription?.logResubMessages,
}
);
} else {
this.accountSubscriber = new WebSocketUserAccountSubscriber(
config.driftClient.program,
config.userAccountPublicKey,
{
resubTimeoutMs: config.accountSubscription?.resubTimeoutMs,
logResubMessages: config.accountSubscription?.logResubMessages,
},
config.accountSubscription?.commitment
);
}
this.eventEmitter = this.accountSubscriber.eventEmitter;
}
/**
* Subscribe to User state accounts
* @returns SusbcriptionSuccess result
*/
public async subscribe(userAccount?: UserAccount): Promise<boolean> {
this.isSubscribed = await this.accountSubscriber.subscribe(userAccount);
return this.isSubscribed;
}
/**
* Forces the accountSubscriber to fetch account updates from rpc
*/
public async fetchAccounts(): Promise<void> {
await this.accountSubscriber.fetch();
}
public async unsubscribe(): Promise<void> {
await this.accountSubscriber.unsubscribe();
this.isSubscribed = false;
}
public getUserAccount(): UserAccount {
return this.accountSubscriber.getUserAccountAndSlot().data;
}
public async forceGetUserAccount(): Promise<UserAccount> {
await this.fetchAccounts();
return this.accountSubscriber.getUserAccountAndSlot().data;
}
public getUserAccountAndSlot(): DataAndSlot<UserAccount> | undefined {
return this.accountSubscriber.getUserAccountAndSlot();
}
public getPerpPositionForUserAccount(
userAccount: UserAccount,
marketIndex: number
): PerpPosition | undefined {
return this.getActivePerpPositionsForUserAccount(userAccount).find(
(position) => position.marketIndex === marketIndex
);
}
/**
* Gets the user's current position for a given perp market. If the user has no position returns undefined
* @param marketIndex
* @returns userPerpPosition
*/
public getPerpPosition(marketIndex: number): PerpPosition | undefined {
const userAccount = this.getUserAccount();
return this.getPerpPositionForUserAccount(userAccount, marketIndex);
}
public getPerpPositionAndSlot(
marketIndex: number
): DataAndSlot<PerpPosition | undefined> {
const userAccount = this.getUserAccountAndSlot();
const perpPosition = this.getPerpPositionForUserAccount(
userAccount.data,
marketIndex
);
return {
data: perpPosition,
slot: userAccount.slot,
};
}
public getSpotPositionForUserAccount(
userAccount: UserAccount,
marketIndex: number
): SpotPosition | undefined {
return userAccount.spotPositions.find(
(position) => position.marketIndex === marketIndex
);
}
/**
* Gets the user's current position for a given spot market. If the user has no position returns undefined
* @param marketIndex
* @returns userSpotPosition
*/
public getSpotPosition(marketIndex: number): SpotPosition | undefined {
const userAccount = this.getUserAccount();
return this.getSpotPositionForUserAccount(userAccount, marketIndex);
}
public getSpotPositionAndSlot(
marketIndex: number
): DataAndSlot<SpotPosition | undefined> {
const userAccount = this.getUserAccountAndSlot();
const spotPosition = this.getSpotPositionForUserAccount(
userAccount.data,
marketIndex
);
return {
data: spotPosition,
slot: userAccount.slot,
};
}
getEmptySpotPosition(marketIndex: number): SpotPosition {
return {
marketIndex,
scaledBalance: ZERO,
balanceType: SpotBalanceType.DEPOSIT,
cumulativeDeposits: ZERO,
openAsks: ZERO,
openBids: ZERO,
openOrders: 0,
};
}
/**
* Returns the token amount for a given market. The spot market precision is based on the token mint decimals.
* Positive if it is a deposit, negative if it is a borrow.
*
* @param marketIndex
*/
public getTokenAmount(marketIndex: number): BN {
const spotPosition = this.getSpotPosition(marketIndex);
if (spotPosition === undefined) {
return ZERO;
}
const spotMarket = this.driftClient.getSpotMarketAccount(marketIndex);
return getSignedTokenAmount(
getTokenAmount(
spotPosition.scaledBalance,
spotMarket,
spotPosition.balanceType
),
spotPosition.balanceType
);
}
public getEmptyPosition(marketIndex: number): PerpPosition {
return {
baseAssetAmount: ZERO,
remainderBaseAssetAmount: 0,
lastCumulativeFundingRate: ZERO,
marketIndex,
quoteAssetAmount: ZERO,
quoteEntryAmount: ZERO,
quoteBreakEvenAmount: ZERO,
openOrders: 0,
openBids: ZERO,
openAsks: ZERO,
settledPnl: ZERO,
lpShares: ZERO,
lastBaseAssetAmountPerLp: ZERO,
lastQuoteAssetAmountPerLp: ZERO,
perLpBase: 0,
};
}
public getClonedPosition(position: PerpPosition): PerpPosition {
const clonedPosition = Object.assign({}, position);
return clonedPosition;
}
public getOrderForUserAccount(
userAccount: UserAccount,
orderId: number
): Order | undefined {
return userAccount.orders.find((order) => order.orderId === orderId);
}
/**
* @param orderId
* @returns Order
*/
public getOrder(orderId: number): Order | undefined {
const userAccount = this.getUserAccount();
return this.getOrderForUserAccount(userAccount, orderId);
}
public getOrderAndSlot(orderId: number): DataAndSlot<Order | undefined> {
const userAccount = this.getUserAccountAndSlot();
const order = this.getOrderForUserAccount(userAccount.data, orderId);
return {
data: order,
slot: userAccount.slot,
};
}
public getOrderByUserIdForUserAccount(
userAccount: UserAccount,
userOrderId: number
): Order | undefined {
return userAccount.orders.find(
(order) => order.userOrderId === userOrderId
);
}
/**
* @param userOrderId
* @returns Order
*/
public getOrderByUserOrderId(userOrderId: number): Order | undefined {
const userAccount = this.getUserAccount();
return this.getOrderByUserIdForUserAccount(userAccount, userOrderId);
}
public getOrderByUserOrderIdAndSlot(
userOrderId: number
): DataAndSlot<Order | undefined> {
const userAccount = this.getUserAccountAndSlot();
const order = this.getOrderByUserIdForUserAccount(
userAccount.data,
userOrderId
);
return {
data: order,
slot: userAccount.slot,
};
}
public getOpenOrdersForUserAccount(userAccount?: UserAccount): Order[] {
return userAccount?.orders.filter((order) =>
isVariant(order.status, 'open')
);
}
public getOpenOrders(): Order[] {
const userAccount = this.getUserAccount();
return this.getOpenOrdersForUserAccount(userAccount);
}
public getOpenOrdersAndSlot(): DataAndSlot<Order[]> {
const userAccount = this.getUserAccountAndSlot();
const openOrders = this.getOpenOrdersForUserAccount(userAccount.data);
return {
data: openOrders,
slot: userAccount.slot,
};
}
public getUserAccountPublicKey(): PublicKey {
return this.userAccountPublicKey;
}
public async exists(): Promise<boolean> {
const userAccountRPCResponse =
await this.driftClient.connection.getParsedAccountInfo(
this.userAccountPublicKey
);
return userAccountRPCResponse.value !== null;
}
/**
* calculates the total open bids/asks in a perp market (including lps)
* @returns : open bids
* @returns : open asks
*/
public getPerpBidAsks(marketIndex: number): [BN, BN] {
const position = this.getPerpPosition(marketIndex);
const [lpOpenBids, lpOpenAsks] = this.getLPBidAsks(marketIndex);
const totalOpenBids = lpOpenBids.add(position.openBids);
const totalOpenAsks = lpOpenAsks.add(position.openAsks);
return [totalOpenBids, totalOpenAsks];
}
/**
* calculates the open bids and asks for an lp
* optionally pass in lpShares to see what bid/asks a user *would* take on
* @returns : lp open bids
* @returns : lp open asks
*/
public getLPBidAsks(marketIndex: number, lpShares?: BN): [BN, BN] {
const position = this.getPerpPosition(marketIndex);
const lpSharesToCalc = lpShares ?? position?.lpShares;
if (!lpSharesToCalc || lpSharesToCalc.eq(ZERO)) {
return [ZERO, ZERO];
}
const market = this.driftClient.getPerpMarketAccount(marketIndex);
const [marketOpenBids, marketOpenAsks] = calculateMarketOpenBidAsk(
market.amm.baseAssetReserve,
market.amm.minBaseAssetReserve,
market.amm.maxBaseAssetReserve,
market.amm.orderStepSize
);
const lpOpenBids = marketOpenBids.mul(lpSharesToCalc).div(market.amm.sqrtK);
const lpOpenAsks = marketOpenAsks.mul(lpSharesToCalc).div(market.amm.sqrtK);
return [lpOpenBids, lpOpenAsks];
}
/**
* calculates the market position if the lp position was settled
* @returns : the settled userPosition
* @returns : the dust base asset amount (ie, < stepsize)
* @returns : pnl from settle
*/
public getPerpPositionWithLPSettle(
marketIndex: number,
originalPosition?: PerpPosition,
burnLpShares = false,
includeRemainderInBaseAmount = false
): [PerpPosition, BN, BN] {
originalPosition =
originalPosition ??
this.getPerpPosition(marketIndex) ??
this.getEmptyPosition(marketIndex);
if (originalPosition.lpShares.eq(ZERO)) {
return [originalPosition, ZERO, ZERO];
}
const position = this.getClonedPosition(originalPosition);
const market = this.driftClient.getPerpMarketAccount(position.marketIndex);
if (market.amm.perLpBase != position.perLpBase) {
// perLpBase = 1 => per 10 LP shares, perLpBase = -1 => per 0.1 LP shares
const expoDiff = market.amm.perLpBase - position.perLpBase;
const marketPerLpRebaseScalar = new BN(10 ** Math.abs(expoDiff));
if (expoDiff > 0) {
position.lastBaseAssetAmountPerLp =
position.lastBaseAssetAmountPerLp.mul(marketPerLpRebaseScalar);
position.lastQuoteAssetAmountPerLp =
position.lastQuoteAssetAmountPerLp.mul(marketPerLpRebaseScalar);
} else {
position.lastBaseAssetAmountPerLp =
position.lastBaseAssetAmountPerLp.div(marketPerLpRebaseScalar);
position.lastQuoteAssetAmountPerLp =
position.lastQuoteAssetAmountPerLp.div(marketPerLpRebaseScalar);
}
position.perLpBase = position.perLpBase + expoDiff;
}
const nShares = position.lpShares;
// incorp unsettled funding on pre settled position
const quoteFundingPnl = calculateUnsettledFundingPnl(market, position);
let baseUnit = AMM_RESERVE_PRECISION;
if (market.amm.perLpBase == position.perLpBase) {
if (
position.perLpBase >= 0 &&
position.perLpBase <= AMM_RESERVE_PRECISION_EXP.toNumber()
) {
const marketPerLpRebase = new BN(10 ** market.amm.perLpBase);
baseUnit = baseUnit.mul(marketPerLpRebase);
} else if (
position.perLpBase < 0 &&
position.perLpBase >= -AMM_RESERVE_PRECISION_EXP.toNumber()
) {
const marketPerLpRebase = new BN(10 ** Math.abs(market.amm.perLpBase));
baseUnit = baseUnit.div(marketPerLpRebase);
} else {
throw 'cannot calc';
}
} else {
throw 'market.amm.perLpBase != position.perLpBase';
}
const deltaBaa = market.amm.baseAssetAmountPerLp
.sub(position.lastBaseAssetAmountPerLp)
.mul(nShares)
.div(baseUnit);
const deltaQaa = market.amm.quoteAssetAmountPerLp
.sub(position.lastQuoteAssetAmountPerLp)
.mul(nShares)
.div(baseUnit);
function sign(v: BN) {
return v.isNeg() ? new BN(-1) : new BN(1);
}
function standardize(amount: BN, stepSize: BN) {
const remainder = amount.abs().mod(stepSize).mul(sign(amount));
const standardizedAmount = amount.sub(remainder);
return [standardizedAmount, remainder];
}
const [standardizedBaa, remainderBaa] = standardize(
deltaBaa,
market.amm.orderStepSize
);
position.remainderBaseAssetAmount += remainderBaa.toNumber();
if (
Math.abs(position.remainderBaseAssetAmount) >
market.amm.orderStepSize.toNumber()
) {
const [newStandardizedBaa, newRemainderBaa] = standardize(
new BN(position.remainderBaseAssetAmount),
market.amm.orderStepSize
);
position.baseAssetAmount =
position.baseAssetAmount.add(newStandardizedBaa);
position.remainderBaseAssetAmount = newRemainderBaa.toNumber();
}
let dustBaseAssetValue = ZERO;
if (burnLpShares && position.remainderBaseAssetAmount != 0) {
const oraclePriceData = this.driftClient.getOracleDataForPerpMarket(
position.marketIndex
);
dustBaseAssetValue = new BN(Math.abs(position.remainderBaseAssetAmount))
.mul(oraclePriceData.price)
.div(AMM_RESERVE_PRECISION)
.add(ONE);
}
let updateType;
if (position.baseAssetAmount.eq(ZERO)) {
updateType = 'open';
} else if (sign(position.baseAssetAmount).eq(sign(deltaBaa))) {
updateType = 'increase';
} else if (position.baseAssetAmount.abs().gt(deltaBaa.abs())) {
updateType = 'reduce';
} else if (position.baseAssetAmount.abs().eq(deltaBaa.abs())) {
updateType = 'close';
} else {
updateType = 'flip';
}
let newQuoteEntry;
let pnl;
if (updateType == 'open' || updateType == 'increase') {
newQuoteEntry = position.quoteEntryAmount.add(deltaQaa);
pnl = ZERO;
} else if (updateType == 'reduce' || updateType == 'close') {
newQuoteEntry = position.quoteEntryAmount.sub(
position.quoteEntryAmount
.mul(deltaBaa.abs())
.div(position.baseAssetAmount.abs())
);
pnl = position.quoteEntryAmount.sub(newQuoteEntry).add(deltaQaa);
} else {
newQuoteEntry = deltaQaa.sub(
deltaQaa.mul(position.baseAssetAmount.abs()).div(deltaBaa.abs())
);
pnl = position.quoteEntryAmount.add(deltaQaa.sub(newQuoteEntry));
}
position.quoteEntryAmount = newQuoteEntry;
position.baseAssetAmount = position.baseAssetAmount.add(standardizedBaa);
position.quoteAssetAmount = position.quoteAssetAmount
.add(deltaQaa)
.add(quoteFundingPnl)
.sub(dustBaseAssetValue);
position.quoteBreakEvenAmount = position.quoteBreakEvenAmount
.add(deltaQaa)
.add(quoteFundingPnl)
.sub(dustBaseAssetValue);
// update open bids/asks
const [marketOpenBids, marketOpenAsks] = calculateMarketOpenBidAsk(
market.amm.baseAssetReserve,
market.amm.minBaseAssetReserve,
market.amm.maxBaseAssetReserve,
market.amm.orderStepSize
);
const lpOpenBids = marketOpenBids
.mul(position.lpShares)
.div(market.amm.sqrtK);
const lpOpenAsks = marketOpenAsks
.mul(position.lpShares)
.div(market.amm.sqrtK);
position.openBids = lpOpenBids.add(position.openBids);
position.openAsks = lpOpenAsks.add(position.openAsks);
// eliminate counting funding on settled position
if (position.baseAssetAmount.gt(ZERO)) {
position.lastCumulativeFundingRate = market.amm.cumulativeFundingRateLong;
} else if (position.baseAssetAmount.lt(ZERO)) {
position.lastCumulativeFundingRate =
market.amm.cumulativeFundingRateShort;
} else {
position.lastCumulativeFundingRate = ZERO;
}
const remainderBeforeRemoval = new BN(position.remainderBaseAssetAmount);
if (includeRemainderInBaseAmount) {
position.baseAssetAmount = position.baseAssetAmount.add(
remainderBeforeRemoval
);
position.remainderBaseAssetAmount = 0;
}
return [position, remainderBeforeRemoval, pnl];
}
/**
* calculates Buying Power = free collateral / initial margin ratio
* @returns : Precision QUOTE_PRECISION
*/
public getPerpBuyingPower(marketIndex: number, collateralBuffer = ZERO): BN {
const perpPosition = this.getPerpPositionWithLPSettle(
marketIndex,
undefined,
true
)[0];
const perpMarket = this.driftClient.getPerpMarketAccount(marketIndex);
const oraclePriceData = this.getOracleDataForPerpMarket(marketIndex);
const worstCaseBaseAssetAmount = perpPosition
? calculateWorstCaseBaseAssetAmount(
perpPosition,
perpMarket,
oraclePriceData.price
)
: ZERO;
const freeCollateral = this.getFreeCollateral().sub(collateralBuffer);
return this.getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(
marketIndex,
freeCollateral,
worstCaseBaseAssetAmount
);
}
getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(
marketIndex: number,
freeCollateral: BN,
baseAssetAmount: BN
): BN {
const marginRatio = calculateMarketMarginRatio(
this.driftClient.getPerpMarketAccount(marketIndex),
baseAssetAmount,
'Initial',
this.getUserAccount().maxMarginRatio,
this.isHighLeverageMode()
);
return freeCollateral.mul(MARGIN_PRECISION).div(new BN(marginRatio));
}
/**
* calculates Free Collateral = Total collateral - margin requirement
* @returns : Precision QUOTE_PRECISION
*/
public getFreeCollateral(marginCategory: MarginCategory = 'Initial'): BN {
const totalCollateral = this.getTotalCollateral(marginCategory, true);
const marginRequirement =
marginCategory === 'Initial'
? this.getInitialMarginRequirement()
: this.getMaintenanceMarginRequirement();
const freeCollateral = totalCollateral.sub(marginRequirement);
return freeCollateral.gte(ZERO) ? freeCollateral : ZERO;
}
/**
* @returns The margin requirement of a certain type (Initial or Maintenance) in USDC. : QUOTE_PRECISION
*/
public getMarginRequirement(
marginCategory: MarginCategory,
liquidationBuffer?: BN,
strict = false,
includeOpenOrders = true
): BN {
return this.getTotalPerpPositionLiability(
marginCategory,
liquidationBuffer,
includeOpenOrders,
strict
).add(
this.getSpotMarketLiabilityValue(
undefined,
marginCategory,
liquidationBuffer,
includeOpenOrders,
strict
)
);
}
/**
* @returns The initial margin requirement in USDC. : QUOTE_PRECISION
*/
public getInitialMarginRequirement(): BN {
return this.getMarginRequirement('Initial', undefined, true);
}
/**
* @returns The maintenance margin requirement in USDC. : QUOTE_PRECISION
*/
public getMaintenanceMarginRequirement(): BN {
// if user being liq'd, can continue to be liq'd until total collateral above the margin requirement plus buffer
let liquidationBuffer = undefined;
if (this.isBeingLiquidated()) {
liquidationBuffer = new BN(
this.driftClient.getStateAccount().liquidationMarginBufferRatio
);
}
return this.getMarginRequirement('Maintenance', liquidationBuffer);
}
public getActivePerpPositionsForUserAccount(
userAccount: UserAccount
): PerpPosition[] {
return userAccount.perpPositions.filter(
(pos) =>
!pos.baseAssetAmount.eq(ZERO) ||
!pos.quoteAssetAmount.eq(ZERO) ||
!(pos.openOrders == 0) ||
!pos.lpShares.eq(ZERO)
);
}
public getActivePerpPositions(): PerpPosition[] {
const userAccount = this.getUserAccount();
return this.getActivePerpPositionsForUserAccount(userAccount);
}
public getActivePerpPositionsAndSlot(): DataAndSlot<PerpPosition[]> {
const userAccount = this.getUserAccountAndSlot();
const positions = this.getActivePerpPositionsForUserAccount(
userAccount.data
);
return {
data: positions,
slot: userAccount.slot,
};
}
public getActiveSpotPositionsForUserAccount(
userAccount: UserAccount
): SpotPosition[] {
return userAccount.spotPositions.filter(
(pos) => !isSpotPositionAvailable(pos)
);
}
public getActiveSpotPositions(): SpotPosition[] {
const userAccount = this.getUserAccount();
return this.getActiveSpotPositionsForUserAccount(userAccount);
}
public getActiveSpotPositionsAndSlot(): DataAndSlot<SpotPosition[]> {
const userAccount = this.getUserAccountAndSlot();
const positions = this.getActiveSpotPositionsForUserAccount(
userAccount.data
);
return {
data: positions,
slot: userAccount.slot,
};
}
/**
* calculates unrealized position price pnl
* @returns : Precision QUOTE_PRECISION
*/
public getUnrealizedPNL(
withFunding?: boolean,
marketIndex?: number,
withWeightMarginCategory?: MarginCategory,
strict = false
): BN {
return this.getActivePerpPositions()
.filter((pos) =>
marketIndex !== undefined ? pos.marketIndex === marketIndex : true
)
.reduce((unrealizedPnl, perpPosition) => {
const market = this.driftClient.getPerpMarketAccount(
perpPosition.marketIndex
);
const oraclePriceData = this.getOracleDataForPerpMarket(
market.marketIndex
);
const quoteSpotMarket = this.driftClient.getSpotMarketAccount(
market.quoteSpotMarketIndex
);
const quoteOraclePriceData = this.getOracleDataForSpotMarket(
market.quoteSpotMarketIndex
);
if (perpPosition.lpShares.gt(ZERO)) {
perpPosition = this.getPerpPositionWithLPSettle(
perpPosition.marketIndex,
undefined,
!!withWeightMarginCategory
)[0];
}
let positionUnrealizedPnl = calculatePositionPNL(
market,
perpPosition,
withFunding,
oraclePriceData
);
let quotePrice;
if (strict && positionUnrealizedPnl.gt(ZERO)) {
quotePrice = BN.min(
quoteOraclePriceData.price,
quoteSpotMarket.historicalOracleData.lastOraclePriceTwap5Min
);
} else if (strict && positionUnrealizedPnl.lt(ZERO)) {
quotePrice = BN.max(
quoteOraclePriceData.price,
quoteSpotMarket.historicalOracleData.lastOraclePriceTwap5Min
);
} else {
quotePrice = quoteOraclePriceData.price;
}
positionUnrealizedPnl = positionUnrealizedPnl
.mul(quotePrice)
.div(PRICE_PRECISION);
if (withWeightMarginCategory !== undefined) {
if (positionUnrealizedPnl.gt(ZERO)) {
positionUnrealizedPnl = positionUnrealizedPnl
.mul(
calculateUnrealizedAssetWeight(
market,
quoteSpotMarket,
positionUnrealizedPnl,
withWeightMarginCategory,
oraclePriceData
)
)
.div(new BN(SPOT_MARKET_WEIGHT_PRECISION));
}
}
return unrealizedPnl.add(positionUnrealizedPnl);
}, ZERO);
}
/**
* calculates unrealized funding payment pnl
* @returns : Precision QUOTE_PRECISION
*/
public getUnrealizedFundingPNL(marketIndex?: number): BN {
return this.getUserAccount()
.perpPositions.filter((pos) =>
marketIndex !== undefined ? pos.marketIndex === marketIndex : true
)
.reduce((pnl, perpPosition) => {
const market = this.driftClient.getPerpMarketAccount(
perpPosition.marketIndex
);
return pnl.add(calculateUnsettledFundingPnl(market, perpPosition));
}, ZERO);
}
public getFuelBonus(
now: BN,
includeSettled = true,
includeUnsettled = true
): {
depositFuel: BN;
borrowFuel: BN;
positionFuel: BN;
takerFuel: BN;
makerFuel: BN;
insuranceFuel: BN;
} {
const userAccount: UserAccount = this.getUserAccount();
const result = {
insuranceFuel: ZERO,
takerFuel: ZERO,
makerFuel: ZERO,
depositFuel: ZERO,
borrowFuel: ZERO,
positionFuel: ZERO,
};
const userStats = this.driftClient.getUserStats();
const userStatsAccount: UserStatsAccount = userStats.getAccount();
if (includeSettled) {
result.takerFuel = result.takerFuel.add(
new BN(userStatsAccount.fuelTaker)
);
result.makerFuel = result.makerFuel.add(
new BN(userStatsAccount.fuelMaker)
);
result.depositFuel = result.depositFuel.add(
new BN(userStatsAccount.fuelDeposits)
);
result.borrowFuel = result.borrowFuel.add(
new BN(userStatsAccount.fuelBorrows)
);
result.positionFuel = result.positionFuel.add(
new BN(userStatsAccount.fuelPositions)
);
}
if (includeUnsettled) {
const fuelBonusNumerator = BN.max(
now.sub(
BN.max(new BN(userAccount.lastFuelBonusUpdateTs), FUEL_START_TS)
),
ZERO
);
if (fuelBonusNumerator.gt(ZERO)) {
for (const spotPosition of this.getActiveSpotPositions()) {
const spotMarketAccount: SpotMarketAccount =
this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
const tokenAmount = this.getTokenAmount(spotPosition.marketIndex);
const oraclePriceData = this.getOracleDataForSpotMarket(
spotPosition.marketIndex
);
const twap5min = calculateLiveOracleTwap(
spotMarketAccount.historicalOracleData,
oraclePriceData,
now,
FIVE_MINUTE // 5MIN
);
const strictOraclePrice = new StrictOraclePrice(
oraclePriceData.price,
twap5min
);
const signedTokenValue = getStrictTokenValue(
tokenAmount,
spotMarketAccount.decimals,
strictOraclePrice
);
if (signedTokenValue.gt(ZERO)) {
result.depositFuel = result.depositFuel.add(
calculateSpotFuelBonus(
spotMarketAccount,
signedTokenValue,
fuelBonusNumerator
)
);
} else {
result.borrowFuel = result.borrowFuel.add(
calculateSpotFuelBonus(
spotMarketAccount,
signedTokenValue,
fuelBonusNumerator
)
);
}
}
for (const perpPosition of this.getActivePerpPositions()) {
const oraclePriceData = this.getOracleDataForPerpMarket(
perpPosition.marketIndex
);
const perpMarketAccount = this.driftClient.getPerpMarketAccount(
perpPosition.marketIndex
);
const baseAssetValue = this.getPerpPositionValue(
perpPosition.marketIndex,
oraclePriceData,
false
);
result.positionFuel = result.positionFuel.add(
calculatePerpFuelBonus(
perpMarketAccount,
baseAssetValue,
fuelBonusNumerator
)
);
}
}
}
result.insuranceFuel = userStats.getInsuranceFuelBonus(
now,
includeSettled,
includeUnsettled
);
return result;
}
public getSpotMarketAssetAndLiabilityValue(
marketIndex?: number,
marginCategory?: MarginCategory,
liquidationBuffer?: BN,
includeOpenOrders?: boolean,
strict = false,
now?: BN
): { totalAssetValue: BN; totalLiabilityValue: BN } {
now = now || new BN(new Date().getTime() / 1000);
let netQuoteValue = ZERO;
let totalAssetValue = ZERO;
let totalLiabilityValue = ZERO;
for (const spotPosition of this.getUserAccount().spotPositions) {
const countForBase =
marketIndex === undefined || spotPosition.marketIndex === marketIndex;
const countForQuote =
marketIndex === undefined ||
marketIndex === QUOTE_SPOT_MARKET_INDEX ||
(includeOpenOrders && spotPosition.openOrders !== 0);
if (
isSpotPositionAvailable(spotPosition) ||
(!countForBase && !countForQuote)
) {
continue;
}
const spotMarketAccount: SpotMarketAccount =
this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
const oraclePriceData = this.getOracleDataForSpotMarket(
spotPosition.marketIndex
);
let twap5min;
if (strict) {
twap5min = calculateLiveOracleTwap(
spotMarketAccount.historicalOracleData,
oraclePriceData,
now,
FIVE_MINUTE // 5MIN
);
}
const strictOraclePrice = new StrictOraclePrice(
oraclePriceData.price,
twap5min
);
if (
spotPosition.marketIndex === QUOTE_SPOT_MARKET_INDEX &&
countForQuote
) {
const tokenAmount = getSignedTokenAmount(
getTokenAmount(
spotPosition.scaledBalance,
spotMarketAccount,
spotPosition.balanceType
),
spotPosition.balanceType
);
if (isVariant(spotPosition.balanceType, 'borrow')) {
const weightedTokenValue = this.getSpotLiabilityValue(
tokenAmount,
strictOraclePrice,
spotMarketAccount,
marginCategory,
liquidationBuffer
).abs();
netQuoteValue = netQuoteValue.sub(weightedTokenValue);
} else {
const weightedTokenValue = this.getSpotAssetValue(
tokenAmount,
strictOraclePrice,
spotMarketAccount,
marginCategory
);
netQuoteValue = netQuoteValue.add(weightedTokenValue);
}
continue;
}
if (!includeOpenOrders && countForBase) {
if (isVariant(spotPosition.balanceType, 'borrow')) {
const tokenAmount = getSignedTokenAmount(
getTokenAmount(
spotPosition.scaledBalance,
spotMarketAccount,
spotPosition.balanceType
),
SpotBalanceType.BORROW
);
const liabilityValue = this.getSpotLiabilityValue(
tokenAmount,
strictOraclePrice,
spotMarketAccount,
marginCategory,
liquidationBuffer
).abs();
totalLiabilityValue = totalLiabilityValue.add(liabilityValue);
continue;
} else {
const tokenAmount = getTokenAmount(
spotPosition.scaledBalance,
spotMarketAccount,
spotPosition.balanceType
);
const assetValue = this.getSpotAssetValue(
tokenAmount,
strictOraclePrice,
spotMarketAccount,
marginCategory
);
totalAssetValue = totalAssetValue.add(assetValue);
continue;
}
}
const {
tokenAmount: worstCaseTokenAmount,
ordersValue: worstCaseQuoteTokenAmount,
} = getWorstCaseTokenAmounts(
spotPosition,
spotMarketAccount,
strictOraclePrice,
marginCategory,
this.getUserAccount().maxMarginRatio
);
if (worstCaseTokenAmount.gt(ZERO) && countForBase) {
const baseAssetValue = this.getSpotAssetValue(
worstCaseTokenAmount,
strictOraclePrice,
spotMarketAccount,
marginCategory
);
totalAssetValue = totalAssetValue.add(baseAssetValue);
}
if (worstCaseTokenAmount.lt(ZERO) && countForBase) {
const baseLiabilityValue = this.getSpotLiabilityValue(
worstCaseTokenAmount,
strictOraclePrice,
spotMarketAccount,
marginCategory,
liquidationBuffer
).abs();
totalLiabilityValue = totalLiabilityValue.add(baseLiabilityValue);
}
if (worstCaseQuoteTokenAmount.gt(ZERO) && countForQuote) {
netQuoteValue = netQuoteValue.add(worstCaseQuoteTokenAmount);
}
if (worstCaseQuoteTokenAmount.lt(ZERO) && countForQuote) {
let weight = SPOT_MARKET_WEIGHT_PRECISION;
if (marginCategory === 'Initial') {
weight = BN.max(weight, new BN(this.getUserAccount().maxMarginRatio));
}
const weightedTokenValue = worstCaseQuoteTokenAmount
.abs()
.mul(weight)
.div(SPOT_MARKET_WEIGHT_PRECISION);
netQuoteValue = netQuoteValue.sub(weightedTokenValue);
}
totalLiabilityValue = totalLiabilityValue.add(
new BN(spotPosition.openOrders).mul(OPEN_ORDER_MARGIN_REQUIREMENT)
);
}
if (marketIndex === undefined || marketIndex === QUOTE_SPOT_MARKET_INDEX) {
if (netQuoteValue.gt(ZERO)) {
totalAssetValue = totalAssetValue.add(netQuoteValue);
} else {
totalLiabilityValue = totalLiabilityValue.add(netQuoteValue.abs());
}
}
return { totalAssetValue, totalLiabilityValue };
}
public getSpotMarketLiabilityValue(
marketIndex?: number,
marginCategory?: MarginCategory,
liquidationBuffer?: BN,
includeOpenOrders?: boolean,
strict = false,
now?: BN
): BN {
const { totalLiabilityValue } = this.getSpotMarketAssetAndLiabilityValue(
marketIndex,
marginCategory,
liquidationBuffer,
includeOpenOrders,
strict,
now
);
return totalLiabilityValue;
}
getSpotLiabilityValue(
tokenAmount: BN,
strictOraclePrice: StrictOraclePrice,
spotMarketAccount: SpotMarketAccount,
marginCategory?: MarginCategory,
liquidationBuffer?: BN
): BN {
let liabilityValue = getStrictTokenValue(
tokenAmount,
spotMarketAccount.decimals,
strictOraclePrice
);
if (marginCategory !== undefined) {
let weight = calculateLiabilityWeight(
tokenAmount,
spotMarketAccount,
marginCategory
);
if (
marginCategory === 'Initial' &&
spotMarketAccount.marketIndex !== QUOTE_SPOT_MARKET_INDEX
) {
weight = BN.max(
weight,
SPOT_MARKET_WEIGHT_PRECISION.addn(
this.getUserAccount().maxMarginRatio
)
);
}
if (liquidationBuffer !== undefined) {
weight = weight.add(liquidationBuffer);
}
liabilityValue = liabilityValue
.mul(weight)
.div(SPOT_MARKET_WEIGHT_PRECISION);
}
return liabilityValue;
}
public getSpotMarketAssetValue(
marketIndex?: number,
marginCategory?: MarginCategory,
includeOpenOrders?: boolean,
strict = false,
now?: BN
): BN {
const { totalAssetValue } = this.getSpotMarketAssetAndLiabilityValue(
marketIndex,
marginCategory,
undefined,
includeOpenOrders,
strict,
now
);
return totalAssetValue;
}
getSpotAssetValue(
tokenAmount: BN,
strictOraclePrice: StrictOraclePrice,
spotMarketAccount: SpotMarketAccount,
marginCategory?: MarginCategory
): BN {
let assetValue = getStrictTokenValue(
tokenAmount,
spotMarketAccount.decimals,
strictOraclePrice
);
if (marginCategory !== undefined) {
let weight = calculateAssetWeight(
tokenAmount,
strictOraclePrice.current,
spotMarketAccount,
marginCategory
);
if (
marginCategory === 'Initial' &&
spotMarketAccount.marketIndex !== QUOTE_SPOT_MARKET_INDEX
) {
const userCustomAssetWeight = BN.max(
ZERO,
SPOT_MARKET_WEIGHT_PRECISION.subn(
this.getUserAccount().maxMarginRatio
)
);
weight = BN.min(weight, userCustomAssetWeight);
}
assetValue = assetValue.mul(weight).div(SPOT_MARKET_WEIGHT_PRECISION);
}
return assetValue;
}
public getSpotPositionValue(
marketIndex: number,
marginCategory?: MarginCategory,
includeOpenOrders?: boolean,
strict = false,
now?: BN
): BN {
const { totalAssetValue, totalLiabilityValue } =
this.getSpotMarketAssetAndLiabilityValue(
marketIndex,
marginCategory,
undefined,
includeOpenOrders,
strict,
now
);
return totalAssetValue.sub(totalLiabilityValue);
}
public getNetSpotMarketValue(withWeightMarginCategory?: MarginCategory): BN {
const { totalAssetValue, totalLiabilityValue } =
this.getSpotMarketAssetAndLiabilityValue(
undefined,
withWeightMarginCategory
);
return totalAssetValue.sub(totalLiabilityValue);
}
/**
* calculates TotalCollateral: collateral + unrealized pnl
* @returns : Precision QUOTE_PRECISION
*/
public getTotalCollateral(
marginCategory: MarginCategory = 'Initial',
strict = false,
includeOpenOrders = true
): BN {
return this.getSpotMarketAssetValue(
undefined,
marginCategory,
includeOpenOrders,
strict
).add(this.getUnrealizedPNL(true, undefined, marginCategory, strict));
}
/**
* calculates User Health by comparing total collateral and maint. margin requirement
* @returns : number (value from [0, 100])
*/
public getHealth(): number {
if (this.isBeingLiquidated()) {
return 0;
}
const totalCollateral = this.getTotalCollateral('Maintenance');
const maintenanceMarginReq = this.getMaintenanceMarginRequirement();
let health: number;
if (maintenanceMarginReq.eq(ZERO) && totalCollateral.gte(ZERO)) {
health = 100;
} else if (totalCollateral.lte(ZERO)) {
health = 0;
} else {
health = Math.round(
Math.min(
100,
Math.max(
0,
(1 - maintenanceMarginReq.toNumber() / totalCollateral.toNumber()) *
100
)
)
);
}
return health;
}
calculateWeightedPerpPositionLiability(
perpPosition: PerpPosition,
marginCategory?: MarginCategory,
liquidationBuffer?: BN,
includeOpenOrders?: boolean,
strict = false
): BN {
const market = this.driftClient.getPerpMarketAccount(
perpPosition.marketIndex
);
if (perpPosition.lpShares.gt(ZERO)) {
// is an lp, clone so we dont mutate the position
perpPosition = this.getPerpPositionWithLPSettle(
market.marketIndex,
this.getClonedPosition(perpPosition),
!!marginCategory
)[0];
}
let valuationPrice = this.getOracleDataForPerpMarket(
market.marketIndex
).price;
if (isVariant(market.status, 'settlement')) {
valuationPrice = market.expiryPrice;
}
let baseAssetAmount: BN;
let liabilityValue;
if (includeOpenOrders) {
const { worstCaseBaseAssetAmount, worstCaseLiabilityValue } =
calculateWorstCasePerpLiabilityValue(
perpPosition,
market,
valuationPrice
);
baseAssetAmount = worstCaseBaseAssetAmount;
liabilityValue = worstCaseLiabilityValue;
} else {
baseAssetAmount = perpPosition.baseAssetAmount;
liabilityValue = calculatePerpLiabilityValue(
baseAssetAmount,
valuationPrice,
isVariant(market.contractType, 'prediction')
);
}
if (marginCategory) {
let marginRatio = new BN(
calculateMarketMarginRatio(
market,
baseAssetAmount.abs(),
marginCategory,
this.getUserAccount().maxMarginRatio,
this.isHighLeverageMode()
)
);
if (liquidationBuffer !== undefined) {
marginRatio = marginRatio.add(liquidationBuffer);
}
if (isVariant(market.status, 'settlement')) {
marginRatio = ZERO;
}
const quoteSpotMarket = this.driftClient.getSpotMarketAccount(
market.quoteSpotMarketIndex
);
const quoteOraclePriceData = this.driftClient.getOracleDataForSpotMarket(
QUOTE_SPOT_MARKET_INDEX
);
let quotePrice;
if (strict) {
quotePrice = BN.max(
quoteOraclePriceData.price,
quoteSpotMarket.historicalOracleData.lastOraclePriceTwap5Min
);
} else {
quotePrice = quoteOraclePriceData.price;
}
liabilityValue = liabilityValue
.mul(quotePrice)
.div(PRICE_PRECISION)
.mul(marginRatio)
.div(MARGIN_PRECISION);
if (includeOpenOrders) {
liabilityValue = liabilityValue.add(
new BN(perpPosition.openOrders).mul(OPEN_ORDER_MARGIN_REQUIREMENT)
);
if (perpPosition.lpShares.gt(ZERO)) {
liabilityValue = liabilityValue.add(
BN.max(
QUOTE_PRECISION,
valuationPrice
.mul(market.amm.orderStepSize)
.mul(QUOTE_PRECISION)
.div(AMM_RESERVE_PRECISION)
.div(PRICE_PRECISION)
)
);
}
}
}
return liabilityValue;
}
/**
* calculates position value of a single perp market in margin system
* @returns : Precision QUOTE_PRECISION
*/
public getPerpMarketLiabilityValue(
marketIndex: number,
marginCategory?: MarginCategory,
liquidationBuffer?: BN,
includeOpenOrders?: boolean,
strict = false
): BN {
const perpPosition = this.getPerpPosition(marketIndex);
return this.calculateWeightedPerpPositionLiability(
perpPosition,
marginCategory,
liquidationBuffer,
includeOpenOrders,
strict
);
}
/**
* calculates sum of position value across all positions in margin system
* @returns : Precision QUOTE_PRECISION
*/
getTotalPerpPositionLiability(
marginCategory?: MarginCategory,
liquidationBuffer?: BN,
includeOpenOrders?: boolean,
strict = false
): BN {
return this.getActivePerpPositions().reduce(
(totalPerpValue, perpPosition) => {
const baseAssetValue = this.calculateWeightedPerpPositionLiability(
perpPosition,
marginCategory,
liquidationBuffer,
includeOpenOrders,
strict
);
return totalPerpValue.add(baseAssetValue);
},
ZERO
);
}
/**
* calculates position value based on oracle
* @returns : Precision QUOTE_PRECISION
*/
public getPerpPositionValue(
marketIndex: number,
oraclePriceData: OraclePriceData,
includeOpenOrders = false
): BN {
const userPosition =
this.getPerpPositionWithLPSettle(
marketIndex,
undefined,
false,
true
)[0] || this.getEmptyPosition(marketIndex);
const market = this.driftClient.getPerpMarketAccount(
userPosition.marketIndex
);
return calculateBaseAssetValueWithOracle(
market,
userPosition,
oraclePriceData,
includeOpenOrders
);
}
/**
* calculates position liabiltiy value in margin system
* @returns : Precision QUOTE_PRECISION
*/
public getPerpLiabilityValue(
marketIndex: number,
oraclePriceData: OraclePriceData,
includeOpenOrders = false
): BN {
const userPosition =
this.getPerpPositionWithLPSettle(
marketIndex,
undefined,
false,
true
)[0] || this.getEmptyPosition(marketIndex);
const market = this.driftClient.getPerpMarketAccount(
userPosition.marketIndex
);
if (includeOpenOrders) {
return calculateWorstCasePerpLiabilityValue(
userPosition,
market,
oraclePriceData.price
).worstCaseLiabilityValue;
} else {
return calculatePerpLiabilityValue(
userPosition.baseAssetAmount,
oraclePriceData.price,
isVariant(market.contractType, 'prediction')
);
}
}
public getPositionSide(
currentPosition: Pick<PerpPosition, 'baseAssetAmount'>
): PositionDirection | undefined {
if (currentPosition.baseAssetAmount.gt(ZERO)) {
return PositionDirection.LONG;
} else if (currentPosition.baseAssetAmount.lt(ZERO)) {
return PositionDirection.SHORT;
} else {
return undefined;
}
}
/**
* calculates average exit price (optionally for closing up to 100% of position)
* @returns : Precision PRICE_PRECISION
*/
public getPositionEstimatedExitPriceAndPnl(
position: PerpPosition,
amountToClose?: BN,
useAMMClose = false
): [BN, BN] {
const market = this.driftClient.getPerpMarketAccount(position.marketIndex);
const entryPrice = calculateEntryPrice(position);
const oraclePriceData = this.getOracleDataForPerpMarket(
position.marketIndex
);
if (amountToClose) {
if (amountToClose.eq(ZERO)) {
return [calculateReservePrice(market, oraclePriceData), ZERO];
}
position = {
baseAssetAmount: amountToClose,
lastCumulativeFundingRate: position.lastCumulativeFundingRate,
marketIndex: position.marketIndex,
quoteAssetAmount: position.quoteAssetAmount,
} as PerpPosition;
}
let baseAssetValue: BN;
if (useAMMClose) {
baseAssetValue = calculateBaseAssetValue(
market,
position,
oraclePriceData
);
} else {
baseAssetValue = calculateBaseAssetValueWithOracle(
market,
position,
oraclePriceData
);
}
if (position.baseAssetAmount.eq(ZERO)) {
return [ZERO, ZERO];
}
const exitPrice = baseAssetValue
.mul(AMM_TO_QUOTE_PRECISION_RATIO)
.mul(PRICE_PRECISION)
.div(position.baseAssetAmount.abs());
const pnlPerBase = exitPrice.sub(entryPrice);
const pnl = pnlPerBase
.mul(position.baseAssetAmount)
.div(PRICE_PRECISION)
.div(AMM_TO_QUOTE_PRECISION_RATIO);
return [exitPrice, pnl];
}
/**
* calculates current user leverage which is (total liability size) / (net asset value)
* @returns : Precision TEN_THOUSAND
*/
public getLeverage(includeOpenOrders = true): BN {
return this.calculateLeverageFromComponents(
this.getLeverageComponents(includeOpenOrders)
);
}
calculateLeverageFromComponents({
perpLiabilityValue,
perpPnl,
spotAssetValue,
spotLiabilityValue,
}: {
perpLiabilityValue: BN;
perpPnl: BN;
spotAssetValue: BN;
spotLiabilityValue: BN;
}): BN {
const totalLiabilityValue = perpLiabilityValue.add(spotLiabilityValue);
const totalAssetValue = spotAssetValue.add(perpPnl);
const netAssetValue = totalAssetValue.sub(spotLiabilityValue);
if (netAssetValue.eq(ZERO)) {
return ZERO;
}
return totalLiabilityValue.mul(TEN_THOUSAND).div(netAssetValue);
}
getLeverageComponents(
includeOpenOrders = true,
marginCategory: MarginCategory = undefined
): {
perpLiabilityValue: BN;
perpPnl: BN;
spotAssetValue: BN;
spotLiabilityValue: BN;
} {
const perpLiability = this.getTotalPerpPositionLiability(
marginCategory,
undefined,
includeOpenOrders
);
const perpPnl = this.getUnrealizedPNL(true, undefined, marginCategory);
const {
totalAssetValue: spotAssetValue,
totalLiabilityValue: spotLiabilityValue,
} = this.getSpotMarketAssetAndLiabilityValue(
undefined,
marginCategory,
undefined,
includeOpenOrders
);
return {
perpLiabilityValue: perpLiability,
perpPnl,
spotAssetValue,
spotLiabilityValue,
};
}
isDustDepositPosition(spotMarketAccount: SpotMarketAccount): boolean {
const marketIndex = spotMarketAccount.marketIndex;
const spotPosition = this.getSpotPosition(spotMarketAccount.marketIndex);
if (isSpotPositionAvailable(spotPosition)) {
return false;
}
const depositAmount = this.getTokenAmount(spotMarketAccount.marketIndex);
if (depositAmount.lte(ZERO)) {
return false;
}
const oraclePriceData = this.getOracleDataForSpotMarket(marketIndex);
const strictOraclePrice = new StrictOraclePrice(
oraclePriceData.price,
oraclePriceData.twap
);
const balanceValue = this.getSpotAssetValue(
depositAmount,
strictOraclePrice,
spotMarketAccount
);
if (balanceValue.lt(DUST_POSITION_SIZE)) {
return true;
}
return false;
}
getSpotMarketAccountsWithDustPosition() {
const spotMarketAccounts = this.driftClient.getSpotMarketAccounts();
const dustPositionAccounts: SpotMarketAccount[] = [];
for (const spotMarketAccount of spotMarketAccounts) {
const isDust = this.isDustDepositPosition(spotMarketAccount);
if (isDust) {
dustPositionAccounts.push(spotMarketAccount);
}
}
return dustPositionAccounts;
}
getTotalLiabilityValue(marginCategory?: MarginCategory): BN {
return this.getTotalPerpPositionLiability(
marginCategory,
undefined,
true
).add(
this.getSpotMarketLiabilityValue(
undefined,
marginCategory,
undefined,
true
)
);
}
getTotalAssetValue(marginCategory?: MarginCategory): BN {
return this.getSpotMarketAssetValue(undefined, marginCategory, true).add(
this.getUnrealizedPNL(true, undefined, marginCategory)
);
}
getNetUsdValue(): BN {
const netSpotValue = this.getNetSpotMarketValue();
const unrealizedPnl = this.getUnrealizedPNL(true, undefined, undefined);
return netSpotValue.add(unrealizedPnl);
}
/**
* Calculates the all time P&L of the user.
*
* Net withdraws + Net spot market value + Net unrealized P&L -
*/
getTotalAllTimePnl(): BN {
const netUsdValue = this.getNetUsdValue();
const totalDeposits = this.getUserAccount().totalDeposits;
const totalWithdraws = this.getUserAccount().totalWithdraws;
const totalPnl = netUsdValue.add(totalWithdraws).sub(totalDeposits);
return totalPnl;
}
/**
* calculates max allowable leverage exceeding hitting requirement category
* for large sizes where imf factor activates, result is a lower bound
* @param marginCategory {Initial, Maintenance}
* @param isLp if calculating max leveraging for adding lp, need to add buffer
* @returns : Precision TEN_THOUSAND
*/
public getMaxLeverageForPerp(
perpMarketIndex: number,
marginCategory: MarginCategory = 'Initial',
isLp = false
): BN {
const market = this.driftClient.getPerpMarketAccount(perpMarketIndex);
const marketPrice =
this.driftClient.getOracleDataForPerpMarket(perpMarketIndex).price;
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } =
this.getLeverageComponents();
const totalAssetValue = spotAssetValue.add(perpPnl);
const netAssetValue = totalAssetValue.sub(spotLiabilityValue);
if (netAssetValue.eq(ZERO)) {
return ZERO;
}
const totalLiabilityValue = perpLiabilityValue.add(spotLiabilityValue);
const lpBuffer = isLp
? marketPrice.mul(market.amm.orderStepSize).div(AMM_RESERVE_PRECISION)
: ZERO;
const freeCollateral = this.getFreeCollateral().sub(lpBuffer);
let rawMarginRatio;
switch (marginCategory) {
case 'Initial':
rawMarginRatio = Math.max(
market.marginRatioInitial,
this.getUserAccount().maxMarginRatio
);
break;
case 'Maintenance':
rawMarginRatio = market.marginRatioMaintenance;
break;
default:
rawMarginRatio = market.marginRatioInitial;
break;
}
// absolute max fesible size (upper bound)
const maxSize = BN.max(
ZERO,
freeCollateral
.mul(MARGIN_PRECISION)
.div(new BN(rawMarginRatio))
.mul(PRICE_PRECISION)
.div(marketPrice)
);
// margin ratio incorporting upper bound on size
let marginRatio = calculateMarketMarginRatio(
market,
maxSize,
marginCategory,
this.getUserAccount().maxMarginRatio,
this.isHighLeverageMode()
);
// use more fesible size since imf factor activated
let attempts = 0;
while (marginRatio > rawMarginRatio + 1e-4 && attempts < 10) {
// more fesible size (upper bound)
const targetSize = BN.max(
ZERO,
freeCollateral
.mul(MARGIN_PRECISION)
.div(new BN(marginRatio))
.mul(PRICE_PRECISION)
.div(marketPrice)
);
// margin ratio incorporting more fesible target size
marginRatio = calculateMarketMarginRatio(
market,
targetSize,
marginCategory,
this.getUserAccount().maxMarginRatio,
this.isHighLeverageMode()
);
attempts += 1;
}
// how much more liabilities can be opened w remaining free collateral
const additionalLiabilities = freeCollateral
.mul(MARGIN_PRECISION)
.div(new BN(marginRatio));
return totalLiabilityValue
.add(additionalLiabilities)
.mul(TEN_THOUSAND)
.div(netAssetValue);
}
/**
* calculates max allowable leverage exceeding hitting requirement category
* @param spotMarketIndex
* @param direction
* @returns : Precision TEN_THOUSAND
*/
public getMaxLeverageForSpot(
spotMarketIndex: number,
direction: PositionDirection
): BN {
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } =
this.getLeverageComponents();
const totalLiabilityValue = perpLiabilityValue.add(spotLiabilityValue);
const totalAssetValue = spotAssetValue.add(perpPnl);
const netAssetValue = totalAssetValue.sub(spotLiabilityValue);
if (netAssetValue.eq(ZERO)) {
return ZERO;
}
const currentQuoteAssetValue = this.getSpotMarketAssetValue(
QUOTE_SPOT_MARKET_INDEX
);
const currentQuoteLiabilityValue = this.getSpotMarketLiabilityValue(
QUOTE_SPOT_MARKET_INDEX
);
const currentQuoteValue = currentQuoteAssetValue.sub(
currentQuoteLiabilityValue
);
const currentSpotMarketAssetValue =
this.getSpotMarketAssetValue(spotMarketIndex);
const currentSpotMarketLiabilityValue =
this.getSpotMarketLiabilityValue(spotMarketIndex);
const currentSpotMarketNetValue = currentSpotMarketAssetValue.sub(
currentSpotMarketLiabilityValue
);
const tradeQuoteAmount = this.getMaxTradeSizeUSDCForSpot(
spotMarketIndex,
direction,
currentQuoteAssetValue,
currentSpotMarketNetValue
);
let assetValueToAdd = ZERO;
let liabilityValueToAdd = ZERO;
const newQuoteNetValue = isVariant(direction, 'short')
? currentQuoteValue.add(tradeQuoteAmount)
: currentQuoteValue.sub(tradeQuoteAmount);
const newQuoteAssetValue = BN.max(newQuoteNetValue, ZERO);
const newQuoteLiabilityValue = BN.min(newQuoteNetValue, ZERO).abs();
assetValueToAdd = assetValueToAdd.add(
newQuoteAssetValue.sub(currentQuoteAssetValue)
);
liabilityValueToAdd = liabilityValueToAdd.add(
newQuoteLiabilityValue.sub(currentQuoteLiabilityValue)
);
const newSpotMarketNetValue = isVariant(direction, 'long')
? currentSpotMarketNetValue.add(tradeQuoteAmount)
: currentSpotMarketNetValue.sub(tradeQuoteAmount);
const newSpotMarketAssetValue = BN.max(newSpotMarketNetValue, ZERO);
const newSpotMarketLiabilityValue = BN.min(
newSpotMarketNetValue,
ZERO
).abs();
assetValueToAdd = assetValueToAdd.add(
newSpotMarketAssetValue.sub(currentSpotMarketAssetValue)
);
liabilityValueToAdd = liabilityValueToAdd.add(
newSpotMarketLiabilityValue.sub(currentSpotMarketLiabilityValue)
);
const finalTotalAssetValue = totalAssetValue.add(assetValueToAdd);
const finalTotalSpotLiability = spotLiabilityValue.add(liabilityValueToAdd);
const finalTotalLiabilityValue =
totalLiabilityValue.add(liabilityValueToAdd);
const finalNetAssetValue = finalTotalAssetValue.sub(
finalTotalSpotLiability
);
return finalTotalLiabilityValue.mul(TEN_THOUSAND).div(finalNetAssetValue);
}
/**
* calculates margin ratio: 1 / leverage
* @returns : Precision TEN_THOUSAND
*/
public getMarginRatio(): BN {
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } =
this.getLeverageComponents();
const totalLiabilityValue = perpLiabilityValue.add(spotLiabilityValue);
const totalAssetValue = spotAssetValue.add(perpPnl);
if (totalLiabilityValue.eq(ZERO)) {
return BN_MAX;
}
const netAssetValue = totalAssetValue.sub(spotLiabilityValue);
return netAssetValue.mul(TEN_THOUSAND).div(totalLiabilityValue);
}
public canBeLiquidated(): {
canBeLiquidated: boolean;
marginRequirement: BN;
totalCollateral: BN;
} {
const totalCollateral = this.getTotalCollateral('Maintenance');
const marginRequirement = this.getMaintenanceMarginRequirement();
const canBeLiquidated = totalCollateral.lt(marginRequirement);
return {
canBeLiquidated,
marginRequirement,
totalCollateral,
};
}
public isBeingLiquidated(): boolean {
return (
(this.getUserAccount().status &
(UserStatus.BEING_LIQUIDATED | UserStatus.BANKRUPT)) >
0
);
}
public hasStatus(status: UserStatus): boolean {
return (this.getUserAccount().status & status) > 0;
}
public isBankrupt(): boolean {
return (this.getUserAccount().status & UserStatus.BANKRUPT) > 0;
}
public isHighLeverageMode(): boolean {
return isVariant(this.getUserAccount().marginMode, 'highLeverage');
}
/**
* Checks if any user position cumulative funding differs from respective market cumulative funding
* @returns
*/
public needsToSettleFundingPayment(): boolean {
for (const userPosition of this.getUserAccount().perpPositions) {
if (userPosition.baseAssetAmount.eq(ZERO)) {
continue;
}
const market = this.driftClient.getPerpMarketAccount(
userPosition.marketIndex
);
if (
market.amm.cumulativeFundingRateLong.eq(
userPosition.lastCumulativeFundingRate
) ||
market.amm.cumulativeFundingRateShort.eq(
userPosition.lastCumulativeFundingRate
)
) {
continue;
}
return true;
}
return false;
}
/**
* Calculate the liquidation price of a spot position
* @param marketIndex
* @returns Precision : PRICE_PRECISION
*/
public spotLiquidationPrice(
marketIndex: number,
positionBaseSizeChange: BN = ZERO
): BN {
const currentSpotPosition = this.getSpotPosition(marketIndex);
if (!currentSpotPosition) {
return new BN(-1);
}
const totalCollateral = this.getTotalCollateral('Maintenance');
const maintenanceMarginRequirement = this.getMaintenanceMarginRequirement();
const freeCollateral = BN.max(
ZERO,
totalCollateral.sub(maintenanceMarginRequirement)
);
const market = this.driftClient.getSpotMarketAccount(marketIndex);
let signedTokenAmount = getSignedTokenAmount(
getTokenAmount(
currentSpotPosition.scaledBalance,
market,
currentSpotPosition.balanceType
),
currentSpotPosition.balanceType
);
signedTokenAmount = signedTokenAmount.add(positionBaseSizeChange);
if (signedTokenAmount.eq(ZERO)) {
return new BN(-1);
}
let freeCollateralDelta = this.calculateFreeCollateralDeltaForSpot(
market,
signedTokenAmount
);
const oracle = market.oracle;
const perpMarketWithSameOracle = this.driftClient
.getPerpMarketAccounts()
.find((market) => market.amm.oracle.equals(oracle));
const oraclePrice =
this.driftClient.getOracleDataForSpotMarket(marketIndex).price;
if (perpMarketWithSameOracle) {
const perpPosition = this.getPerpPositionWithLPSettle(
perpMarketWithSameOracle.marketIndex,
undefined,
true
)[0];
if (perpPosition) {
const freeCollateralDeltaForPerp =
this.calculateFreeCollateralDeltaForPerp(
perpMarketWithSameOracle,
perpPosition,
ZERO,
oraclePrice
);
freeCollateralDelta = freeCollateralDelta.add(
freeCollateralDeltaForPerp || ZERO
);
}
}
if (freeCollateralDelta.eq(ZERO)) {
return new BN(-1);
}
const liqPriceDelta = freeCollateral
.mul(QUOTE_PRECISION)
.div(freeCollateralDelta);
const liqPrice = oraclePrice.sub(liqPriceDelta);
if (liqPrice.lt(ZERO)) {
return new BN(-1);
}
return liqPrice;
}
/**
* Calculate the liquidation price of a perp position, with optional parameter to calculate the liquidation price after a trade
* @param marketIndex
* @param positionBaseSizeChange // change in position size to calculate liquidation price for : Precision 10^9
* @param estimatedEntryPrice
* @param marginCategory // allow Initial to be passed in if we are trying to calculate price for DLP de-risking
* @param includeOpenOrders
* @param offsetCollateral // allows calculating the liquidation price after this offset collateral is added to the user's account (e.g. : what will the liquidation price be for this position AFTER I deposit $x worth of collateral)
* @returns Precision : PRICE_PRECISION
*/
public liquidationPrice(
marketIndex: number,
positionBaseSizeChange: BN = ZERO,
estimatedEntryPrice: BN = ZERO,
marginCategory: MarginCategory = 'Maintenance',
includeOpenOrders = false,
offsetCollateral = ZERO
): BN {
const totalCollateral = this.getTotalCollateral(
marginCategory,
false,
includeOpenOrders
);
const marginRequirement = this.getMarginRequirement(
marginCategory,
undefined,
false,
includeOpenOrders
);
let freeCollateral = BN.max(
ZERO,
totalCollateral.sub(marginRequirement)
).add(offsetCollateral);
const oracle =
this.driftClient.getPerpMarketAccount(marketIndex).amm.oracle;
const oraclePrice =
this.driftClient.getOracleDataForPerpMarket(marketIndex).price;
const market = this.driftClient.getPerpMarketAccount(marketIndex);
const currentPerpPosition =
this.getPerpPositionWithLPSettle(marketIndex, undefined, true)[0] ||
this.getEmptyPosition(marketIndex);
positionBaseSizeChange = standardizeBaseAssetAmount(
positionBaseSizeChange,
market.amm.orderStepSize
);
const freeCollateralChangeFromNewPosition =
this.calculateEntriesEffectOnFreeCollateral(
market,
oraclePrice,
currentPerpPosition,
positionBaseSizeChange,
estimatedEntryPrice,
includeOpenOrders
);
freeCollateral = freeCollateral.add(freeCollateralChangeFromNewPosition);
let freeCollateralDelta = this.calculateFreeCollateralDeltaForPerp(
market,
currentPerpPosition,
positionBaseSizeChange,
oraclePrice,
marginCategory,
includeOpenOrders
);
if (!freeCollateralDelta) {
return new BN(-1);
}
const spotMarketWithSameOracle = this.driftClient
.getSpotMarketAccounts()
.find((market) => market.oracle.equals(oracle));
if (spotMarketWithSameOracle) {
const spotPosition = this.getSpotPosition(
spotMarketWithSameOracle.marketIndex
);
if (spotPosition) {
const signedTokenAmount = getSignedTokenAmount(
getTokenAmount(
spotPosition.scaledBalance,
spotMarketWithSameOracle,
spotPosition.balanceType
),
spotPosition.balanceType
);
const spotFreeCollateralDelta =
this.calculateFreeCollateralDeltaForSpot(
spotMarketWithSameOracle,
signedTokenAmount,
marginCategory
);
freeCollateralDelta = freeCollateralDelta.add(
spotFreeCollateralDelta || ZERO
);
}
}
if (freeCollateralDelta.eq(ZERO)) {
return new BN(-1);
}
const liqPriceDelta = freeCollateral
.mul(QUOTE_PRECISION)
.div(freeCollateralDelta);
const liqPrice = oraclePrice.sub(liqPriceDelta);
if (liqPrice.lt(ZERO)) {
return new BN(-1);
}
return liqPrice;
}
calculateEntriesEffectOnFreeCollateral(
market: PerpMarketAccount,
oraclePrice: BN,
perpPosition: PerpPosition,
positionBaseSizeChange: BN,
estimatedEntryPrice: BN,
includeOpenOrders: boolean
): BN {
let freeCollateralChange = ZERO;
// update free collateral to account for change in pnl from new position
if (!estimatedEntryPrice.eq(ZERO) && !positionBaseSizeChange.eq(ZERO)) {
const costBasis = oraclePrice
.mul(positionBaseSizeChange.abs())
.div(BASE_PRECISION);
const newPositionValue = estimatedEntryPrice
.mul(positionBaseSizeChange.abs())
.div(BASE_PRECISION);
if (positionBaseSizeChange.gt(ZERO)) {
freeCollateralChange = costBasis.sub(newPositionValue);
} else {
freeCollateralChange = newPositionValue.sub(costBasis);
}
// assume worst fee tier
const takerFeeTier =
this.driftClient.getStateAccount().perpFeeStructure.feeTiers[0];
const takerFee = newPositionValue
.muln(takerFeeTier.feeNumerator)
.divn(takerFeeTier.feeDenominator);
freeCollateralChange = freeCollateralChange.sub(takerFee);
}
const calculateMarginRequirement = (perpPosition: PerpPosition) => {
let baseAssetAmount: BN;
let liabilityValue: BN;
if (includeOpenOrders) {
const { worstCaseBaseAssetAmount, worstCaseLiabilityValue } =
calculateWorstCasePerpLiabilityValue(
perpPosition,
market,
oraclePrice
);
baseAssetAmount = worstCaseBaseAssetAmount;
liabilityValue = worstCaseLiabilityValue;
} else {
baseAssetAmount = perpPosition.baseAssetAmount;
liabilityValue = calculatePerpLiabilityValue(
baseAssetAmount,
oraclePrice,
isVariant(market.contractType, 'prediction')
);
}
const marginRatio = calculateMarketMarginRatio(
market,
baseAssetAmount.abs(),
'Maintenance',
this.getUserAccount().maxMarginRatio,
this.isHighLeverageMode()
);
return liabilityValue.mul(new BN(marginRatio)).div(MARGIN_PRECISION);
};
const freeCollateralConsumptionBefore =
calculateMarginRequirement(perpPosition);
const perpPositionAfter = Object.assign({}, perpPosition);
perpPositionAfter.baseAssetAmount = perpPositionAfter.baseAssetAmount.add(
positionBaseSizeChange
);
const freeCollateralConsumptionAfter =
calculateMarginRequirement(perpPositionAfter);
return freeCollateralChange.sub(
freeCollateralConsumptionAfter.sub(freeCollateralConsumptionBefore)
);
}
calculateFreeCollateralDeltaForPerp(
market: PerpMarketAccount,
perpPosition: PerpPosition,
positionBaseSizeChange: BN,
oraclePrice: BN,
marginCategory: MarginCategory = 'Maintenance',
includeOpenOrders = false
): BN | undefined {
const baseAssetAmount = includeOpenOrders
? calculateWorstCaseBaseAssetAmount(perpPosition, market, oraclePrice)
: perpPosition.baseAssetAmount;
// zero if include orders == false
const orderBaseAssetAmount = baseAssetAmount.sub(
perpPosition.baseAssetAmount
);
const proposedBaseAssetAmount = baseAssetAmount.add(positionBaseSizeChange);
const marginRatio = calculateMarketMarginRatio(
market,
proposedBaseAssetAmount.abs(),
marginCategory,
this.getUserAccount().maxMarginRatio,
this.isHighLeverageMode()
);
const marginRatioQuotePrecision = new BN(marginRatio)
.mul(QUOTE_PRECISION)
.div(MARGIN_PRECISION);
if (proposedBaseAssetAmount.eq(ZERO)) {
return undefined;
}
let freeCollateralDelta = ZERO;
if (isVariant(market.contractType, 'prediction')) {
// for prediction market, increase in pnl and margin requirement will net out for position
// open order margin requirement will change with price though
if (orderBaseAssetAmount.gt(ZERO)) {
freeCollateralDelta = marginRatioQuotePrecision.neg();
} else if (orderBaseAssetAmount.lt(ZERO)) {
freeCollateralDelta = marginRatioQuotePrecision;
}
} else {
if (proposedBaseAssetAmount.gt(ZERO)) {
freeCollateralDelta = QUOTE_PRECISION.sub(marginRatioQuotePrecision)
.mul(proposedBaseAssetAmount)
.div(BASE_PRECISION);
} else {
freeCollateralDelta = QUOTE_PRECISION.neg()
.sub(marginRatioQuotePrecision)
.mul(proposedBaseAssetAmount.abs())
.div(BASE_PRECISION);
}
if (!orderBaseAssetAmount.eq(ZERO)) {
freeCollateralDelta = freeCollateralDelta.sub(
marginRatioQuotePrecision
.mul(orderBaseAssetAmount.abs())
.div(BASE_PRECISION)
);
}
}
return freeCollateralDelta;
}
calculateFreeCollateralDeltaForSpot(
market: SpotMarketAccount,
signedTokenAmount: BN,
marginCategory: MarginCategory = 'Maintenance'
): BN {
const tokenPrecision = new BN(Math.pow(10, market.decimals));
if (signedTokenAmount.gt(ZERO)) {
const assetWeight = calculateAssetWeight(
signedTokenAmount,
this.driftClient.getOracleDataForSpotMarket(market.marketIndex).price,
market,
marginCategory
);
return QUOTE_PRECISION.mul(assetWeight)
.div(SPOT_MARKET_WEIGHT_PRECISION)
.mul(signedTokenAmount)
.div(tokenPrecision);
} else {
const liabilityWeight = calculateLiabilityWeight(
signedTokenAmount.abs(),
market,
marginCategory
);
return QUOTE_PRECISION.neg()
.mul(liabilityWeight)
.div(SPOT_MARKET_WEIGHT_PRECISION)
.mul(signedTokenAmount.abs())
.div(tokenPrecision);
}
}
/**
* Calculates the estimated liquidation price for a position after closing a quote amount of the position.
* @param positionMarketIndex
* @param closeQuoteAmount
* @returns : Precision PRICE_PRECISION
*/
public liquidationPriceAfterClose(
positionMarketIndex: number,
closeQuoteAmount: BN,
estimatedEntryPrice: BN = ZERO
): BN {
const currentPosition =
this.getPerpPositionWithLPSettle(
positionMarketIndex,
undefined,
true
)[0] || this.getEmptyPosition(positionMarketIndex);
const closeBaseAmount = currentPosition.baseAssetAmount
.mul(closeQuoteAmount)
.div(currentPosition.quoteAssetAmount.abs())
.add(
currentPosition.baseAssetAmount
.mul(closeQuoteAmount)
.mod(currentPosition.quoteAssetAmount.abs())
)
.neg();
return this.liquidationPrice(
positionMarketIndex,
closeBaseAmount,
estimatedEntryPrice
);
}
public getMarginUSDCRequiredForTrade(
targetMarketIndex: number,
baseSize: BN,
estEntryPrice?: BN
): BN {
return calculateMarginUSDCRequiredForTrade(
this.driftClient,
targetMarketIndex,
baseSize,
this.getUserAccount().maxMarginRatio,
undefined,
estEntryPrice
);
}
public getCollateralDepositRequiredForTrade(
targetMarketIndex: number,
baseSize: BN,
collateralIndex: number
): BN {
return calculateCollateralDepositRequiredForTrade(
this.driftClient,
targetMarketIndex,
baseSize,
collateralIndex,
this.getUserAccount().maxMarginRatio,
false // assume user cant be high leverage if they havent created user account ?
);
}
/**
* Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.
*
* To Calculate Max Quote Available:
*
* Case 1: SameSide
* => Remaining quote to get to maxLeverage
*
* Case 2: NOT SameSide && currentLeverage <= maxLeverage
* => Current opposite position x2 + remaining to get to maxLeverage
*
* Case 3: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition > maxLeverage
* => strictly reduce current position size
*
* Case 4: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition < maxLeverage
* => current position + remaining to get to maxLeverage
*
* @param targetMarketIndex
* @param tradeSide
* @param isLp
* @returns { tradeSize: BN, oppositeSideTradeSize: BN} : Precision QUOTE_PRECISION
*/
public getMaxTradeSizeUSDCForPerp(
targetMarketIndex: number,
tradeSide: PositionDirection,
isLp = false
): { tradeSize: BN; oppositeSideTradeSize: BN } {
let tradeSize = ZERO;
let oppositeSideTradeSize = ZERO;
const currentPosition =
this.getPerpPositionWithLPSettle(targetMarketIndex, undefined, true)[0] ||
this.getEmptyPosition(targetMarketIndex);
const targetSide = isVariant(tradeSide, 'short') ? 'short' : 'long';
const currentPositionSide = currentPosition?.baseAssetAmount.isNeg()
? 'short'
: 'long';
const targetingSameSide = !currentPosition
? true
: targetSide === currentPositionSide;
const oracleData = this.getOracleDataForPerpMarket(targetMarketIndex);
const marketAccount =
this.driftClient.getPerpMarketAccount(targetMarketIndex);
const lpBuffer = isLp
? oracleData.price
.mul(marketAccount.amm.orderStepSize)
.div(AMM_RESERVE_PRECISION)
: ZERO;
// add any position we have on the opposite side of the current trade, because we can "flip" the size of this position without taking any extra leverage.
const oppositeSizeLiabilityValue = targetingSameSide
? ZERO
: calculatePerpLiabilityValue(
currentPosition.baseAssetAmount,
oracleData.price,
isVariant(marketAccount.contractType, 'prediction')
);
const maxPositionSize = this.getPerpBuyingPower(
targetMarketIndex,
lpBuffer
);
if (maxPositionSize.gte(ZERO)) {
if (oppositeSizeLiabilityValue.eq(ZERO)) {
// case 1 : Regular trade where current total position less than max, and no opposite position to account for
// do nothing
tradeSize = maxPositionSize;
} else {
// case 2 : trade where current total position less than max, but need to account for flipping the current position over to the other side
tradeSize = maxPositionSize.add(oppositeSizeLiabilityValue);
oppositeSideTradeSize = oppositeSizeLiabilityValue;
}
} else {
// current leverage is greater than max leverage - can only reduce position size
if (!targetingSameSide) {
const market = this.driftClient.getPerpMarketAccount(targetMarketIndex);
const perpLiabilityValue = calculatePerpLiabilityValue(
currentPosition.baseAssetAmount,
oracleData.price,
isVariant(market.contractType, 'prediction')
);
const totalCollateral = this.getTotalCollateral();
const marginRequirement = this.getInitialMarginRequirement();
const marginFreedByClosing = perpLiabilityValue
.mul(new BN(market.marginRatioInitial))
.div(MARGIN_PRECISION);
const marginRequirementAfterClosing =
marginRequirement.sub(marginFreedByClosing);
if (marginRequirementAfterClosing.gt(totalCollateral)) {
oppositeSideTradeSize = perpLiabilityValue;
} else {
const freeCollateralAfterClose = totalCollateral.sub(
marginRequirementAfterClosing
);
const buyingPowerAfterClose =
this.getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(
targetMarketIndex,
freeCollateralAfterClose,
ZERO
);
oppositeSideTradeSize = perpLiabilityValue;
tradeSize = buyingPowerAfterClose;
}
} else {
// do nothing if targetting same side
tradeSize = maxPositionSize;
}
}
return { tradeSize, oppositeSideTradeSize };
}
/**
* Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.
*
* @param targetMarketIndex
* @param direction
* @param currentQuoteAssetValue
* @param currentSpotMarketNetValue
* @returns tradeSizeAllowed : Precision QUOTE_PRECISION
*/
public getMaxTradeSizeUSDCForSpot(
targetMarketIndex: number,
direction: PositionDirection,
currentQuoteAssetValue?: BN,
currentSpotMarketNetValue?: BN
): BN {
const market = this.driftClient.getSpotMarketAccount(targetMarketIndex);
const oraclePrice =
this.driftClient.getOracleDataForSpotMarket(targetMarketIndex).price;
currentQuoteAssetValue = this.getSpotMarketAssetValue(
QUOTE_SPOT_MARKET_INDEX
);
currentSpotMarketNetValue =
currentSpotMarketNetValue ?? this.getSpotPositionValue(targetMarketIndex);
let freeCollateral = this.getFreeCollateral();
const marginRatio = calculateSpotMarketMarginRatio(
market,
oraclePrice,
'Initial',
ZERO,
isVariant(direction, 'long')
? SpotBalanceType.DEPOSIT
: SpotBalanceType.BORROW,
this.getUserAccount().maxMarginRatio
);
let tradeAmount = ZERO;
if (this.getUserAccount().isMarginTradingEnabled) {
// if the user is buying/selling and already short/long, need to account for closing out short/long
if (isVariant(direction, 'long') && currentSpotMarketNetValue.lt(ZERO)) {
tradeAmount = currentSpotMarketNetValue.abs();
const marginRatio = calculateSpotMarketMarginRatio(
market,
oraclePrice,
'Initial',
this.getTokenAmount(targetMarketIndex).abs(),
SpotBalanceType.BORROW,
this.getUserAccount().maxMarginRatio
);
freeCollateral = freeCollateral.add(
tradeAmount.mul(new BN(marginRatio)).div(MARGIN_PRECISION)
);
} else if (
isVariant(direction, 'short') &&
currentSpotMarketNetValue.gt(ZERO)
) {
tradeAmount = currentSpotMarketNetValue;
const marginRatio = calculateSpotMarketMarginRatio(
market,
oraclePrice,
'Initial',
this.getTokenAmount(targetMarketIndex),
SpotBalanceType.DEPOSIT,
this.getUserAccount().maxMarginRatio
);
freeCollateral = freeCollateral.add(
tradeAmount.mul(new BN(marginRatio)).div(MARGIN_PRECISION)
);
}
tradeAmount = tradeAmount.add(
freeCollateral.mul(MARGIN_PRECISION).div(new BN(marginRatio))
);
} else if (isVariant(direction, 'long')) {
tradeAmount = BN.min(
currentQuoteAssetValue,
freeCollateral.mul(MARGIN_PRECISION).div(new BN(marginRatio))
);
} else {
tradeAmount = BN.max(ZERO, currentSpotMarketNetValue);
}
return tradeAmount;
}
/**
* Calculates the max amount of token that can be swapped from inMarket to outMarket
* Assumes swap happens at oracle price
*
* @param inMarketIndex
* @param outMarketIndex
* @param calculateSwap function to similate in to out swa
* @param iterationLimit how long to run appromixation before erroring out
*/
public getMaxSwapAmount({
inMarketIndex,
outMarketIndex,
calculateSwap,
iterationLimit = 1000,
}: {
inMarketIndex: number;
outMarketIndex: number;
calculateSwap?: (inAmount: BN) => BN;
iterationLimit?: number;
}): { inAmount: BN; outAmount: BN; leverage: BN } {
const inMarket = this.driftClient.getSpotMarketAccount(inMarketIndex);
const outMarket = this.driftClient.getSpotMarketAccount(outMarketIndex);
const inOraclePriceData = this.getOracleDataForSpotMarket(inMarketIndex);
const inOraclePrice = inOraclePriceData.price;
const outOraclePriceData = this.getOracleDataForSpotMarket(outMarketIndex);
const outOraclePrice = outOraclePriceData.price;
const inStrictOraclePrice = new StrictOraclePrice(inOraclePrice);
const outStrictOraclePrice = new StrictOraclePrice(outOraclePrice);
const inPrecision = new BN(10 ** inMarket.decimals);
const outPrecision = new BN(10 ** outMarket.decimals);
const inSpotPosition =
this.getSpotPosition(inMarketIndex) ||
this.getEmptySpotPosition(inMarketIndex);
const outSpotPosition =
this.getSpotPosition(outMarketIndex) ||
this.getEmptySpotPosition(outMarketIndex);
const freeCollateral = this.getFreeCollateral();
const inContributionInitial =
this.calculateSpotPositionFreeCollateralContribution(
inSpotPosition,
inStrictOraclePrice
);
const {
totalAssetValue: inTotalAssetValueInitial,
totalLiabilityValue: inTotalLiabilityValueInitial,
} = this.calculateSpotPositionLeverageContribution(
inSpotPosition,
inStrictOraclePrice
);
const outContributionInitial =
this.calculateSpotPositionFreeCollateralContribution(
outSpotPosition,
outStrictOraclePrice
);
const {
totalAssetValue: outTotalAssetValueInitial,
totalLiabilityValue: outTotalLiabilityValueInitial,
} = this.calculateSpotPositionLeverageContribution(
outSpotPosition,
outStrictOraclePrice
);
const initialContribution = inContributionInitial.add(
outContributionInitial
);
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } =
this.getLeverageComponents();
if (!calculateSwap) {
calculateSwap = (inSwap: BN) => {
return inSwap
.mul(outPrecision)
.mul(inOraclePrice)
.div(outOraclePrice)
.div(inPrecision);
};
}
let inSwap = ZERO;
let outSwap = ZERO;
const inTokenAmount = this.getTokenAmount(inMarketIndex);
const outTokenAmount = this.getTokenAmount(outMarketIndex);
const inAssetWeight = calculateAssetWeight(
inTokenAmount,
inOraclePriceData.price,
inMarket,
'Initial'
);
const outAssetWeight = calculateAssetWeight(
outTokenAmount,
outOraclePriceData.price,
outMarket,
'Initial'
);
const outSaferThanIn =
// selling asset to close borrow
(inTokenAmount.gt(ZERO) && outTokenAmount.lt(ZERO)) ||
// buying asset with higher initial asset weight
inAssetWeight.lt(outAssetWeight);
if (freeCollateral.lt(PRICE_PRECISION.divn(100))) {
if (outSaferThanIn && inTokenAmount.gt(ZERO)) {
inSwap = inTokenAmount;
outSwap = calculateSwap(inSwap);
}
} else {
let minSwap = ZERO;
let maxSwap = BN.max(
freeCollateral.mul(inPrecision).mul(new BN(100)).div(inOraclePrice), // 100x current free collateral
inTokenAmount.abs().mul(new BN(10)) // 10x current position
);
inSwap = maxSwap.div(TWO);
const error = freeCollateral.div(new BN(10000));
let i = 0;
let freeCollateralAfter = freeCollateral;
while (freeCollateralAfter.gt(error) || freeCollateralAfter.isNeg()) {
outSwap = calculateSwap(inSwap);
const inPositionAfter = this.cloneAndUpdateSpotPosition(
inSpotPosition,
inSwap.neg(),
inMarket
);
const outPositionAfter = this.cloneAndUpdateSpotPosition(
outSpotPosition,
outSwap,
outMarket
);
const inContributionAfter =
this.calculateSpotPositionFreeCollateralContribution(
inPositionAfter,
inStrictOraclePrice
);
const outContributionAfter =
this.calculateSpotPositionFreeCollateralContribution(
outPositionAfter,
outStrictOraclePrice
);
const contributionAfter = inContributionAfter.add(outContributionAfter);
const contributionDelta = contributionAfter.sub(initialContribution);
freeCollateralAfter = freeCollateral.add(contributionDelta);
if (freeCollateralAfter.gt(error)) {
minSwap = inSwap;
inSwap = minSwap.add(maxSwap).div(TWO);
} else if (freeCollateralAfter.isNeg()) {
maxSwap = inSwap;
inSwap = minSwap.add(maxSwap).div(TWO);
}
if (i++ > iterationLimit) {
console.log('getMaxSwapAmount iteration limit reached');
break;
}
}
}
const inPositionAfter = this.cloneAndUpdateSpotPosition(
inSpotPosition,
inSwap.neg(),
inMarket
);
const outPositionAfter = this.cloneAndUpdateSpotPosition(
outSpotPosition,
outSwap,
outMarket
);
const {
totalAssetValue: inTotalAssetValueAfter,
totalLiabilityValue: inTotalLiabilityValueAfter,
} = this.calculateSpotPositionLeverageContribution(
inPositionAfter,
inStrictOraclePrice
);
const {
totalAssetValue: outTotalAssetValueAfter,
totalLiabilityValue: outTotalLiabilityValueAfter,
} = this.calculateSpotPositionLeverageContribution(
outPositionAfter,
outStrictOraclePrice
);
const spotAssetValueDelta = inTotalAssetValueAfter
.add(outTotalAssetValueAfter)
.sub(inTotalAssetValueInitial)
.sub(outTotalAssetValueInitial);
const spotLiabilityValueDelta = inTotalLiabilityValueAfter
.add(outTotalLiabilityValueAfter)
.sub(inTotalLiabilityValueInitial)
.sub(outTotalLiabilityValueInitial);
const spotAssetValueAfter = spotAssetValue.add(spotAssetValueDelta);
const spotLiabilityValueAfter = spotLiabilityValue.add(
spotLiabilityValueDelta
);
const leverage = this.calculateLeverageFromComponents({
perpLiabilityValue,
perpPnl,
spotAssetValue: spotAssetValueAfter,
spotLiabilityValue: spotLiabilityValueAfter,
});
return { inAmount: inSwap, outAmount: outSwap, leverage };
}
public cloneAndUpdateSpotPosition(
position: SpotPosition,
tokenAmount: BN,
market: SpotMarketAccount
): SpotPosition {
const clonedPosition = Object.assign({}, position);
if (tokenAmount.eq(ZERO)) {
return clonedPosition;
}
const preTokenAmount = getSignedTokenAmount(
getTokenAmount(position.scaledBalance, market, position.balanceType),
position.balanceType
);
if (sigNum(preTokenAmount).eq(sigNum(tokenAmount))) {
const scaledBalanceDelta = getBalance(
tokenAmount.abs(),
market,
position.balanceType
);
clonedPosition.scaledBalance =
clonedPosition.scaledBalance.add(scaledBalanceDelta);
return clonedPosition;
}
const updateDirection = tokenAmount.isNeg()
? SpotBalanceType.BORROW
: SpotBalanceType.DEPOSIT;
if (tokenAmount.abs().gte(preTokenAmount.abs())) {
clonedPosition.scaledBalance = getBalance(
tokenAmount.abs().sub(preTokenAmount.abs()),
market,
updateDirection
);
clonedPosition.balanceType = updateDirection;
} else {
const scaledBalanceDelta = getBalance(
tokenAmount.abs(),
market,
position.balanceType
);
clonedPosition.scaledBalance =
clonedPosition.scaledBalance.sub(scaledBalanceDelta);
}
return clonedPosition;
}
calculateSpotPositionFreeCollateralContribution(
spotPosition: SpotPosition,
strictOraclePrice: StrictOraclePrice
): BN {
const marginCategory = 'Initial';
const spotMarketAccount: SpotMarketAccount =
this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
const { freeCollateralContribution } = getWorstCaseTokenAmounts(
spotPosition,
spotMarketAccount,
strictOraclePrice,
marginCategory,
this.getUserAccount().maxMarginRatio
);
return freeCollateralContribution;
}
calculateSpotPositionLeverageContribution(
spotPosition: SpotPosition,
strictOraclePrice: StrictOraclePrice
): {
totalAssetValue: BN;
totalLiabilityValue: BN;
} {
let totalAssetValue = ZERO;
let totalLiabilityValue = ZERO;
const spotMarketAccount: SpotMarketAccount =
this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
const { tokenValue, ordersValue } = getWorstCaseTokenAmounts(
spotPosition,
spotMarketAccount,
strictOraclePrice,
'Initial',
this.getUserAccount().maxMarginRatio
);
if (tokenValue.gte(ZERO)) {
totalAssetValue = tokenValue;
} else {
totalLiabilityValue = tokenValue.abs();
}
if (ordersValue.gt(ZERO)) {
totalAssetValue = totalAssetValue.add(ordersValue);
} else {
totalLiabilityValue = totalLiabilityValue.add(ordersValue.abs());
}
return {
totalAssetValue,
totalLiabilityValue,
};
}
/**
* Estimates what the user leverage will be after swap
* @param inMarketIndex
* @param outMarketIndex
* @param inAmount
* @param outAmount
*/
public accountLeverageAfterSwap({
inMarketIndex,
outMarketIndex,
inAmount,
outAmount,
}: {
inMarketIndex: number;
outMarketIndex: number;
inAmount: BN;
outAmount: BN;
}): BN {
const inMarket = this.driftClient.getSpotMarketAccount(inMarketIndex);
const outMarket = this.driftClient.getSpotMarketAccount(outMarketIndex);
const inOraclePriceData = this.getOracleDataForSpotMarket(inMarketIndex);
const inOraclePrice = inOraclePriceData.price;
const outOraclePriceData = this.getOracleDataForSpotMarket(outMarketIndex);
const outOraclePrice = outOraclePriceData.price;
const inStrictOraclePrice = new StrictOraclePrice(inOraclePrice);
const outStrictOraclePrice = new StrictOraclePrice(outOraclePrice);
const inSpotPosition =
this.getSpotPosition(inMarketIndex) ||
this.getEmptySpotPosition(inMarketIndex);
const outSpotPosition =
this.getSpotPosition(outMarketIndex) ||
this.getEmptySpotPosition(outMarketIndex);
const {
totalAssetValue: inTotalAssetValueInitial,
totalLiabilityValue: inTotalLiabilityValueInitial,
} = this.calculateSpotPositionLeverageContribution(
inSpotPosition,
inStrictOraclePrice
);
const {
totalAssetValue: outTotalAssetValueInitial,
totalLiabilityValue: outTotalLiabilityValueInitial,
} = this.calculateSpotPositionLeverageContribution(
outSpotPosition,
outStrictOraclePrice
);
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } =
this.getLeverageComponents();
const inPositionAfter = this.cloneAndUpdateSpotPosition(
inSpotPosition,
inAmount.abs().neg(),
inMarket
);
const outPositionAfter = this.cloneAndUpdateSpotPosition(
outSpotPosition,
outAmount.abs(),
outMarket
);
const {
totalAssetValue: inTotalAssetValueAfter,
totalLiabilityValue: inTotalLiabilityValueAfter,
} = this.calculateSpotPositionLeverageContribution(
inPositionAfter,
inStrictOraclePrice
);
const {
totalAssetValue: outTotalAssetValueAfter,
totalLiabilityValue: outTotalLiabilityValueAfter,
} = this.calculateSpotPositionLeverageContribution(
outPositionAfter,
outStrictOraclePrice
);
const spotAssetValueDelta = inTotalAssetValueAfter
.add(outTotalAssetValueAfter)
.sub(inTotalAssetValueInitial)
.sub(outTotalAssetValueInitial);
const spotLiabilityValueDelta = inTotalLiabilityValueAfter
.add(outTotalLiabilityValueAfter)
.sub(inTotalLiabilityValueInitial)
.sub(outTotalLiabilityValueInitial);
const spotAssetValueAfter = spotAssetValue.add(spotAssetValueDelta);
const spotLiabilityValueAfter = spotLiabilityValue.add(
spotLiabilityValueDelta
);
return this.calculateLeverageFromComponents({
perpLiabilityValue,
perpPnl,
spotAssetValue: spotAssetValueAfter,
spotLiabilityValue: spotLiabilityValueAfter,
});
}
// TODO - should this take the price impact of the trade into account for strict accuracy?
/**
* Returns the leverage ratio for the account after adding (or subtracting) the given quote size to the given position
* @param targetMarketIndex
* @param: targetMarketType
* @param tradeQuoteAmount
* @param tradeSide
* @param includeOpenOrders
* @returns leverageRatio : Precision TEN_THOUSAND
*/
public accountLeverageRatioAfterTrade(
targetMarketIndex: number,
targetMarketType: MarketType,
tradeQuoteAmount: BN,
tradeSide: PositionDirection,
includeOpenOrders = true
): BN {
const tradeIsPerp = isVariant(targetMarketType, 'perp');
if (!tradeIsPerp) {
// calculate new asset/liability values for base and quote market to find new account leverage
const totalLiabilityValue = this.getTotalLiabilityValue();
const totalAssetValue = this.getTotalAssetValue();
const spotLiabilityValue = this.getSpotMarketLiabilityValue(
undefined,
undefined,
undefined,
includeOpenOrders
);
const currentQuoteAssetValue = this.getSpotMarketAssetValue(
QUOTE_SPOT_MARKET_INDEX,
undefined,
includeOpenOrders
);
const currentQuoteLiabilityValue = this.getSpotMarketLiabilityValue(
QUOTE_SPOT_MARKET_INDEX,
undefined,
undefined,
includeOpenOrders
);
const currentQuoteValue = currentQuoteAssetValue.sub(
currentQuoteLiabilityValue
);
const currentSpotMarketAssetValue = this.getSpotMarketAssetValue(
targetMarketIndex,
undefined,
includeOpenOrders
);
const currentSpotMarketLiabilityValue = this.getSpotMarketLiabilityValue(
targetMarketIndex,
undefined,
undefined,
includeOpenOrders
);
const currentSpotMarketNetValue = currentSpotMarketAssetValue.sub(
currentSpotMarketLiabilityValue
);
let assetValueToAdd = ZERO;
let liabilityValueToAdd = ZERO;
const newQuoteNetValue =
tradeSide == PositionDirection.SHORT
? currentQuoteValue.add(tradeQuoteAmount)
: currentQuoteValue.sub(tradeQuoteAmount);
const newQuoteAssetValue = BN.max(newQuoteNetValue, ZERO);
const newQuoteLiabilityValue = BN.min(newQuoteNetValue, ZERO).abs();
assetValueToAdd = assetValueToAdd.add(
newQuoteAssetValue.sub(currentQuoteAssetValue)
);
liabilityValueToAdd = liabilityValueToAdd.add(
newQuoteLiabilityValue.sub(currentQuoteLiabilityValue)
);
const newSpotMarketNetValue =
tradeSide == PositionDirection.LONG
? currentSpotMarketNetValue.add(tradeQuoteAmount)
: currentSpotMarketNetValue.sub(tradeQuoteAmount);
const newSpotMarketAssetValue = BN.max(newSpotMarketNetValue, ZERO);
const newSpotMarketLiabilityValue = BN.min(
newSpotMarketNetValue,
ZERO
).abs();
assetValueToAdd = assetValueToAdd.add(
newSpotMarketAssetValue.sub(currentSpotMarketAssetValue)
);
liabilityValueToAdd = liabilityValueToAdd.add(
newSpotMarketLiabilityValue.sub(currentSpotMarketLiabilityValue)
);
const totalAssetValueAfterTrade = totalAssetValue.add(assetValueToAdd);
const totalSpotLiabilityValueAfterTrade =
spotLiabilityValue.add(liabilityValueToAdd);
const totalLiabilityValueAfterTrade =
totalLiabilityValue.add(liabilityValueToAdd);
const netAssetValueAfterTrade = totalAssetValueAfterTrade.sub(
totalSpotLiabilityValueAfterTrade
);
if (netAssetValueAfterTrade.eq(ZERO)) {
return ZERO;
}
const newLeverage = totalLiabilityValueAfterTrade
.mul(TEN_THOUSAND)
.div(netAssetValueAfterTrade);
return newLeverage;
}
const currentPosition =
this.getPerpPositionWithLPSettle(targetMarketIndex)[0] ||
this.getEmptyPosition(targetMarketIndex);
const perpMarket = this.driftClient.getPerpMarketAccount(targetMarketIndex);
const oracleData = this.getOracleDataForPerpMarket(targetMarketIndex);
let {
// eslint-disable-next-line prefer-const
worstCaseBaseAssetAmount: worstCaseBase,
worstCaseLiabilityValue: currentPositionQuoteAmount,
} = calculateWorstCasePerpLiabilityValue(
currentPosition,
perpMarket,
oracleData.price
);
// current side is short if position base asset amount is negative OR there is no position open but open orders are short
const currentSide =
currentPosition.baseAssetAmount.isNeg() ||
(currentPosition.baseAssetAmount.eq(ZERO) && worstCaseBase.isNeg())
? PositionDirection.SHORT
: PositionDirection.LONG;
if (currentSide === PositionDirection.SHORT)
currentPositionQuoteAmount = currentPositionQuoteAmount.neg();
if (tradeSide === PositionDirection.SHORT)
tradeQuoteAmount = tradeQuoteAmount.neg();
const currentPerpPositionAfterTrade = currentPositionQuoteAmount
.add(tradeQuoteAmount)
.abs();
const totalPositionAfterTradeExcludingTargetMarket =
this.getTotalPerpPositionValueExcludingMarket(
targetMarketIndex,
undefined,
undefined,
includeOpenOrders
);
const totalAssetValue = this.getTotalAssetValue();
const totalPerpPositionLiability = currentPerpPositionAfterTrade
.add(totalPositionAfterTradeExcludingTargetMarket)
.abs();
const totalSpotLiability = this.getSpotMarketLiabilityValue(
undefined,
undefined,
undefined,
includeOpenOrders
);
const totalLiabilitiesAfterTrade =
totalPerpPositionLiability.add(totalSpotLiability);
const netAssetValue = totalAssetValue.sub(totalSpotLiability);
if (netAssetValue.eq(ZERO)) {
return ZERO;
}
const newLeverage = totalLiabilitiesAfterTrade
.mul(TEN_THOUSAND)
.div(netAssetValue);
return newLeverage;
}
public getUserFeeTier(marketType: MarketType, now?: BN) {
const state = this.driftClient.getStateAccount();
let feeTierIndex = 0;
if (isVariant(marketType, 'perp')) {
if (this.isHighLeverageMode()) {
return state.perpFeeStructure.feeTiers[0];
}
const userStatsAccount: UserStatsAccount = this.driftClient
.getUserStats()
.getAccount();
const total30dVolume = getUser30dRollingVolumeEstimate(
userStatsAccount,
now
);
const stakedQuoteAssetAmount = userStatsAccount.ifStakedQuoteAssetAmount;
const volumeTiers = [
new BN(100_000_000).mul(QUOTE_PRECISION),
new BN(50_000_000).mul(QUOTE_PRECISION),
new BN(10_000_000).mul(QUOTE_PRECISION),
new BN(5_000_000).mul(QUOTE_PRECISION),
new BN(1_000_000).mul(QUOTE_PRECISION),
];
const stakedTiers = [
new BN(10000).mul(QUOTE_PRECISION),
new BN(5000).mul(QUOTE_PRECISION),
new BN(2000).mul(QUOTE_PRECISION),
new BN(1000).mul(QUOTE_PRECISION),
new BN(500).mul(QUOTE_PRECISION),
];
for (let i = 0; i < volumeTiers.length; i++) {
if (
total30dVolume.gte(volumeTiers[i]) ||
stakedQuoteAssetAmount.gte(stakedTiers[i])
) {
feeTierIndex = 5 - i;
break;
}
}
return state.perpFeeStructure.feeTiers[feeTierIndex];
}
return state.spotFeeStructure.feeTiers[feeTierIndex];
}
/**
* Calculates how much perp fee will be taken for a given sized trade
* @param quoteAmount
* @returns feeForQuote : Precision QUOTE_PRECISION
*/
public calculateFeeForQuoteAmount(quoteAmount: BN, marketIndex?: number): BN {
if (marketIndex !== undefined) {
const takerFeeMultiplier = this.driftClient.getMarketFees(
MarketType.PERP,
marketIndex,
this
).takerFee;
const feeAmountNum =
BigNum.from(quoteAmount, QUOTE_PRECISION_EXP).toNum() *
takerFeeMultiplier;
return BigNum.fromPrint(feeAmountNum.toString(), QUOTE_PRECISION_EXP).val;
} else {
const feeTier = this.getUserFeeTier(MarketType.PERP);
return quoteAmount
.mul(new BN(feeTier.feeNumerator))
.div(new BN(feeTier.feeDenominator));
}
}
/**
* Calculates a user's max withdrawal amounts for a spot market. If reduceOnly is true,
* it will return the max withdrawal amount without opening a liability for the user
* @param marketIndex
* @returns withdrawalLimit : Precision is the token precision for the chosen SpotMarket
*/
public getWithdrawalLimit(marketIndex: number, reduceOnly?: boolean): BN {
const nowTs = new BN(Math.floor(Date.now() / 1000));
const spotMarket = this.driftClient.getSpotMarketAccount(marketIndex);
// eslint-disable-next-line prefer-const
let { borrowLimit, withdrawLimit } = calculateWithdrawLimit(
spotMarket,
nowTs
);
const freeCollateral = this.getFreeCollateral();
const initialMarginRequirement = this.getInitialMarginRequirement();
const oracleData = this.getOracleDataForSpotMarket(marketIndex);
const precisionIncrease = TEN.pow(new BN(spotMarket.decimals - 6));
const { canBypass, depositAmount: userDepositAmount } =
this.canBypassWithdrawLimits(marketIndex);
if (canBypass) {
withdrawLimit = BN.max(withdrawLimit, userDepositAmount);
}
const assetWeight = calculateAssetWeight(
userDepositAmount,
oracleData.price,
spotMarket,
'Initial'
);
let amountWithdrawable;
if (assetWeight.eq(ZERO)) {
amountWithdrawable = userDepositAmount;
} else if (initialMarginRequirement.eq(ZERO)) {
amountWithdrawable = userDepositAmount;
} else {
amountWithdrawable = divCeil(
divCeil(freeCollateral.mul(MARGIN_PRECISION), assetWeight).mul(
PRICE_PRECISION
),
oracleData.price
).mul(precisionIncrease);
}
const maxWithdrawValue = BN.min(
BN.min(amountWithdrawable, userDepositAmount),
withdrawLimit.abs()
);
if (reduceOnly) {
return BN.max(maxWithdrawValue, ZERO);
} else {
const weightedAssetValue = this.getSpotMarketAssetValue(
marketIndex,
'Initial',
false
);
const freeCollatAfterWithdraw = userDepositAmount.gt(ZERO)
? freeCollateral.sub(weightedAssetValue)
: freeCollateral;
const maxLiabilityAllowed = freeCollatAfterWithdraw
.mul(MARGIN_PRECISION)
.div(new BN(spotMarket.initialLiabilityWeight))
.mul(PRICE_PRECISION)
.div(oracleData.price)
.mul(precisionIncrease);
const maxBorrowValue = BN.min(
maxWithdrawValue.add(maxLiabilityAllowed),
borrowLimit.abs()
);
return BN.max(maxBorrowValue, ZERO);
}
}
public canBypassWithdrawLimits(marketIndex: number): {
canBypass: boolean;
netDeposits: BN;
depositAmount: BN;
maxDepositAmount: BN;
} {
const spotMarket = this.driftClient.getSpotMarketAccount(marketIndex);
const maxDepositAmount = spotMarket.withdrawGuardThreshold.div(new BN(10));
const position = this.getSpotPosition(marketIndex);
const netDeposits = this.getUserAccount().totalDeposits.sub(
this.getUserAccount().totalWithdraws
);
if (!position) {
return {
canBypass: false,
maxDepositAmount,
depositAmount: ZERO,
netDeposits,
};
}
if (isVariant(position.balanceType, 'borrow')) {
return {
canBypass: false,
maxDepositAmount,
netDeposits,
depositAmount: ZERO,
};
}
const depositAmount = getTokenAmount(
position.scaledBalance,
spotMarket,
SpotBalanceType.DEPOSIT
);
if (netDeposits.lt(ZERO)) {
return {
canBypass: false,
maxDepositAmount,
depositAmount,
netDeposits,
};
}
return {
canBypass: depositAmount.lt(maxDepositAmount),
maxDepositAmount,
netDeposits,
depositAmount,
};
}
public canMakeIdle(slot: BN): boolean {
const userAccount = this.getUserAccount();
if (userAccount.idle) {
return false;
}
const { totalAssetValue, totalLiabilityValue } =
this.getSpotMarketAssetAndLiabilityValue();
const equity = totalAssetValue.sub(totalLiabilityValue);
let slotsBeforeIdle: BN;
if (equity.lt(QUOTE_PRECISION.muln(1000))) {
slotsBeforeIdle = new BN(9000); // 1 hour
} else {
slotsBeforeIdle = new BN(1512000); // 1 week
}
const userLastActiveSlot = userAccount.lastActiveSlot;
const slotsSinceLastActive = slot.sub(userLastActiveSlot);
if (slotsSinceLastActive.lt(slotsBeforeIdle)) {
return false;
}
if (this.isBeingLiquidated()) {
return false;
}
for (const perpPosition of userAccount.perpPositions) {
if (!positionIsAvailable(perpPosition)) {
return false;
}
}
for (const spotPosition of userAccount.spotPositions) {
if (
isVariant(spotPosition.balanceType, 'borrow') &&
spotPosition.scaledBalance.gt(ZERO)
) {
return false;
}
if (spotPosition.openOrders !== 0) {
return false;
}
}
for (const order of userAccount.orders) {
if (!isVariant(order.status, 'init')) {
return false;
}
}
return true;
}
public getSafestTiers(): { perpTier: number; spotTier: number } {
let safestPerpTier = 4;
let safestSpotTier = 4;
for (const perpPosition of this.getActivePerpPositions()) {
safestPerpTier = Math.min(
safestPerpTier,
getPerpMarketTierNumber(
this.driftClient.getPerpMarketAccount(perpPosition.marketIndex)
)
);
}
for (const spotPosition of this.getActiveSpotPositions()) {
if (isVariant(spotPosition.balanceType, 'deposit')) {
continue;
}
safestSpotTier = Math.min(
safestSpotTier,
getSpotMarketTierNumber(
this.driftClient.getSpotMarketAccount(spotPosition.marketIndex)
)
);
}
return {
perpTier: safestPerpTier,
spotTier: safestSpotTier,
};
}
public getPerpPositionHealth({
marginCategory,
perpPosition,
oraclePriceData,
quoteOraclePriceData,
}: {
marginCategory: MarginCategory;
perpPosition: PerpPosition;
oraclePriceData?: OraclePriceData;
quoteOraclePriceData?: OraclePriceData;
}): HealthComponent {
const settledLpPosition = this.getPerpPositionWithLPSettle(
perpPosition.marketIndex,
perpPosition
)[0];
const perpMarket = this.driftClient.getPerpMarketAccount(
perpPosition.marketIndex
);
const _oraclePriceData =
oraclePriceData ||
this.driftClient.getOracleDataForPerpMarket(perpMarket.marketIndex);
const oraclePrice = _oraclePriceData.price;
const {
worstCaseBaseAssetAmount: worstCaseBaseAmount,
worstCaseLiabilityValue,
} = calculateWorstCasePerpLiabilityValue(
settledLpPosition,
perpMarket,
oraclePrice
);
const marginRatio = new BN(
calculateMarketMarginRatio(
perpMarket,
worstCaseBaseAmount.abs(),
marginCategory,
this.getUserAccount().maxMarginRatio,
this.isHighLeverageMode()
)
);
const _quoteOraclePriceData =
quoteOraclePriceData ||
this.driftClient.getOracleDataForSpotMarket(QUOTE_SPOT_MARKET_INDEX);
let marginRequirement = worstCaseLiabilityValue
.mul(_quoteOraclePriceData.price)
.div(PRICE_PRECISION)
.mul(marginRatio)
.div(MARGIN_PRECISION);
marginRequirement = marginRequirement.add(
new BN(perpPosition.openOrders).mul(OPEN_ORDER_MARGIN_REQUIREMENT)
);
if (perpPosition.lpShares.gt(ZERO)) {
marginRequirement = marginRequirement.add(
BN.max(
QUOTE_PRECISION,
oraclePrice
.mul(perpMarket.amm.orderStepSize)
.mul(QUOTE_PRECISION)
.div(AMM_RESERVE_PRECISION)
.div(PRICE_PRECISION)
)
);
}
return {
marketIndex: perpMarket.marketIndex,
size: worstCaseBaseAmount,
value: worstCaseLiabilityValue,
weight: marginRatio,
weightedValue: marginRequirement,
};
}
public getHealthComponents({
marginCategory,
}: {
marginCategory: MarginCategory;
}): HealthComponents {
const healthComponents: HealthComponents = {
deposits: [],
borrows: [],
perpPositions: [],
perpPnl: [],
};
for (const perpPosition of this.getActivePerpPositions()) {
const perpMarket = this.driftClient.getPerpMarketAccount(
perpPosition.marketIndex
);
const oraclePriceData = this.driftClient.getOracleDataForPerpMarket(
perpMarket.marketIndex
);
const quoteOraclePriceData = this.driftClient.getOracleDataForSpotMarket(
QUOTE_SPOT_MARKET_INDEX
);
healthComponents.perpPositions.push(
this.getPerpPositionHealth({
marginCategory,
perpPosition,
oraclePriceData,
quoteOraclePriceData,
})
);
const quoteSpotMarket = this.driftClient.getSpotMarketAccount(
perpMarket.quoteSpotMarketIndex
);
const settledPerpPosition = this.getPerpPositionWithLPSettle(
perpPosition.marketIndex,
perpPosition
)[0];
const positionUnrealizedPnl = calculatePositionPNL(
perpMarket,
settledPerpPosition,
true,
oraclePriceData
);
let pnlWeight;
if (positionUnrealizedPnl.gt(ZERO)) {
pnlWeight = calculateUnrealizedAssetWeight(
perpMarket,
quoteSpotMarket,
positionUnrealizedPnl,
marginCategory,
oraclePriceData
);
} else {
pnlWeight = SPOT_MARKET_WEIGHT_PRECISION;
}
const pnlValue = positionUnrealizedPnl
.mul(quoteOraclePriceData.price)
.div(PRICE_PRECISION);
const wegithedPnlValue = pnlValue
.mul(pnlWeight)
.div(SPOT_MARKET_WEIGHT_PRECISION);
healthComponents.perpPnl.push({
marketIndex: perpMarket.marketIndex,
size: positionUnrealizedPnl,
value: pnlValue,
weight: pnlWeight,
weightedValue: wegithedPnlValue,
});
}
let netQuoteValue = ZERO;
for (const spotPosition of this.getActiveSpotPositions()) {
const spotMarketAccount: SpotMarketAccount =
this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
const oraclePriceData = this.getOracleDataForSpotMarket(
spotPosition.marketIndex
);
const strictOraclePrice = new StrictOraclePrice(oraclePriceData.price);
if (spotPosition.marketIndex === QUOTE_SPOT_MARKET_INDEX) {
const tokenAmount = getSignedTokenAmount(
getTokenAmount(
spotPosition.scaledBalance,
spotMarketAccount,
spotPosition.balanceType
),
spotPosition.balanceType
);
netQuoteValue = netQuoteValue.add(tokenAmount);
continue;
}
const {
tokenAmount: worstCaseTokenAmount,
tokenValue: tokenValue,
weight,
weightedTokenValue: weightedTokenValue,
ordersValue: ordersValue,
} = getWorstCaseTokenAmounts(
spotPosition,
spotMarketAccount,
strictOraclePrice,
marginCategory,
this.getUserAccount().maxMarginRatio
);
netQuoteValue = netQuoteValue.add(ordersValue);
const baseAssetValue = tokenValue.abs();
const weightedValue = weightedTokenValue.abs();
if (weightedTokenValue.lt(ZERO)) {
healthComponents.borrows.push({
marketIndex: spotMarketAccount.marketIndex,
size: worstCaseTokenAmount,
value: baseAssetValue,
weight: weight,
weightedValue: weightedValue,
});
} else {
healthComponents.deposits.push({
marketIndex: spotMarketAccount.marketIndex,
size: worstCaseTokenAmount,
value: baseAssetValue,
weight: weight,
weightedValue: weightedValue,
});
}
}
if (!netQuoteValue.eq(ZERO)) {
const spotMarketAccount = this.driftClient.getQuoteSpotMarketAccount();
const oraclePriceData = this.getOracleDataForSpotMarket(
QUOTE_SPOT_MARKET_INDEX
);
const baseAssetValue = getTokenValue(
netQuoteValue,
spotMarketAccount.decimals,
oraclePriceData
);
const { weight, weightedTokenValue } = calculateWeightedTokenValue(
netQuoteValue,
baseAssetValue,
oraclePriceData.price,
spotMarketAccount,
marginCategory,
this.getUserAccount().maxMarginRatio
);
if (netQuoteValue.lt(ZERO)) {
healthComponents.borrows.push({
marketIndex: spotMarketAccount.marketIndex,
size: netQuoteValue,
value: baseAssetValue.abs(),
weight: weight,
weightedValue: weightedTokenValue.abs(),
});
} else {
healthComponents.deposits.push({
marketIndex: spotMarketAccount.marketIndex,
size: netQuoteValue,
value: baseAssetValue,
weight: weight,
weightedValue: weightedTokenValue,
});
}
}
return healthComponents;
}
/**
* Get the total position value, excluding any position coming from the given target market
* @param marketToIgnore
* @returns positionValue : Precision QUOTE_PRECISION
*/
private getTotalPerpPositionValueExcludingMarket(
marketToIgnore: number,
marginCategory?: MarginCategory,
liquidationBuffer?: BN,
includeOpenOrders?: boolean
): BN {
const currentPerpPosition =
this.getPerpPositionWithLPSettle(
marketToIgnore,
undefined,
!!marginCategory
)[0] || this.getEmptyPosition(marketToIgnore);
const oracleData = this.getOracleDataForPerpMarket(marketToIgnore);
let currentPerpPositionValueUSDC = ZERO;
if (currentPerpPosition) {
currentPerpPositionValueUSDC = this.getPerpLiabilityValue(
marketToIgnore,
oracleData,
includeOpenOrders
);
}
return this.getTotalPerpPositionLiability(
marginCategory,
liquidationBuffer,
includeOpenOrders
).sub(currentPerpPositionValueUSDC);
}
private getOracleDataForPerpMarket(marketIndex: number): OraclePriceData {
return this.driftClient.getOracleDataForPerpMarket(marketIndex);
}
private getOracleDataForSpotMarket(marketIndex: number): OraclePriceData {
return this.driftClient.getOracleDataForSpotMarket(marketIndex);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/token/index.ts
|
import { Account, TOKEN_PROGRAM_ID, unpackAccount } from '@solana/spl-token';
import { PublicKey, AccountInfo } from '@solana/web3.js';
export function parseTokenAccount(data: Buffer, pubkey: PublicKey): Account {
// mock AccountInfo so unpackAccount can be used
const accountInfo: AccountInfo<Buffer> = {
data,
owner: TOKEN_PROGRAM_ID,
executable: false,
lamports: 0,
};
return unpackAccount(pubkey, accountInfo, TOKEN_PROGRAM_ID);
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/idl/pyth.json
|
{
"version": "0.1.0",
"name": "pyth",
"instructions": [
{
"name": "initialize",
"accounts": [
{
"name": "price",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "price",
"type": "i64"
},
{
"name": "expo",
"type": "i32"
},
{
"name": "conf",
"type": "u64"
}
]
},
{
"name": "setPrice",
"accounts": [
{
"name": "price",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "price",
"type": "i64"
}
]
},
{
"name": "setPriceInfo",
"accounts": [
{
"name": "price",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "price",
"type": "i64"
},
{
"name": "conf",
"type": "u64"
},
{
"name": "slot",
"type": "u64"
}
]
},
{
"name": "setTwap",
"accounts": [
{
"name": "price",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "twap",
"type": "i64"
}
]
}
],
"types": [
{
"name": "PriceStatus",
"type": {
"kind": "enum",
"variants": [
{
"name": "Unknown"
},
{
"name": "Trading"
},
{
"name": "Halted"
},
{
"name": "Auction"
}
]
}
},
{
"name": "CorpAction",
"type": {
"kind": "enum",
"variants": [
{
"name": "NoCorpAct"
}
]
}
},
{
"name": "PriceType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Unknown"
},
{
"name": "Price"
},
{
"name": "TWAP"
},
{
"name": "Volatility"
}
]
}
}
],
"metadata": {
"address": "gSbePebfvPy7tRqimPoVecS2UsBvYv46ynrzWocc92s"
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/idl/switchboard_on_demand_30.json
|
{
"address": "SBondMDrcV3K4kxZR1HNVT7osZxAHVHgYXL5Ze1oMUv",
"metadata": {
"name": "sb_on_demand",
"version": "0.1.0",
"spec": "0.1.0",
"description": "Created with Anchor"
},
"instructions": [
{
"name": "guardian_quote_verify",
"discriminator": [
168,
36,
93,
156,
157,
150,
148,
45
],
"accounts": [
{
"name": "guardian",
"writable": true
},
{
"name": "oracle",
"writable": true
},
{
"name": "authority",
"signer": true,
"relations": [
"oracle"
]
},
{
"name": "guardian_queue",
"writable": true,
"relations": [
"state"
]
},
{
"name": "state"
},
{
"name": "recent_slothashes",
"address": "SysvarS1otHashes111111111111111111111111111"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "GuardianQuoteVerifyParams"
}
}
}
]
},
{
"name": "guardian_register",
"discriminator": [
159,
76,
53,
117,
219,
29,
116,
135
],
"accounts": [
{
"name": "oracle",
"writable": true
},
{
"name": "state"
},
{
"name": "guardian_queue",
"relations": [
"state"
]
},
{
"name": "authority",
"signer": true,
"relations": [
"state"
]
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "GuardianRegisterParams"
}
}
}
]
},
{
"name": "guardian_unregister",
"discriminator": [
215,
19,
61,
120,
155,
224,
120,
60
],
"accounts": [
{
"name": "oracle",
"writable": true
},
{
"name": "state"
},
{
"name": "guardian_queue",
"writable": true,
"relations": [
"state"
]
},
{
"name": "authority",
"signer": true,
"relations": [
"state"
]
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "GuardianUnregisterParams"
}
}
}
]
},
{
"name": "oracle_heartbeat",
"discriminator": [
10,
175,
217,
130,
111,
35,
117,
54
],
"accounts": [
{
"name": "oracle",
"writable": true
},
{
"name": "oracle_stats",
"writable": true,
"pda": {
"seeds": [
{
"kind": "const",
"value": [
79,
114,
97,
99,
108,
101,
83,
116,
97,
116,
115
]
},
{
"kind": "account",
"path": "oracle"
}
]
}
},
{
"name": "oracle_signer",
"signer": true
},
{
"name": "queue",
"writable": true,
"relations": [
"oracle",
"gc_node"
]
},
{
"name": "gc_node",
"writable": true
},
{
"name": "program_state",
"writable": true
},
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
},
{
"name": "token_program",
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
},
{
"name": "native_mint",
"address": "So11111111111111111111111111111111111111112"
},
{
"name": "queue_escrow",
"writable": true
},
{
"name": "stake_program",
"address": "SBSTk6t52R89MmCdD739Rdd97HdbTQUFHe41vCX7pTt",
"relations": [
"program_state"
]
},
{
"name": "delegation_pool",
"writable": true
},
{
"name": "delegation_group",
"writable": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "OracleHeartbeatParams"
}
}
}
]
},
{
"name": "oracle_init",
"discriminator": [
21,
158,
66,
65,
60,
221,
148,
61
],
"accounts": [
{
"name": "oracle",
"writable": true,
"signer": true
},
{
"name": "oracle_stats",
"writable": true,
"pda": {
"seeds": [
{
"kind": "const",
"value": [
79,
114,
97,
99,
108,
101,
83,
116,
97,
116,
115
]
},
{
"kind": "account",
"path": "oracle"
}
]
}
},
{
"name": "program_state",
"writable": true
},
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
},
{
"name": "token_program",
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
},
{
"name": "lut_signer"
},
{
"name": "lut",
"writable": true
},
{
"name": "address_lookup_table_program",
"address": "AddressLookupTab1e1111111111111111111111111"
},
{
"name": "stake_program",
"relations": [
"program_state"
]
},
{
"name": "stake_pool",
"relations": [
"program_state"
]
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "OracleInitParams"
}
}
}
]
},
{
"name": "oracle_set_configs",
"discriminator": [
129,
111,
223,
4,
191,
188,
70,
180
],
"accounts": [
{
"name": "oracle"
},
{
"name": "authority",
"signer": true,
"relations": [
"oracle"
]
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "OracleSetConfigsParams"
}
}
}
]
},
{
"name": "oracle_update_delegation",
"discriminator": [
46,
198,
113,
223,
160,
189,
118,
90
],
"accounts": [
{
"name": "oracle",
"writable": true
},
{
"name": "oracle_stats",
"pda": {
"seeds": [
{
"kind": "const",
"value": [
79,
114,
97,
99,
108,
101,
83,
116,
97,
116,
115
]
},
{
"kind": "account",
"path": "oracle"
}
]
}
},
{
"name": "queue",
"relations": [
"oracle"
]
},
{
"name": "authority",
"signer": true
},
{
"name": "program_state",
"writable": true
},
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
},
{
"name": "token_program",
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
},
{
"name": "delegation_pool",
"writable": true
},
{
"name": "lut_signer"
},
{
"name": "lut",
"writable": true
},
{
"name": "address_lookup_table_program",
"address": "AddressLookupTab1e1111111111111111111111111"
},
{
"name": "switch_mint"
},
{
"name": "native_mint",
"address": "So11111111111111111111111111111111111111112"
},
{
"name": "wsol_vault",
"writable": true
},
{
"name": "switch_vault",
"writable": true
},
{
"name": "stake_program",
"relations": [
"program_state"
]
},
{
"name": "stake_pool"
},
{
"name": "delegation_group"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "OracleUpdateDelegationParams"
}
}
}
]
},
{
"name": "permission_set",
"discriminator": [
211,
122,
185,
120,
129,
182,
55,
103
],
"accounts": [
{
"name": "authority",
"signer": true
},
{
"name": "granter"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "PermissionSetParams"
}
}
}
]
},
{
"name": "pull_feed_close",
"discriminator": [
19,
134,
50,
142,
177,
215,
196,
83
],
"accounts": [
{
"name": "pull_feed",
"writable": true
},
{
"name": "reward_escrow",
"writable": true
},
{
"name": "lut",
"writable": true
},
{
"name": "lut_signer"
},
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "state"
},
{
"name": "authority",
"writable": true,
"signer": true,
"relations": [
"pull_feed"
]
},
{
"name": "token_program",
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
},
{
"name": "associated_token_program",
"address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
},
{
"name": "address_lookup_table_program",
"address": "AddressLookupTab1e1111111111111111111111111"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "PullFeedCloseParams"
}
}
}
]
},
{
"name": "pull_feed_init",
"discriminator": [
198,
130,
53,
198,
235,
61,
143,
40
],
"accounts": [
{
"name": "pull_feed",
"writable": true,
"signer": true
},
{
"name": "queue"
},
{
"name": "authority"
},
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
},
{
"name": "program_state"
},
{
"name": "reward_escrow",
"writable": true,
"pda": {
"seeds": [
{
"kind": "account",
"path": "pull_feed"
},
{
"kind": "const",
"value": [
6,
221,
246,
225,
215,
101,
161,
147,
217,
203,
225,
70,
206,
235,
121,
172,
28,
180,
133,
237,
95,
91,
55,
145,
58,
140,
245,
133,
126,
255,
0,
169
]
},
{
"kind": "account",
"path": "wrapped_sol_mint"
}
],
"program": {
"kind": "const",
"value": [
140,
151,
37,
143,
78,
36,
137,
241,
187,
61,
16,
41,
20,
142,
13,
131,
11,
90,
19,
153,
218,
255,
16,
132,
4,
142,
123,
216,
219,
233,
248,
89
]
}
}
},
{
"name": "token_program",
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
},
{
"name": "associated_token_program",
"address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
},
{
"name": "wrapped_sol_mint",
"address": "So11111111111111111111111111111111111111112"
},
{
"name": "lut_signer"
},
{
"name": "lut",
"writable": true
},
{
"name": "address_lookup_table_program",
"address": "AddressLookupTab1e1111111111111111111111111"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "PullFeedInitParams"
}
}
}
]
},
{
"name": "pull_feed_set_configs",
"discriminator": [
217,
45,
11,
246,
64,
26,
82,
168
],
"accounts": [
{
"name": "pull_feed",
"writable": true
},
{
"name": "authority",
"signer": true,
"relations": [
"pull_feed"
]
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "PullFeedSetConfigsParams"
}
}
}
]
},
{
"name": "pull_feed_submit_response",
"discriminator": [
150,
22,
215,
166,
143,
93,
48,
137
],
"accounts": [
{
"name": "feed",
"writable": true
},
{
"name": "queue",
"relations": [
"feed"
]
},
{
"name": "program_state"
},
{
"name": "recent_slothashes",
"address": "SysvarS1otHashes111111111111111111111111111"
},
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
},
{
"name": "reward_vault",
"writable": true
},
{
"name": "token_program",
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
},
{
"name": "token_mint",
"address": "So11111111111111111111111111111111111111112"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "PullFeedSubmitResponseParams"
}
}
}
]
},
{
"name": "pull_feed_submit_response_many",
"discriminator": [
47,
156,
45,
25,
200,
71,
37,
215
],
"accounts": [
{
"name": "queue"
},
{
"name": "program_state"
},
{
"name": "recent_slothashes",
"address": "SysvarS1otHashes111111111111111111111111111"
},
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
},
{
"name": "reward_vault",
"writable": true
},
{
"name": "token_program",
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
},
{
"name": "token_mint",
"address": "So11111111111111111111111111111111111111112"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "PullFeedSubmitResponseManyParams"
}
}
}
]
},
{
"name": "queue_add_mr_enclave",
"discriminator": [
199,
255,
81,
50,
60,
133,
171,
138
],
"accounts": [
{
"name": "queue",
"writable": true
},
{
"name": "authority",
"signer": true
},
{
"name": "program_authority"
},
{
"name": "state"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "QueueAddMrEnclaveParams"
}
}
}
]
},
{
"name": "queue_allow_subsidies",
"discriminator": [
94,
203,
82,
157,
188,
138,
202,
108
],
"accounts": [
{
"name": "queue",
"writable": true
},
{
"name": "authority",
"signer": true,
"relations": [
"state"
]
},
{
"name": "state",
"writable": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "QueueAllowSubsidiesParams"
}
}
}
]
},
{
"name": "queue_garbage_collect",
"discriminator": [
187,
208,
104,
247,
16,
91,
96,
98
],
"accounts": [
{
"name": "queue",
"writable": true
},
{
"name": "oracle",
"writable": true
},
{
"name": "authority",
"signer": true
},
{
"name": "state"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "QueueGarbageCollectParams"
}
}
}
]
},
{
"name": "queue_init",
"discriminator": [
144,
18,
99,
145,
133,
27,
207,
13
],
"accounts": [
{
"name": "queue",
"writable": true,
"signer": true
},
{
"name": "queue_escrow",
"writable": true,
"pda": {
"seeds": [
{
"kind": "account",
"path": "queue"
},
{
"kind": "const",
"value": [
6,
221,
246,
225,
215,
101,
161,
147,
217,
203,
225,
70,
206,
235,
121,
172,
28,
180,
133,
237,
95,
91,
55,
145,
58,
140,
245,
133,
126,
255,
0,
169
]
},
{
"kind": "account",
"path": "native_mint"
}
],
"program": {
"kind": "const",
"value": [
140,
151,
37,
143,
78,
36,
137,
241,
187,
61,
16,
41,
20,
142,
13,
131,
11,
90,
19,
153,
218,
255,
16,
132,
4,
142,
123,
216,
219,
233,
248,
89
]
}
}
},
{
"name": "authority"
},
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
},
{
"name": "token_program",
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
},
{
"name": "native_mint",
"address": "So11111111111111111111111111111111111111112"
},
{
"name": "program_state"
},
{
"name": "lut_signer",
"writable": true
},
{
"name": "lut",
"writable": true
},
{
"name": "address_lookup_table_program",
"address": "AddressLookupTab1e1111111111111111111111111"
},
{
"name": "associated_token_program",
"address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "QueueInitParams"
}
}
}
]
},
{
"name": "queue_init_delegation_group",
"discriminator": [
239,
146,
75,
158,
20,
166,
159,
14
],
"accounts": [
{
"name": "queue",
"writable": true
},
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
},
{
"name": "program_state"
},
{
"name": "lut_signer"
},
{
"name": "lut",
"writable": true
},
{
"name": "address_lookup_table_program",
"address": "AddressLookupTab1e1111111111111111111111111"
},
{
"name": "delegation_group",
"writable": true
},
{
"name": "stake_program",
"relations": [
"program_state"
]
},
{
"name": "stake_pool"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "QueueInitDelegationGroupParams"
}
}
}
]
},
{
"name": "queue_remove_mr_enclave",
"discriminator": [
3,
64,
135,
33,
190,
133,
68,
252
],
"accounts": [
{
"name": "queue",
"writable": true
},
{
"name": "authority",
"signer": true
},
{
"name": "program_authority"
},
{
"name": "state"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "QueueRemoveMrEnclaveParams"
}
}
}
]
},
{
"name": "queue_set_configs",
"discriminator": [
54,
183,
243,
199,
49,
103,
142,
48
],
"accounts": [
{
"name": "queue",
"writable": true
},
{
"name": "authority",
"signer": true
},
{
"name": "state"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "QueueSetConfigsParams"
}
}
}
]
},
{
"name": "randomness_commit",
"discriminator": [
52,
170,
152,
201,
179,
133,
242,
141
],
"accounts": [
{
"name": "randomness",
"writable": true
},
{
"name": "queue",
"relations": [
"randomness",
"oracle"
]
},
{
"name": "oracle",
"writable": true
},
{
"name": "recent_slothashes",
"address": "SysvarS1otHashes111111111111111111111111111"
},
{
"name": "authority",
"signer": true,
"relations": [
"randomness"
]
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "RandomnessCommitParams"
}
}
}
]
},
{
"name": "randomness_init",
"discriminator": [
9,
9,
204,
33,
50,
116,
113,
15
],
"accounts": [
{
"name": "randomness",
"writable": true,
"signer": true
},
{
"name": "reward_escrow",
"writable": true,
"pda": {
"seeds": [
{
"kind": "account",
"path": "randomness"
},
{
"kind": "const",
"value": [
6,
221,
246,
225,
215,
101,
161,
147,
217,
203,
225,
70,
206,
235,
121,
172,
28,
180,
133,
237,
95,
91,
55,
145,
58,
140,
245,
133,
126,
255,
0,
169
]
},
{
"kind": "account",
"path": "wrapped_sol_mint"
}
],
"program": {
"kind": "const",
"value": [
140,
151,
37,
143,
78,
36,
137,
241,
187,
61,
16,
41,
20,
142,
13,
131,
11,
90,
19,
153,
218,
255,
16,
132,
4,
142,
123,
216,
219,
233,
248,
89
]
}
}
},
{
"name": "authority",
"signer": true
},
{
"name": "queue",
"writable": true
},
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
},
{
"name": "token_program",
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
},
{
"name": "associated_token_program",
"address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
},
{
"name": "wrapped_sol_mint",
"address": "So11111111111111111111111111111111111111112"
},
{
"name": "program_state"
},
{
"name": "lut_signer"
},
{
"name": "lut",
"writable": true
},
{
"name": "address_lookup_table_program",
"address": "AddressLookupTab1e1111111111111111111111111"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "RandomnessInitParams"
}
}
}
]
},
{
"name": "randomness_reveal",
"discriminator": [
197,
181,
187,
10,
30,
58,
20,
73
],
"accounts": [
{
"name": "randomness",
"writable": true
},
{
"name": "oracle",
"relations": [
"randomness"
]
},
{
"name": "queue",
"relations": [
"oracle"
]
},
{
"name": "stats",
"writable": true,
"pda": {
"seeds": [
{
"kind": "const",
"value": [
79,
114,
97,
99,
108,
101,
82,
97,
110,
100,
111,
109,
110,
101,
115,
115,
83,
116,
97,
116,
115
]
},
{
"kind": "account",
"path": "oracle"
}
]
}
},
{
"name": "authority",
"signer": true,
"relations": [
"randomness"
]
},
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "recent_slothashes",
"address": "SysvarS1otHashes111111111111111111111111111"
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
},
{
"name": "reward_escrow",
"writable": true
},
{
"name": "token_program",
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
},
{
"name": "wrapped_sol_mint",
"address": "So11111111111111111111111111111111111111112"
},
{
"name": "program_state"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "RandomnessRevealParams"
}
}
}
]
},
{
"name": "state_init",
"discriminator": [
103,
241,
106,
190,
217,
153,
87,
105
],
"accounts": [
{
"name": "state",
"writable": true,
"pda": {
"seeds": [
{
"kind": "const",
"value": [
83,
84,
65,
84,
69
]
}
]
}
},
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "StateInitParams"
}
}
}
]
},
{
"name": "state_set_configs",
"discriminator": [
40,
98,
76,
37,
206,
9,
47,
144
],
"accounts": [
{
"name": "state",
"writable": true
},
{
"name": "authority",
"signer": true,
"relations": [
"state"
]
},
{
"name": "queue",
"writable": true
},
{
"name": "payer",
"writable": true,
"signer": true
},
{
"name": "system_program",
"address": "11111111111111111111111111111111"
}
],
"args": [
{
"name": "params",
"type": {
"defined": {
"name": "StateSetConfigsParams"
}
}
}
]
}
],
"accounts": [
{
"name": "OracleAccountData",
"discriminator": [
128,
30,
16,
241,
170,
73,
55,
54
]
},
{
"name": "OracleStatsAccountData",
"discriminator": [
180,
157,
178,
234,
240,
27,
152,
179
]
},
{
"name": "PullFeedAccountData",
"discriminator": [
196,
27,
108,
196,
10,
215,
219,
40
]
},
{
"name": "QueueAccountData",
"discriminator": [
217,
194,
55,
127,
184,
83,
138,
1
]
},
{
"name": "RandomnessAccountData",
"discriminator": [
10,
66,
229,
135,
220,
239,
217,
114
]
},
{
"name": "State",
"discriminator": [
216,
146,
107,
94,
104,
75,
182,
177
]
}
],
"events": [
{
"name": "CostWhitelistEvent",
"discriminator": [
56,
107,
191,
127,
116,
6,
138,
149
]
},
{
"name": "GarbageCollectionEvent",
"discriminator": [
232,
235,
2,
188,
8,
143,
145,
237
]
},
{
"name": "GuardianQuoteVerifyEvent",
"discriminator": [
31,
37,
39,
6,
214,
186,
33,
115
]
},
{
"name": "OracleHeartbeatEvent",
"discriminator": [
52,
29,
166,
2,
94,
7,
188,
13
]
},
{
"name": "OracleInitEvent",
"discriminator": [
89,
193,
219,
200,
1,
83,
167,
24
]
},
{
"name": "OracleQuoteOverrideEvent",
"discriminator": [
78,
204,
191,
210,
164,
196,
244,
65
]
},
{
"name": "OracleQuoteRotateEvent",
"discriminator": [
26,
189,
196,
192,
225,
127,
26,
228
]
},
{
"name": "OracleQuoteVerifyRequestEvent",
"discriminator": [
203,
209,
79,
0,
20,
71,
226,
202
]
},
{
"name": "PermissionSetEvent",
"discriminator": [
148,
86,
123,
0,
102,
20,
119,
206
]
},
{
"name": "PullFeedErrorValueEvent",
"discriminator": [
225,
80,
192,
95,
14,
12,
83,
192
]
},
{
"name": "PullFeedValueEvents",
"discriminator": [
86,
7,
231,
28,
122,
161,
117,
69
]
},
{
"name": "QueueAddMrEnclaveEvent",
"discriminator": [
170,
186,
175,
38,
216,
51,
69,
175
]
},
{
"name": "QueueInitEvent",
"discriminator": [
44,
137,
99,
227,
107,
8,
30,
105
]
},
{
"name": "QueueRemoveMrEnclaveEvent",
"discriminator": [
4,
105,
196,
60,
84,
122,
203,
196
]
},
{
"name": "RandomnessCommitEvent",
"discriminator": [
88,
60,
172,
90,
112,
10,
206,
147
]
}
],
"errors": [
{
"code": 6000,
"name": "GenericError"
},
{
"code": 6001,
"name": "InvalidQuote"
},
{
"code": 6002,
"name": "InsufficientQueue"
},
{
"code": 6003,
"name": "QueueFull"
},
{
"code": 6004,
"name": "InvalidEnclaveSigner"
},
{
"code": 6005,
"name": "InvalidSigner"
},
{
"code": 6006,
"name": "MrEnclaveAlreadyExists"
},
{
"code": 6007,
"name": "MrEnclaveAtCapacity"
},
{
"code": 6008,
"name": "MrEnclaveDoesntExist"
},
{
"code": 6009,
"name": "PermissionDenied"
},
{
"code": 6010,
"name": "InvalidQueue"
},
{
"code": 6011,
"name": "IncorrectMrEnclave"
},
{
"code": 6012,
"name": "InvalidAuthority"
},
{
"code": 6013,
"name": "InvalidMrEnclave"
},
{
"code": 6014,
"name": "InvalidTimestamp"
},
{
"code": 6015,
"name": "InvalidOracleIdx"
},
{
"code": 6016,
"name": "InvalidSecpSignature"
},
{
"code": 6017,
"name": "InvalidGuardianQueue"
},
{
"code": 6018,
"name": "InvalidIndex"
},
{
"code": 6019,
"name": "InvalidOracleQueue"
},
{
"code": 6020,
"name": "InvalidPermission"
},
{
"code": 6021,
"name": "InvalidePermissionedAccount"
},
{
"code": 6022,
"name": "InvalidEpochRotate"
},
{
"code": 6023,
"name": "InvalidEpochFinalize"
},
{
"code": 6024,
"name": "InvalidEscrow"
},
{
"code": 6025,
"name": "IllegalOracle"
},
{
"code": 6026,
"name": "IllegalExecuteAttempt"
},
{
"code": 6027,
"name": "IllegalFeedValue"
},
{
"code": 6028,
"name": "InvalidOracleFeedStats"
},
{
"code": 6029,
"name": "InvalidStateAuthority"
},
{
"code": 6030,
"name": "NotEnoughSamples"
},
{
"code": 6031,
"name": "OracleIsVerified"
},
{
"code": 6032,
"name": "QueueIsEmpty"
},
{
"code": 6033,
"name": "SecpRecoverFailure"
},
{
"code": 6034,
"name": "StaleSample"
},
{
"code": 6035,
"name": "SwitchboardRandomnessTooOld"
},
{
"code": 6036,
"name": "EpochIdMismatch"
},
{
"code": 6037,
"name": "GuardianAlreadyVoted"
},
{
"code": 6038,
"name": "RandomnessNotRequested"
},
{
"code": 6039,
"name": "InvalidSlotNumber"
},
{
"code": 6040,
"name": "RandomnessOracleKeyExpired"
},
{
"code": 6041,
"name": "InvalidAdvisory"
},
{
"code": 6042,
"name": "InvalidOracleStats"
},
{
"code": 6043,
"name": "InvalidStakeProgram"
},
{
"code": 6044,
"name": "InvalidStakePool"
},
{
"code": 6045,
"name": "InvalidDelegationPool"
},
{
"code": 6046,
"name": "UnparsableAccount"
},
{
"code": 6047,
"name": "InvalidInstruction"
},
{
"code": 6048,
"name": "OracleAlreadyVerified"
},
{
"code": 6049,
"name": "GuardianNotVerified"
},
{
"code": 6050,
"name": "InvalidConstraint"
},
{
"code": 6051,
"name": "InvalidDelegationGroup"
},
{
"code": 6052,
"name": "OracleKeyNotFound"
},
{
"code": 6053,
"name": "GuardianReregisterAttempt"
}
],
"types": [
{
"name": "CompactResult",
"serialization": "bytemuck",
"repr": {
"kind": "c"
},
"type": {
"kind": "struct",
"fields": [
{
"name": "std_dev",
"docs": [
"The standard deviation of the submissions needed for quorom size"
],
"type": "f32"
},
{
"name": "mean",
"docs": [
"The mean of the submissions needed for quorom size"
],
"type": "f32"
},
{
"name": "slot",
"docs": [
"The slot at which this value was signed."
],
"type": "u64"
}
]
}
},
{
"name": "CostWhitelistEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "feeds",
"type": {
"vec": "pubkey"
}
},
{
"name": "reward",
"type": "u32"
}
]
}
},
{
"name": "CurrentResult",
"serialization": "bytemuck",
"repr": {
"kind": "c"
},
"type": {
"kind": "struct",
"fields": [
{
"name": "value",
"docs": [
"The median value of the submissions needed for quorom size"
],
"type": "i128"
},
{
"name": "std_dev",
"docs": [
"The standard deviation of the submissions needed for quorom size"
],
"type": "i128"
},
{
"name": "mean",
"docs": [
"The mean of the submissions needed for quorom size"
],
"type": "i128"
},
{
"name": "range",
"docs": [
"The range of the submissions needed for quorom size"
],
"type": "i128"
},
{
"name": "min_value",
"docs": [
"The minimum value of the submissions needed for quorom size"
],
"type": "i128"
},
{
"name": "max_value",
"docs": [
"The maximum value of the submissions needed for quorom size"
],
"type": "i128"
},
{
"name": "num_samples",
"docs": [
"The number of samples used to calculate this result"
],
"type": "u8"
},
{
"name": "submission_idx",
"docs": [
"The index of the submission that was used to calculate this result"
],
"type": "u8"
},
{
"name": "padding1",
"type": {
"array": [
"u8",
6
]
}
},
{
"name": "slot",
"docs": [
"The slot at which this value was signed."
],
"type": "u64"
},
{
"name": "min_slot",
"docs": [
"The slot at which the first considered submission was made"
],
"type": "u64"
},
{
"name": "max_slot",
"docs": [
"The slot at which the last considered submission was made"
],
"type": "u64"
}
]
}
},
{
"name": "GarbageCollectionEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "oracle",
"type": "pubkey"
},
{
"name": "queue",
"type": "pubkey"
}
]
}
},
{
"name": "GuardianQuoteVerifyEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "quote",
"type": "pubkey"
},
{
"name": "queue",
"type": "pubkey"
},
{
"name": "oracle",
"type": "pubkey"
}
]
}
},
{
"name": "GuardianQuoteVerifyParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "timestamp",
"type": "i64"
},
{
"name": "mr_enclave",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "_reserved1",
"type": "u32"
},
{
"name": "ed25519_key",
"type": "pubkey"
},
{
"name": "secp256k1_key",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "slot",
"type": "u64"
},
{
"name": "signature",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "recovery_id",
"type": "u8"
},
{
"name": "advisories",
"type": {
"vec": "u32"
}
}
]
}
},
{
"name": "GuardianRegisterParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "GuardianUnregisterParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "MegaSlotInfo",
"serialization": "bytemuck",
"repr": {
"kind": "c"
},
"type": {
"kind": "struct",
"fields": [
{
"name": "reserved1",
"type": "u64"
},
{
"name": "slot_end",
"type": "u64"
},
{
"name": "perf_goal",
"type": "i64"
},
{
"name": "current_signature_count",
"type": "i64"
}
]
}
},
{
"name": "MultiSubmission",
"type": {
"kind": "struct",
"fields": [
{
"name": "values",
"type": {
"vec": "i128"
}
},
{
"name": "signature",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "recovery_id",
"type": "u8"
}
]
}
},
{
"name": "OracleAccountData",
"serialization": "bytemuck",
"repr": {
"kind": "c"
},
"type": {
"kind": "struct",
"fields": [
{
"name": "enclave",
"docs": [
"Represents the state of the quote verifiers enclave."
],
"type": {
"defined": {
"name": "Quote"
}
}
},
{
"name": "authority",
"docs": [
"The authority of the EnclaveAccount which is permitted to make account changes."
],
"type": "pubkey"
},
{
"name": "queue",
"docs": [
"Queue used for attestation to verify a MRENCLAVE measurement."
],
"type": "pubkey"
},
{
"name": "created_at",
"docs": [
"The unix timestamp when the quote was created."
],
"type": "i64"
},
{
"name": "last_heartbeat",
"docs": [
"The last time the quote heartbeated on-chain."
],
"type": "i64"
},
{
"name": "secp_authority",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "gateway_uri",
"docs": [
"URI location of the verifier's gateway."
],
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "permissions",
"type": "u64"
},
{
"name": "is_on_queue",
"docs": [
"Whether the quote is located on the AttestationQueues buffer."
],
"type": "u8"
},
{
"name": "_padding1",
"type": {
"array": [
"u8",
7
]
}
},
{
"name": "lut_slot",
"type": "u64"
},
{
"name": "last_reward_epoch",
"type": "u64"
},
{
"name": "_ebuf4",
"type": {
"array": [
"u8",
16
]
}
},
{
"name": "_ebuf3",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "_ebuf2",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "_ebuf1",
"type": {
"array": [
"u8",
1024
]
}
}
]
}
},
{
"name": "OracleEpochInfo",
"serialization": "bytemuck",
"repr": {
"kind": "c"
},
"type": {
"kind": "struct",
"fields": [
{
"name": "id",
"type": "u64"
},
{
"name": "reserved1",
"type": "u64"
},
{
"name": "slot_end",
"type": "u64"
},
{
"name": "slash_score",
"type": "u64"
},
{
"name": "reward_score",
"type": "u64"
},
{
"name": "stake_score",
"type": "u64"
}
]
}
},
{
"name": "OracleHeartbeatEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "oracle",
"type": "pubkey"
},
{
"name": "queue",
"type": "pubkey"
}
]
}
},
{
"name": "OracleHeartbeatParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "gateway_uri",
"type": {
"option": {
"array": [
"u8",
64
]
}
}
}
]
}
},
{
"name": "OracleInitEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "oracle",
"type": "pubkey"
}
]
}
},
{
"name": "OracleInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "recent_slot",
"type": "u64"
},
{
"name": "authority",
"type": "pubkey"
},
{
"name": "queue",
"type": "pubkey"
},
{
"name": "secp_authority",
"type": {
"option": {
"array": [
"u8",
64
]
}
}
}
]
}
},
{
"name": "OracleQuoteOverrideEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "oracle",
"type": "pubkey"
},
{
"name": "queue",
"type": "pubkey"
}
]
}
},
{
"name": "OracleQuoteRotateEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "oracle",
"type": "pubkey"
}
]
}
},
{
"name": "OracleQuoteVerifyRequestEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "quote",
"type": "pubkey"
},
{
"name": "oracle",
"type": "pubkey"
}
]
}
},
{
"name": "OracleSetConfigsParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "new_authority",
"type": {
"option": "pubkey"
}
},
{
"name": "new_secp_authority",
"type": {
"option": {
"array": [
"u8",
64
]
}
}
}
]
}
},
{
"name": "OracleStatsAccountData",
"serialization": "bytemuck",
"repr": {
"kind": "c"
},
"type": {
"kind": "struct",
"fields": [
{
"name": "owner",
"type": "pubkey"
},
{
"name": "oracle",
"type": "pubkey"
},
{
"name": "finalized_epoch",
"docs": [
"The last epoch that has completed. cleared after registered with the",
"staking program."
],
"type": {
"defined": {
"name": "OracleEpochInfo"
}
}
},
{
"name": "current_epoch",
"docs": [
"The current epoch info being used by the oracle. for stake. Will moved",
"to finalized_epoch as soon as the epoch is over."
],
"type": {
"defined": {
"name": "OracleEpochInfo"
}
}
},
{
"name": "mega_slot_info",
"type": {
"defined": {
"name": "MegaSlotInfo"
}
}
},
{
"name": "last_transfer_slot",
"type": "u64"
},
{
"name": "bump",
"type": "u8"
},
{
"name": "padding1",
"type": {
"array": [
"u8",
7
]
}
},
{
"name": "_ebuf",
"docs": [
"Reserved."
],
"type": {
"array": [
"u8",
1024
]
}
}
]
}
},
{
"name": "OracleSubmission",
"serialization": "bytemuck",
"repr": {
"kind": "c"
},
"type": {
"kind": "struct",
"fields": [
{
"name": "oracle",
"docs": [
"The public key of the oracle that submitted this value."
],
"type": "pubkey"
},
{
"name": "slot",
"docs": [
"The slot at which this value was signed."
],
"type": "u64"
},
{
"name": "landed_at",
"docs": [
"The slot at which this value was landed on chain."
],
"type": "u64"
},
{
"name": "value",
"docs": [
"The value that was submitted."
],
"type": "i128"
}
]
}
},
{
"name": "OracleUpdateDelegationParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "_reserved1",
"type": "u64"
}
]
}
},
{
"name": "PermissionSetEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "permission",
"type": "pubkey"
}
]
}
},
{
"name": "PermissionSetParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "permission",
"type": "u8"
},
{
"name": "enable",
"type": "bool"
}
]
}
},
{
"name": "PullFeedAccountData",
"docs": [
"A representation of the data in a pull feed account."
],
"serialization": "bytemuck",
"repr": {
"kind": "c"
},
"type": {
"kind": "struct",
"fields": [
{
"name": "submissions",
"docs": [
"The oracle submissions for this feed."
],
"type": {
"array": [
{
"defined": {
"name": "OracleSubmission"
}
},
32
]
}
},
{
"name": "authority",
"docs": [
"The public key of the authority that can update the feed hash that",
"this account will use for registering updates."
],
"type": "pubkey"
},
{
"name": "queue",
"docs": [
"The public key of the queue which oracles must be bound to in order to",
"submit data to this feed."
],
"type": "pubkey"
},
{
"name": "feed_hash",
"docs": [
"SHA-256 hash of the job schema oracles will execute to produce data",
"for this feed."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "initialized_at",
"docs": [
"The slot at which this account was initialized."
],
"type": "i64"
},
{
"name": "permissions",
"type": "u64"
},
{
"name": "max_variance",
"type": "u64"
},
{
"name": "min_responses",
"type": "u32"
},
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "padding1",
"type": {
"array": [
"u8",
2
]
}
},
{
"name": "historical_result_idx",
"type": "u8"
},
{
"name": "min_sample_size",
"type": "u8"
},
{
"name": "last_update_timestamp",
"type": "i64"
},
{
"name": "lut_slot",
"type": "u64"
},
{
"name": "_reserved1",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "result",
"type": {
"defined": {
"name": "CurrentResult"
}
}
},
{
"name": "max_staleness",
"type": "u32"
},
{
"name": "padding2",
"type": {
"array": [
"u8",
12
]
}
},
{
"name": "historical_results",
"type": {
"array": [
{
"defined": {
"name": "CompactResult"
}
},
32
]
}
},
{
"name": "_ebuf4",
"type": {
"array": [
"u8",
8
]
}
},
{
"name": "_ebuf3",
"type": {
"array": [
"u8",
24
]
}
},
{
"name": "_ebuf2",
"type": {
"array": [
"u8",
256
]
}
}
]
}
},
{
"name": "PullFeedCloseParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "PullFeedErrorValueEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "feed",
"type": "pubkey"
},
{
"name": "oracle",
"type": "pubkey"
}
]
}
},
{
"name": "PullFeedInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "feed_hash",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "max_variance",
"type": "u64"
},
{
"name": "min_responses",
"type": "u32"
},
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "recent_slot",
"type": "u64"
},
{
"name": "ipfs_hash",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "min_sample_size",
"type": "u8"
},
{
"name": "max_staleness",
"type": "u32"
}
]
}
},
{
"name": "PullFeedSetConfigsParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "feed_hash",
"type": {
"option": {
"array": [
"u8",
32
]
}
}
},
{
"name": "authority",
"type": {
"option": "pubkey"
}
},
{
"name": "max_variance",
"type": {
"option": "u64"
}
},
{
"name": "min_responses",
"type": {
"option": "u32"
}
},
{
"name": "name",
"type": {
"option": {
"array": [
"u8",
32
]
}
}
},
{
"name": "ipfs_hash",
"type": {
"option": {
"array": [
"u8",
32
]
}
}
},
{
"name": "min_sample_size",
"type": {
"option": "u8"
}
},
{
"name": "max_staleness",
"type": {
"option": "u32"
}
}
]
}
},
{
"name": "PullFeedSubmitResponseManyParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "slot",
"type": "u64"
},
{
"name": "submissions",
"type": {
"vec": {
"defined": {
"name": "MultiSubmission"
}
}
}
}
]
}
},
{
"name": "PullFeedSubmitResponseParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "slot",
"type": "u64"
},
{
"name": "submissions",
"type": {
"vec": {
"defined": {
"name": "Submission"
}
}
}
}
]
}
},
{
"name": "PullFeedValueEvents",
"type": {
"kind": "struct",
"fields": [
{
"name": "feeds",
"type": {
"vec": "pubkey"
}
},
{
"name": "oracles",
"type": {
"vec": "pubkey"
}
},
{
"name": "values",
"type": {
"vec": {
"vec": "i128"
}
}
},
{
"name": "reward",
"type": "u32"
}
]
}
},
{
"name": "QueueAccountData",
"docs": [
"An Queue represents a round-robin queue of oracle oracles who attest on-chain",
"whether a Switchboard Function was executed within an enclave against an expected set of",
"enclave measurements.",
"",
"For an oracle to join the queue, the oracle must first submit their enclave quote on-chain and",
"wait for an existing oracle to attest their quote. If the oracle's quote matches an expected",
"measurement within the queues mr_enclaves config, it is granted permissions and will start",
"being assigned update requests."
],
"serialization": "bytemuck",
"repr": {
"kind": "c"
},
"type": {
"kind": "struct",
"fields": [
{
"name": "authority",
"docs": [
"The address of the authority which is permitted to add/remove allowed enclave measurements."
],
"type": "pubkey"
},
{
"name": "mr_enclaves",
"docs": [
"Allowed enclave measurements."
],
"type": {
"array": [
{
"array": [
"u8",
32
]
},
32
]
}
},
{
"name": "oracle_keys",
"docs": [
"The addresses of the quote oracles who have a valid",
"verification status and have heartbeated on-chain recently."
],
"type": {
"array": [
"pubkey",
128
]
}
},
{
"name": "max_quote_verification_age",
"docs": [
"The maximum allowable time until a EnclaveAccount needs to be re-verified on-chain."
],
"type": "i64"
},
{
"name": "last_heartbeat",
"docs": [
"The unix timestamp when the last quote oracle heartbeated on-chain."
],
"type": "i64"
},
{
"name": "node_timeout",
"type": "i64"
},
{
"name": "oracle_min_stake",
"docs": [
"The minimum number of lamports a quote oracle needs to lock-up in order to heartbeat and verify other quotes."
],
"type": "u64"
},
{
"name": "allow_authority_override_after",
"type": "i64"
},
{
"name": "mr_enclaves_len",
"docs": [
"The number of allowed enclave measurements."
],
"type": "u32"
},
{
"name": "oracle_keys_len",
"docs": [
"The length of valid quote oracles for the given attestation queue."
],
"type": "u32"
},
{
"name": "reward",
"docs": [
"The reward paid to quote oracles for attesting on-chain."
],
"type": "u32"
},
{
"name": "curr_idx",
"docs": [
"Incrementer used to track the current quote oracle permitted to run any available functions."
],
"type": "u32"
},
{
"name": "gc_idx",
"docs": [
"Incrementer used to garbage collect and remove stale quote oracles."
],
"type": "u32"
},
{
"name": "require_authority_heartbeat_permission",
"type": "u8"
},
{
"name": "require_authority_verify_permission",
"type": "u8"
},
{
"name": "require_usage_permissions",
"type": "u8"
},
{
"name": "signer_bump",
"type": "u8"
},
{
"name": "mint",
"type": "pubkey"
},
{
"name": "lut_slot",
"type": "u64"
},
{
"name": "allow_subsidies",
"type": "u8"
},
{
"name": "_ebuf6",
"docs": [
"Reserved."
],
"type": {
"array": [
"u8",
23
]
}
},
{
"name": "_ebuf5",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "_ebuf4",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "_ebuf3",
"type": {
"array": [
"u8",
128
]
}
},
{
"name": "_ebuf2",
"type": {
"array": [
"u8",
256
]
}
},
{
"name": "_ebuf1",
"type": {
"array": [
"u8",
512
]
}
}
]
}
},
{
"name": "QueueAddMrEnclaveEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "queue",
"type": "pubkey"
},
{
"name": "mr_enclave",
"type": {
"array": [
"u8",
32
]
}
}
]
}
},
{
"name": "QueueAddMrEnclaveParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "mr_enclave",
"type": {
"array": [
"u8",
32
]
}
}
]
}
},
{
"name": "QueueAllowSubsidiesParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "allow_subsidies",
"type": "u8"
}
]
}
},
{
"name": "QueueGarbageCollectParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "idx",
"type": "u32"
}
]
}
},
{
"name": "QueueInitDelegationGroupParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "QueueInitEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "queue",
"type": "pubkey"
}
]
}
},
{
"name": "QueueInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "allow_authority_override_after",
"type": "u32"
},
{
"name": "require_authority_heartbeat_permission",
"type": "bool"
},
{
"name": "require_usage_permissions",
"type": "bool"
},
{
"name": "max_quote_verification_age",
"type": "u32"
},
{
"name": "reward",
"type": "u32"
},
{
"name": "node_timeout",
"type": "u32"
},
{
"name": "recent_slot",
"type": "u64"
}
]
}
},
{
"name": "QueueRemoveMrEnclaveEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "queue",
"type": "pubkey"
},
{
"name": "mr_enclave",
"type": {
"array": [
"u8",
32
]
}
}
]
}
},
{
"name": "QueueRemoveMrEnclaveParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "mr_enclave",
"type": {
"array": [
"u8",
32
]
}
}
]
}
},
{
"name": "QueueSetConfigsParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "authority",
"type": {
"option": "pubkey"
}
},
{
"name": "reward",
"type": {
"option": "u32"
}
},
{
"name": "node_timeout",
"type": {
"option": "i64"
}
}
]
}
},
{
"name": "Quote",
"serialization": "bytemuck",
"repr": {
"kind": "c"
},
"type": {
"kind": "struct",
"fields": [
{
"name": "enclave_signer",
"docs": [
"The address of the signer generated within an enclave."
],
"type": "pubkey"
},
{
"name": "mr_enclave",
"docs": [
"The quotes MRENCLAVE measurement dictating the contents of the secure enclave."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "verification_status",
"docs": [
"The VerificationStatus of the quote."
],
"type": "u8"
},
{
"name": "padding1",
"type": {
"array": [
"u8",
7
]
}
},
{
"name": "verification_timestamp",
"docs": [
"The unix timestamp when the quote was last verified."
],
"type": "i64"
},
{
"name": "valid_until",
"docs": [
"The unix timestamp when the quotes verification status expires."
],
"type": "i64"
},
{
"name": "quote_registry",
"docs": [
"The off-chain registry where the verifiers quote can be located."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "registry_key",
"docs": [
"Key to lookup the buffer data on IPFS or an alternative decentralized storage solution."
],
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "secp256k1_signer",
"docs": [
"The secp256k1 public key of the enclave signer. Derived from the enclave_signer."
],
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "last_ed25519_signer",
"type": "pubkey"
},
{
"name": "last_secp256k1_signer",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "last_rotate_slot",
"type": "u64"
},
{
"name": "guardian_approvers",
"type": {
"array": [
"pubkey",
64
]
}
},
{
"name": "guardian_approvers_len",
"type": "u8"
},
{
"name": "padding2",
"type": {
"array": [
"u8",
7
]
}
},
{
"name": "staging_ed25519_signer",
"type": "pubkey"
},
{
"name": "staging_secp256k1_signer",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "_ebuf4",
"docs": [
"Reserved."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "_ebuf3",
"type": {
"array": [
"u8",
128
]
}
},
{
"name": "_ebuf2",
"type": {
"array": [
"u8",
256
]
}
},
{
"name": "_ebuf1",
"type": {
"array": [
"u8",
512
]
}
}
]
}
},
{
"name": "RandomnessAccountData",
"serialization": "bytemuck",
"repr": {
"kind": "c"
},
"type": {
"kind": "struct",
"fields": [
{
"name": "authority",
"type": "pubkey"
},
{
"name": "queue",
"type": "pubkey"
},
{
"name": "seed_slothash",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "seed_slot",
"type": "u64"
},
{
"name": "oracle",
"type": "pubkey"
},
{
"name": "reveal_slot",
"type": "u64"
},
{
"name": "value",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "lut_slot",
"type": "u64"
},
{
"name": "_ebuf3",
"type": {
"array": [
"u8",
24
]
}
},
{
"name": "_ebuf2",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "_ebuf1",
"type": {
"array": [
"u8",
128
]
}
},
{
"name": "active_secp256k1_signer",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "active_secp256k1_expiration",
"type": "i64"
}
]
}
},
{
"name": "RandomnessCommitEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "randomness_account",
"type": "pubkey"
},
{
"name": "oracle",
"type": "pubkey"
},
{
"name": "slot",
"type": "u64"
},
{
"name": "slothash",
"type": {
"array": [
"u8",
32
]
}
}
]
}
},
{
"name": "RandomnessCommitParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "RandomnessInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "recent_slot",
"type": "u64"
}
]
}
},
{
"name": "RandomnessRevealParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "signature",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "recovery_id",
"type": "u8"
},
{
"name": "value",
"type": {
"array": [
"u8",
32
]
}
}
]
}
},
{
"name": "State",
"serialization": "bytemuck",
"repr": {
"kind": "c"
},
"type": {
"kind": "struct",
"fields": [
{
"name": "bump",
"type": "u8"
},
{
"name": "test_only_disable_mr_enclave_check",
"type": "u8"
},
{
"name": "enable_staking",
"type": "u8"
},
{
"name": "padding1",
"type": {
"array": [
"u8",
5
]
}
},
{
"name": "authority",
"type": "pubkey"
},
{
"name": "guardian_queue",
"type": "pubkey"
},
{
"name": "reserved1",
"type": "u64"
},
{
"name": "epoch_length",
"type": "u64"
},
{
"name": "current_epoch",
"type": {
"defined": {
"name": "StateEpochInfo"
}
}
},
{
"name": "next_epoch",
"type": {
"defined": {
"name": "StateEpochInfo"
}
}
},
{
"name": "finalized_epoch",
"type": {
"defined": {
"name": "StateEpochInfo"
}
}
},
{
"name": "stake_pool",
"type": "pubkey"
},
{
"name": "stake_program",
"type": "pubkey"
},
{
"name": "switch_mint",
"type": "pubkey"
},
{
"name": "sgx_advisories",
"type": {
"array": [
"u16",
32
]
}
},
{
"name": "advisories_len",
"type": "u8"
},
{
"name": "padding2",
"type": "u8"
},
{
"name": "flat_reward_cut_percentage",
"type": "u8"
},
{
"name": "enable_slashing",
"type": "u8"
},
{
"name": "subsidy_amount",
"type": "u32"
},
{
"name": "lut_slot",
"type": "u64"
},
{
"name": "base_reward",
"type": "u32"
},
{
"name": "_ebuf6",
"type": {
"array": [
"u8",
28
]
}
},
{
"name": "_ebuf5",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "_ebuf4",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "_ebuf3",
"type": {
"array": [
"u8",
128
]
}
},
{
"name": "_ebuf2",
"type": {
"array": [
"u8",
512
]
}
},
{
"name": "cost_whitelist",
"docs": [
"Cost whitelist by authority"
],
"type": {
"array": [
"pubkey",
32
]
}
}
]
}
},
{
"name": "StateEpochInfo",
"serialization": "bytemuck",
"repr": {
"kind": "c"
},
"type": {
"kind": "struct",
"fields": [
{
"name": "id",
"type": "u64"
},
{
"name": "_reserved1",
"type": "u64"
},
{
"name": "slot_end",
"type": "u64"
}
]
}
},
{
"name": "StateInitParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "StateSetConfigsParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "new_authority",
"type": "pubkey"
},
{
"name": "test_only_disable_mr_enclave_check",
"type": "u8"
},
{
"name": "stake_pool",
"type": "pubkey"
},
{
"name": "stake_program",
"type": "pubkey"
},
{
"name": "add_advisory",
"type": "u16"
},
{
"name": "rm_advisory",
"type": "u16"
},
{
"name": "epoch_length",
"type": "u32"
},
{
"name": "reset_epochs",
"type": "bool"
},
{
"name": "switch_mint",
"type": "pubkey"
},
{
"name": "enable_staking",
"type": "u8"
},
{
"name": "subsidy_amount",
"type": "u32"
},
{
"name": "base_reward",
"type": "u32"
},
{
"name": "add_cost_wl",
"type": "pubkey"
},
{
"name": "rm_cost_wl",
"type": "pubkey"
}
]
}
},
{
"name": "Submission",
"type": {
"kind": "struct",
"fields": [
{
"name": "value",
"type": "i128"
},
{
"name": "signature",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "recovery_id",
"type": "u8"
},
{
"name": "offset",
"type": "u8"
}
]
}
}
]
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/idl/drift.json
|
{
"version": "2.103.0",
"name": "drift",
"instructions": [
{
"name": "initializeUser",
"accounts": [
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "subAccountId",
"type": "u16"
},
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
}
]
},
{
"name": "initializeUserStats",
"accounts": [
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "initializeRfqUser",
"accounts": [
{
"name": "rfqUser",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "initializeSwiftUserOrders",
"accounts": [
{
"name": "swiftUserOrders",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "user",
"isMut": false,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "numOrders",
"type": "u16"
}
]
},
{
"name": "resizeSwiftUserOrders",
"accounts": [
{
"name": "swiftUserOrders",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": true,
"isSigner": true
},
{
"name": "user",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "numOrders",
"type": "u16"
}
]
},
{
"name": "initializeReferrerName",
"accounts": [
{
"name": "referrerName",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
}
]
},
{
"name": "deposit",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "spotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "userTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "amount",
"type": "u64"
},
{
"name": "reduceOnly",
"type": "bool"
}
]
},
{
"name": "withdraw",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "spotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "userTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "amount",
"type": "u64"
},
{
"name": "reduceOnly",
"type": "bool"
}
]
},
{
"name": "transferDeposit",
"accounts": [
{
"name": "fromUser",
"isMut": true,
"isSigner": false
},
{
"name": "toUser",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarketVault",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "amount",
"type": "u64"
}
]
},
{
"name": "placePerpOrder",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "OrderParams"
}
}
]
},
{
"name": "cancelOrder",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "orderId",
"type": {
"option": "u32"
}
}
]
},
{
"name": "cancelOrderByUserId",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "userOrderId",
"type": "u8"
}
]
},
{
"name": "cancelOrders",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "marketType",
"type": {
"option": {
"defined": "MarketType"
}
}
},
{
"name": "marketIndex",
"type": {
"option": "u16"
}
},
{
"name": "direction",
"type": {
"option": {
"defined": "PositionDirection"
}
}
}
]
},
{
"name": "cancelOrdersByIds",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "orderIds",
"type": {
"vec": "u32"
}
}
]
},
{
"name": "modifyOrder",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "orderId",
"type": {
"option": "u32"
}
},
{
"name": "modifyOrderParams",
"type": {
"defined": "ModifyOrderParams"
}
}
]
},
{
"name": "modifyOrderByUserId",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "userOrderId",
"type": "u8"
},
{
"name": "modifyOrderParams",
"type": {
"defined": "ModifyOrderParams"
}
}
]
},
{
"name": "placeAndTakePerpOrder",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "OrderParams"
}
},
{
"name": "successCondition",
"type": {
"option": "u32"
}
}
]
},
{
"name": "placeAndMakePerpOrder",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "taker",
"isMut": true,
"isSigner": false
},
{
"name": "takerStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "OrderParams"
}
},
{
"name": "takerOrderId",
"type": "u32"
}
]
},
{
"name": "placeAndMakeSwiftPerpOrder",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "taker",
"isMut": true,
"isSigner": false
},
{
"name": "takerStats",
"isMut": true,
"isSigner": false
},
{
"name": "takerSwiftUserOrders",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "OrderParams"
}
},
{
"name": "swiftOrderUuid",
"type": {
"array": [
"u8",
8
]
}
}
]
},
{
"name": "placeSwiftTakerOrder",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "swiftUserOrders",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "ixSysvar",
"isMut": false,
"isSigner": false,
"docs": [
"the supplied Sysvar could be anything else.",
"The Instruction Sysvar has not been implemented",
"in the Anchor framework yet, so this is the safe approach."
]
}
],
"args": [
{
"name": "swiftMessageBytes",
"type": "bytes"
},
{
"name": "swiftOrderParamsMessageBytes",
"type": "bytes"
}
]
},
{
"name": "placeAndMatchRfqOrders",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "ixSysvar",
"isMut": false,
"isSigner": false,
"docs": [
"the supplied Sysvar could be anything else.",
"The Instruction Sysvar has not been implemented",
"in the Anchor framework yet, so this is the safe approach."
]
}
],
"args": [
{
"name": "rfqMatches",
"type": {
"vec": {
"defined": "RFQMatch"
}
}
}
]
},
{
"name": "placeSpotOrder",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "OrderParams"
}
}
]
},
{
"name": "placeAndTakeSpotOrder",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "OrderParams"
}
},
{
"name": "fulfillmentType",
"type": {
"option": {
"defined": "SpotFulfillmentType"
}
}
},
{
"name": "makerOrderId",
"type": {
"option": "u32"
}
}
]
},
{
"name": "placeAndMakeSpotOrder",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "taker",
"isMut": true,
"isSigner": false
},
{
"name": "takerStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "OrderParams"
}
},
{
"name": "takerOrderId",
"type": "u32"
},
{
"name": "fulfillmentType",
"type": {
"option": {
"defined": "SpotFulfillmentType"
}
}
}
]
},
{
"name": "placeOrders",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"vec": {
"defined": "OrderParams"
}
}
}
]
},
{
"name": "beginSwap",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "outSpotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "inSpotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "outTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "inTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "instructions",
"isMut": false,
"isSigner": false,
"docs": [
"Instructions Sysvar for instruction introspection"
]
}
],
"args": [
{
"name": "inMarketIndex",
"type": "u16"
},
{
"name": "outMarketIndex",
"type": "u16"
},
{
"name": "amountIn",
"type": "u64"
}
]
},
{
"name": "endSwap",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "outSpotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "inSpotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "outTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "inTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "instructions",
"isMut": false,
"isSigner": false,
"docs": [
"Instructions Sysvar for instruction introspection"
]
}
],
"args": [
{
"name": "inMarketIndex",
"type": "u16"
},
{
"name": "outMarketIndex",
"type": "u16"
},
{
"name": "limitPrice",
"type": {
"option": "u64"
}
},
{
"name": "reduceOnly",
"type": {
"option": {
"defined": "SwapReduceOnly"
}
}
}
]
},
{
"name": "addPerpLpShares",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "nShares",
"type": "u64"
},
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "removePerpLpShares",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "sharesToBurn",
"type": "u64"
},
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "removePerpLpSharesInExpiringMarket",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "sharesToBurn",
"type": "u64"
},
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "updateUserName",
"accounts": [
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "subAccountId",
"type": "u16"
},
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
}
]
},
{
"name": "updateUserCustomMarginRatio",
"accounts": [
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "subAccountId",
"type": "u16"
},
{
"name": "marginRatio",
"type": "u32"
}
]
},
{
"name": "updateUserMarginTradingEnabled",
"accounts": [
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "subAccountId",
"type": "u16"
},
{
"name": "marginTradingEnabled",
"type": "bool"
}
]
},
{
"name": "updateUserPoolId",
"accounts": [
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "subAccountId",
"type": "u16"
},
{
"name": "poolId",
"type": "u8"
}
]
},
{
"name": "updateUserDelegate",
"accounts": [
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "subAccountId",
"type": "u16"
},
{
"name": "delegate",
"type": "publicKey"
}
]
},
{
"name": "updateUserReduceOnly",
"accounts": [
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "subAccountId",
"type": "u16"
},
{
"name": "reduceOnly",
"type": "bool"
}
]
},
{
"name": "updateUserAdvancedLp",
"accounts": [
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "subAccountId",
"type": "u16"
},
{
"name": "advancedLp",
"type": "bool"
}
]
},
{
"name": "updateUserProtectedMakerOrders",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "protectedMakerModeConfig",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "subAccountId",
"type": "u16"
},
{
"name": "protectedMakerOrders",
"type": "bool"
}
]
},
{
"name": "deleteUser",
"accounts": [
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": []
},
{
"name": "forceDeleteUser",
"accounts": [
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": true,
"isSigner": false
},
{
"name": "keeper",
"isMut": true,
"isSigner": true
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "deleteSwiftUserOrders",
"accounts": [
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "swiftUserOrders",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": []
},
{
"name": "reclaimRent",
"accounts": [
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "rent",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "enableUserHighLeverageMode",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "highLeverageModeConfig",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "subAccountId",
"type": "u16"
}
]
},
{
"name": "fillPerpOrder",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "filler",
"isMut": true,
"isSigner": false
},
{
"name": "fillerStats",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "orderId",
"type": {
"option": "u32"
}
},
{
"name": "makerOrderId",
"type": {
"option": "u32"
}
}
]
},
{
"name": "revertFill",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "filler",
"isMut": true,
"isSigner": false
},
{
"name": "fillerStats",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "fillSpotOrder",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "filler",
"isMut": true,
"isSigner": false
},
{
"name": "fillerStats",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "orderId",
"type": {
"option": "u32"
}
},
{
"name": "fulfillmentType",
"type": {
"option": {
"defined": "SpotFulfillmentType"
}
}
},
{
"name": "makerOrderId",
"type": {
"option": "u32"
}
}
]
},
{
"name": "triggerOrder",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "filler",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "orderId",
"type": "u32"
}
]
},
{
"name": "forceCancelOrders",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "filler",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "updateUserIdle",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "filler",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "logUserBalances",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "user",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "disableUserHighLeverageMode",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "highLeverageModeConfig",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "updateUserFuelBonus",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "updateUserStatsReferrerStatus",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "updateUserOpenOrdersCount",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "filler",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "adminDisableUpdatePerpBidAskTwap",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "disable",
"type": "bool"
}
]
},
{
"name": "settlePnl",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "spotMarketVault",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "settleMultiplePnls",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "spotMarketVault",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndexes",
"type": {
"vec": "u16"
}
},
{
"name": "mode",
"type": {
"defined": "SettlePnlMode"
}
}
]
},
{
"name": "settleFundingPayment",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "settleLp",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "settleExpiredMarket",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "liquidatePerp",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "liquidator",
"isMut": true,
"isSigner": false
},
{
"name": "liquidatorStats",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "liquidatorMaxBaseAssetAmount",
"type": "u64"
},
{
"name": "limitPrice",
"type": {
"option": "u64"
}
}
]
},
{
"name": "liquidatePerpWithFill",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "liquidator",
"isMut": true,
"isSigner": false
},
{
"name": "liquidatorStats",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "liquidateSpot",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "liquidator",
"isMut": true,
"isSigner": false
},
{
"name": "liquidatorStats",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "assetMarketIndex",
"type": "u16"
},
{
"name": "liabilityMarketIndex",
"type": "u16"
},
{
"name": "liquidatorMaxLiabilityTransfer",
"type": "u128"
},
{
"name": "limitPrice",
"type": {
"option": "u64"
}
}
]
},
{
"name": "liquidateBorrowForPerpPnl",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "liquidator",
"isMut": true,
"isSigner": false
},
{
"name": "liquidatorStats",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "perpMarketIndex",
"type": "u16"
},
{
"name": "spotMarketIndex",
"type": "u16"
},
{
"name": "liquidatorMaxLiabilityTransfer",
"type": "u128"
},
{
"name": "limitPrice",
"type": {
"option": "u64"
}
}
]
},
{
"name": "liquidatePerpPnlForDeposit",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "liquidator",
"isMut": true,
"isSigner": false
},
{
"name": "liquidatorStats",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "perpMarketIndex",
"type": "u16"
},
{
"name": "spotMarketIndex",
"type": "u16"
},
{
"name": "liquidatorMaxPnlTransfer",
"type": "u128"
},
{
"name": "limitPrice",
"type": {
"option": "u64"
}
}
]
},
{
"name": "setUserStatusToBeingLiquidated",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": []
},
{
"name": "resolvePerpPnlDeficit",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "spotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "insuranceFundVault",
"isMut": true,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "spotMarketIndex",
"type": "u16"
},
{
"name": "perpMarketIndex",
"type": "u16"
}
]
},
{
"name": "resolvePerpBankruptcy",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "liquidator",
"isMut": true,
"isSigner": false
},
{
"name": "liquidatorStats",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "spotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "insuranceFundVault",
"isMut": true,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "quoteSpotMarketIndex",
"type": "u16"
},
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "resolveSpotBankruptcy",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "liquidator",
"isMut": true,
"isSigner": false
},
{
"name": "liquidatorStats",
"isMut": true,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "spotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "insuranceFundVault",
"isMut": true,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "settleRevenueToInsuranceFund",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "spotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "insuranceFundVault",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "spotMarketIndex",
"type": "u16"
}
]
},
{
"name": "updateFundingRate",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "updatePrelaunchOracle",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": false,
"isSigner": false
},
{
"name": "oracle",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "updatePerpBidAskTwap",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
},
{
"name": "keeperStats",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": []
},
{
"name": "updateSpotMarketCumulativeInterest",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarketVault",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "updateAmms",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "marketIndexes",
"type": {
"array": [
"u16",
5
]
}
}
]
},
{
"name": "updateSpotMarketExpiry",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "expiryTs",
"type": "i64"
}
]
},
{
"name": "updateUserQuoteAssetInsuranceStake",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "insuranceFundStake",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "insuranceFundVault",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "updateUserGovTokenInsuranceStake",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "insuranceFundStake",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "insuranceFundVault",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "updateUserGovTokenInsuranceStakeDevnet",
"accounts": [
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "signer",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "govStakeAmount",
"type": "u64"
}
]
},
{
"name": "initializeInsuranceFundStake",
"accounts": [
{
"name": "spotMarket",
"isMut": false,
"isSigner": false
},
{
"name": "insuranceFundStake",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "addInsuranceFundStake",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "insuranceFundStake",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "spotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "insuranceFundVault",
"isMut": true,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "userTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "amount",
"type": "u64"
}
]
},
{
"name": "requestRemoveInsuranceFundStake",
"accounts": [
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "insuranceFundStake",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "insuranceFundVault",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "amount",
"type": "u64"
}
]
},
{
"name": "cancelRequestRemoveInsuranceFundStake",
"accounts": [
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "insuranceFundStake",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "insuranceFundVault",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "removeInsuranceFundStake",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "insuranceFundStake",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "insuranceFundVault",
"isMut": true,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "userTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "transferProtocolIfShares",
"accounts": [
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "transferConfig",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "insuranceFundStake",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "insuranceFundVault",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "shares",
"type": "u128"
}
]
},
{
"name": "updatePythPullOracle",
"accounts": [
{
"name": "keeper",
"isMut": true,
"isSigner": true
},
{
"name": "pythSolanaReceiver",
"isMut": false,
"isSigner": false
},
{
"name": "encodedVaa",
"isMut": false,
"isSigner": false
},
{
"name": "priceFeed",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "feedId",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "params",
"type": "bytes"
}
]
},
{
"name": "postPythPullOracleUpdateAtomic",
"accounts": [
{
"name": "keeper",
"isMut": true,
"isSigner": true
},
{
"name": "pythSolanaReceiver",
"isMut": false,
"isSigner": false
},
{
"name": "guardianSet",
"isMut": false,
"isSigner": false
},
{
"name": "priceFeed",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "feedId",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "params",
"type": "bytes"
}
]
},
{
"name": "postMultiPythPullOracleUpdatesAtomic",
"accounts": [
{
"name": "keeper",
"isMut": true,
"isSigner": true
},
{
"name": "pythSolanaReceiver",
"isMut": false,
"isSigner": false
},
{
"name": "guardianSet",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": "bytes"
}
]
},
{
"name": "initialize",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "quoteAssetMint",
"isMut": false,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "initializeSpotMarket",
"accounts": [
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "spotMarketMint",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "insuranceFundVault",
"isMut": true,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
},
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "optimalUtilization",
"type": "u32"
},
{
"name": "optimalBorrowRate",
"type": "u32"
},
{
"name": "maxBorrowRate",
"type": "u32"
},
{
"name": "oracleSource",
"type": {
"defined": "OracleSource"
}
},
{
"name": "initialAssetWeight",
"type": "u32"
},
{
"name": "maintenanceAssetWeight",
"type": "u32"
},
{
"name": "initialLiabilityWeight",
"type": "u32"
},
{
"name": "maintenanceLiabilityWeight",
"type": "u32"
},
{
"name": "imfFactor",
"type": "u32"
},
{
"name": "liquidatorFee",
"type": "u32"
},
{
"name": "ifLiquidationFee",
"type": "u32"
},
{
"name": "activeStatus",
"type": "bool"
},
{
"name": "assetTier",
"type": {
"defined": "AssetTier"
}
},
{
"name": "scaleInitialAssetWeightStart",
"type": "u64"
},
{
"name": "withdrawGuardThreshold",
"type": "u64"
},
{
"name": "orderTickSize",
"type": "u64"
},
{
"name": "orderStepSize",
"type": "u64"
},
{
"name": "ifTotalFactor",
"type": "u32"
},
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
}
]
},
{
"name": "deleteInitializedSpotMarket",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "spotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "insuranceFundVault",
"isMut": true,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "initializeSerumFulfillmentConfig",
"accounts": [
{
"name": "baseSpotMarket",
"isMut": false,
"isSigner": false
},
{
"name": "quoteSpotMarket",
"isMut": false,
"isSigner": false
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "serumProgram",
"isMut": false,
"isSigner": false
},
{
"name": "serumMarket",
"isMut": false,
"isSigner": false
},
{
"name": "serumOpenOrders",
"isMut": true,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "serumFulfillmentConfig",
"isMut": true,
"isSigner": false
},
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "updateSerumFulfillmentConfigStatus",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "serumFulfillmentConfig",
"isMut": true,
"isSigner": false
},
{
"name": "admin",
"isMut": true,
"isSigner": true
}
],
"args": [
{
"name": "status",
"type": {
"defined": "SpotFulfillmentConfigStatus"
}
}
]
},
{
"name": "initializeOpenbookV2FulfillmentConfig",
"accounts": [
{
"name": "baseSpotMarket",
"isMut": false,
"isSigner": false
},
{
"name": "quoteSpotMarket",
"isMut": false,
"isSigner": false
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "openbookV2Program",
"isMut": false,
"isSigner": false
},
{
"name": "openbookV2Market",
"isMut": false,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "openbookV2FulfillmentConfig",
"isMut": true,
"isSigner": false
},
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "openbookV2FulfillmentConfigStatus",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "openbookV2FulfillmentConfig",
"isMut": true,
"isSigner": false
},
{
"name": "admin",
"isMut": true,
"isSigner": true
}
],
"args": [
{
"name": "status",
"type": {
"defined": "SpotFulfillmentConfigStatus"
}
}
]
},
{
"name": "initializePhoenixFulfillmentConfig",
"accounts": [
{
"name": "baseSpotMarket",
"isMut": false,
"isSigner": false
},
{
"name": "quoteSpotMarket",
"isMut": false,
"isSigner": false
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "phoenixProgram",
"isMut": false,
"isSigner": false
},
{
"name": "phoenixMarket",
"isMut": false,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "phoenixFulfillmentConfig",
"isMut": true,
"isSigner": false
},
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "phoenixFulfillmentConfigStatus",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "phoenixFulfillmentConfig",
"isMut": true,
"isSigner": false
},
{
"name": "admin",
"isMut": true,
"isSigner": true
}
],
"args": [
{
"name": "status",
"type": {
"defined": "SpotFulfillmentConfigStatus"
}
}
]
},
{
"name": "updateSerumVault",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "srmVault",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "initializePerpMarket",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "ammBaseAssetReserve",
"type": "u128"
},
{
"name": "ammQuoteAssetReserve",
"type": "u128"
},
{
"name": "ammPeriodicity",
"type": "i64"
},
{
"name": "ammPegMultiplier",
"type": "u128"
},
{
"name": "oracleSource",
"type": {
"defined": "OracleSource"
}
},
{
"name": "contractTier",
"type": {
"defined": "ContractTier"
}
},
{
"name": "marginRatioInitial",
"type": "u32"
},
{
"name": "marginRatioMaintenance",
"type": "u32"
},
{
"name": "liquidatorFee",
"type": "u32"
},
{
"name": "ifLiquidationFee",
"type": "u32"
},
{
"name": "imfFactor",
"type": "u32"
},
{
"name": "activeStatus",
"type": "bool"
},
{
"name": "baseSpread",
"type": "u32"
},
{
"name": "maxSpread",
"type": "u32"
},
{
"name": "maxOpenInterest",
"type": "u128"
},
{
"name": "maxRevenueWithdrawPerPeriod",
"type": "u64"
},
{
"name": "quoteMaxInsurance",
"type": "u64"
},
{
"name": "orderStepSize",
"type": "u64"
},
{
"name": "orderTickSize",
"type": "u64"
},
{
"name": "minOrderSize",
"type": "u64"
},
{
"name": "concentrationCoefScale",
"type": "u128"
},
{
"name": "curveUpdateIntensity",
"type": "u8"
},
{
"name": "ammJitIntensity",
"type": "u8"
},
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
}
]
},
{
"name": "initializePredictionMarket",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "deleteInitializedPerpMarket",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "marketIndex",
"type": "u16"
}
]
},
{
"name": "moveAmmPrice",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "baseAssetReserve",
"type": "u128"
},
{
"name": "quoteAssetReserve",
"type": "u128"
},
{
"name": "sqrtK",
"type": "u128"
}
]
},
{
"name": "recenterPerpMarketAmm",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "pegMultiplier",
"type": "u128"
},
{
"name": "sqrtK",
"type": "u128"
}
]
},
{
"name": "updatePerpMarketAmmSummaryStats",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": false,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "UpdatePerpMarketSummaryStatsParams"
}
}
]
},
{
"name": "updatePerpMarketExpiry",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "expiryTs",
"type": "i64"
}
]
},
{
"name": "settleExpiredMarketPoolsToRevenuePool",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "depositIntoPerpMarketFeePool",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
},
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "sourceVault",
"isMut": true,
"isSigner": false
},
{
"name": "driftSigner",
"isMut": false,
"isSigner": false
},
{
"name": "quoteSpotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "spotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "amount",
"type": "u64"
}
]
},
{
"name": "depositIntoSpotMarketVault",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "sourceVault",
"isMut": true,
"isSigner": false
},
{
"name": "spotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "amount",
"type": "u64"
}
]
},
{
"name": "depositIntoSpotMarketRevenuePool",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": true,
"isSigner": true
},
{
"name": "spotMarketVault",
"isMut": true,
"isSigner": false
},
{
"name": "userTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "amount",
"type": "u64"
}
]
},
{
"name": "repegAmmCurve",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
},
{
"name": "admin",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "newPegCandidate",
"type": "u128"
}
]
},
{
"name": "updatePerpMarketAmmOracleTwap",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
},
{
"name": "admin",
"isMut": false,
"isSigner": true
}
],
"args": []
},
{
"name": "resetPerpMarketAmmOracleTwap",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
},
{
"name": "admin",
"isMut": false,
"isSigner": true
}
],
"args": []
},
{
"name": "updateK",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "sqrtK",
"type": "u128"
}
]
},
{
"name": "updatePerpMarketMarginRatio",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "marginRatioInitial",
"type": "u32"
},
{
"name": "marginRatioMaintenance",
"type": "u32"
}
]
},
{
"name": "updatePerpMarketHighLeverageMarginRatio",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "marginRatioInitial",
"type": "u16"
},
{
"name": "marginRatioMaintenance",
"type": "u16"
}
]
},
{
"name": "updatePerpMarketFundingPeriod",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "fundingPeriod",
"type": "i64"
}
]
},
{
"name": "updatePerpMarketMaxImbalances",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "unrealizedMaxImbalance",
"type": "u64"
},
{
"name": "maxRevenueWithdrawPerPeriod",
"type": "u64"
},
{
"name": "quoteMaxInsurance",
"type": "u64"
}
]
},
{
"name": "updatePerpMarketLiquidationFee",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "liquidatorFee",
"type": "u32"
},
{
"name": "ifLiquidationFee",
"type": "u32"
}
]
},
{
"name": "updateInsuranceFundUnstakingPeriod",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "insuranceFundUnstakingPeriod",
"type": "i64"
}
]
},
{
"name": "updateSpotMarketPoolId",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "poolId",
"type": "u8"
}
]
},
{
"name": "updateSpotMarketLiquidationFee",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "liquidatorFee",
"type": "u32"
},
{
"name": "ifLiquidationFee",
"type": "u32"
}
]
},
{
"name": "updateWithdrawGuardThreshold",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "withdrawGuardThreshold",
"type": "u64"
}
]
},
{
"name": "updateSpotMarketIfFactor",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "spotMarketIndex",
"type": "u16"
},
{
"name": "userIfFactor",
"type": "u32"
},
{
"name": "totalIfFactor",
"type": "u32"
}
]
},
{
"name": "updateSpotMarketRevenueSettlePeriod",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "revenueSettlePeriod",
"type": "i64"
}
]
},
{
"name": "updateSpotMarketStatus",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "status",
"type": {
"defined": "MarketStatus"
}
}
]
},
{
"name": "updateSpotMarketPausedOperations",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "pausedOperations",
"type": "u8"
}
]
},
{
"name": "updateSpotMarketAssetTier",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "assetTier",
"type": {
"defined": "AssetTier"
}
}
]
},
{
"name": "updateSpotMarketMarginWeights",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "initialAssetWeight",
"type": "u32"
},
{
"name": "maintenanceAssetWeight",
"type": "u32"
},
{
"name": "initialLiabilityWeight",
"type": "u32"
},
{
"name": "maintenanceLiabilityWeight",
"type": "u32"
},
{
"name": "imfFactor",
"type": "u32"
}
]
},
{
"name": "updateSpotMarketBorrowRate",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "optimalUtilization",
"type": "u32"
},
{
"name": "optimalBorrowRate",
"type": "u32"
},
{
"name": "maxBorrowRate",
"type": "u32"
},
{
"name": "minBorrowRate",
"type": {
"option": "u8"
}
}
]
},
{
"name": "updateSpotMarketMaxTokenDeposits",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "maxTokenDeposits",
"type": "u64"
}
]
},
{
"name": "updateSpotMarketMaxTokenBorrows",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "maxTokenBorrowsFraction",
"type": "u16"
}
]
},
{
"name": "updateSpotMarketScaleInitialAssetWeightStart",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "scaleInitialAssetWeightStart",
"type": "u64"
}
]
},
{
"name": "updateSpotMarketOracle",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "oracle",
"type": "publicKey"
},
{
"name": "oracleSource",
"type": {
"defined": "OracleSource"
}
}
]
},
{
"name": "updateSpotMarketStepSizeAndTickSize",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "stepSize",
"type": "u64"
},
{
"name": "tickSize",
"type": "u64"
}
]
},
{
"name": "updateSpotMarketMinOrderSize",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "orderSize",
"type": "u64"
}
]
},
{
"name": "updateSpotMarketOrdersEnabled",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "ordersEnabled",
"type": "bool"
}
]
},
{
"name": "updateSpotMarketIfPausedOperations",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "pausedOperations",
"type": "u8"
}
]
},
{
"name": "updateSpotMarketName",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
}
]
},
{
"name": "updatePerpMarketStatus",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "status",
"type": {
"defined": "MarketStatus"
}
}
]
},
{
"name": "updatePerpMarketPausedOperations",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "pausedOperations",
"type": "u8"
}
]
},
{
"name": "updatePerpMarketContractTier",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "contractTier",
"type": {
"defined": "ContractTier"
}
}
]
},
{
"name": "updatePerpMarketImfFactor",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "imfFactor",
"type": "u32"
},
{
"name": "unrealizedPnlImfFactor",
"type": "u32"
}
]
},
{
"name": "updatePerpMarketUnrealizedAssetWeight",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "unrealizedInitialAssetWeight",
"type": "u32"
},
{
"name": "unrealizedMaintenanceAssetWeight",
"type": "u32"
}
]
},
{
"name": "updatePerpMarketConcentrationCoef",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "concentrationScale",
"type": "u128"
}
]
},
{
"name": "updatePerpMarketCurveUpdateIntensity",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "curveUpdateIntensity",
"type": "u8"
}
]
},
{
"name": "updatePerpMarketTargetBaseAssetAmountPerLp",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "targetBaseAssetAmountPerLp",
"type": "i32"
}
]
},
{
"name": "updatePerpMarketPerLpBase",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "perLpBase",
"type": "i8"
}
]
},
{
"name": "updateLpCooldownTime",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "lpCooldownTime",
"type": "u64"
}
]
},
{
"name": "updatePerpFeeStructure",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "feeStructure",
"type": {
"defined": "FeeStructure"
}
}
]
},
{
"name": "updateSpotFeeStructure",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "feeStructure",
"type": {
"defined": "FeeStructure"
}
}
]
},
{
"name": "updateInitialPctToLiquidate",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "initialPctToLiquidate",
"type": "u16"
}
]
},
{
"name": "updateLiquidationDuration",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "liquidationDuration",
"type": "u8"
}
]
},
{
"name": "updateLiquidationMarginBufferRatio",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "liquidationMarginBufferRatio",
"type": "u32"
}
]
},
{
"name": "updateOracleGuardRails",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "oracleGuardRails",
"type": {
"defined": "OracleGuardRails"
}
}
]
},
{
"name": "updateStateSettlementDuration",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "settlementDuration",
"type": "u16"
}
]
},
{
"name": "updateStateMaxNumberOfSubAccounts",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "maxNumberOfSubAccounts",
"type": "u16"
}
]
},
{
"name": "updateStateMaxInitializeUserFee",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "maxInitializeUserFee",
"type": "u16"
}
]
},
{
"name": "updatePerpMarketOracle",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
},
{
"name": "admin",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "oracle",
"type": "publicKey"
},
{
"name": "oracleSource",
"type": {
"defined": "OracleSource"
}
}
]
},
{
"name": "updatePerpMarketBaseSpread",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "baseSpread",
"type": "u32"
}
]
},
{
"name": "updateAmmJitIntensity",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "ammJitIntensity",
"type": "u8"
}
]
},
{
"name": "updatePerpMarketMaxSpread",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "maxSpread",
"type": "u32"
}
]
},
{
"name": "updatePerpMarketStepSizeAndTickSize",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "stepSize",
"type": "u64"
},
{
"name": "tickSize",
"type": "u64"
}
]
},
{
"name": "updatePerpMarketName",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
}
]
},
{
"name": "updatePerpMarketMinOrderSize",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "orderSize",
"type": "u64"
}
]
},
{
"name": "updatePerpMarketMaxSlippageRatio",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "maxSlippageRatio",
"type": "u16"
}
]
},
{
"name": "updatePerpMarketMaxFillReserveFraction",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "maxFillReserveFraction",
"type": "u16"
}
]
},
{
"name": "updatePerpMarketMaxOpenInterest",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "maxOpenInterest",
"type": "u128"
}
]
},
{
"name": "updatePerpMarketNumberOfUsers",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "numberOfUsers",
"type": {
"option": "u32"
}
},
{
"name": "numberOfUsersWithBase",
"type": {
"option": "u32"
}
}
]
},
{
"name": "updatePerpMarketFeeAdjustment",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "feeAdjustment",
"type": "i16"
}
]
},
{
"name": "updateSpotMarketFeeAdjustment",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "feeAdjustment",
"type": "i16"
}
]
},
{
"name": "updatePerpMarketFuel",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "fuelBoostTaker",
"type": {
"option": "u8"
}
},
{
"name": "fuelBoostMaker",
"type": {
"option": "u8"
}
},
{
"name": "fuelBoostPosition",
"type": {
"option": "u8"
}
}
]
},
{
"name": "updateSpotMarketFuel",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "spotMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "fuelBoostDeposits",
"type": {
"option": "u8"
}
},
{
"name": "fuelBoostBorrows",
"type": {
"option": "u8"
}
},
{
"name": "fuelBoostTaker",
"type": {
"option": "u8"
}
},
{
"name": "fuelBoostMaker",
"type": {
"option": "u8"
}
},
{
"name": "fuelBoostInsurance",
"type": {
"option": "u8"
}
}
]
},
{
"name": "initUserFuel",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "user",
"isMut": true,
"isSigner": false
},
{
"name": "userStats",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "fuelBoostDeposits",
"type": {
"option": "u32"
}
},
{
"name": "fuelBoostBorrows",
"type": {
"option": "u32"
}
},
{
"name": "fuelBoostTaker",
"type": {
"option": "u32"
}
},
{
"name": "fuelBoostMaker",
"type": {
"option": "u32"
}
},
{
"name": "fuelBoostInsurance",
"type": {
"option": "u32"
}
}
]
},
{
"name": "updateAdmin",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "admin",
"type": "publicKey"
}
]
},
{
"name": "updateWhitelistMint",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "whitelistMint",
"type": "publicKey"
}
]
},
{
"name": "updateDiscountMint",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "discountMint",
"type": "publicKey"
}
]
},
{
"name": "updateExchangeStatus",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "exchangeStatus",
"type": "u8"
}
]
},
{
"name": "updatePerpAuctionDuration",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "minPerpAuctionDuration",
"type": "u8"
}
]
},
{
"name": "updateSpotAuctionDuration",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "defaultSpotAuctionDuration",
"type": "u8"
}
]
},
{
"name": "initializeProtocolIfSharesTransferConfig",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "protocolIfSharesTransferConfig",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "updateProtocolIfSharesTransferConfig",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "protocolIfSharesTransferConfig",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "whitelistedSigners",
"type": {
"option": {
"array": [
"publicKey",
4
]
}
}
},
{
"name": "maxTransferPerEpoch",
"type": {
"option": "u128"
}
}
]
},
{
"name": "initializePrelaunchOracle",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "prelaunchOracle",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "PrelaunchOracleParams"
}
}
]
},
{
"name": "updatePrelaunchOracleParams",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "prelaunchOracle",
"isMut": true,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "PrelaunchOracleParams"
}
}
]
},
{
"name": "deletePrelaunchOracle",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "prelaunchOracle",
"isMut": true,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": false,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "perpMarketIndex",
"type": "u16"
}
]
},
{
"name": "initializePythPullOracle",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "pythSolanaReceiver",
"isMut": false,
"isSigner": false
},
{
"name": "priceFeed",
"isMut": true,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "feedId",
"type": {
"array": [
"u8",
32
]
}
}
]
},
{
"name": "initializePythLazerOracle",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "lazerOracle",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "feedId",
"type": "u32"
}
]
},
{
"name": "postPythLazerOracleUpdate",
"accounts": [
{
"name": "keeper",
"isMut": true,
"isSigner": true
},
{
"name": "pythLazerStorage",
"isMut": false,
"isSigner": false
},
{
"name": "ixSysvar",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "pythMessage",
"type": "bytes"
}
]
},
{
"name": "initializeHighLeverageModeConfig",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "highLeverageModeConfig",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "maxUsers",
"type": "u32"
}
]
},
{
"name": "updateHighLeverageModeConfig",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "highLeverageModeConfig",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "maxUsers",
"type": "u32"
},
{
"name": "reduceOnly",
"type": "bool"
}
]
},
{
"name": "initializeProtectedMakerModeConfig",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "protectedMakerModeConfig",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "maxUsers",
"type": "u32"
}
]
},
{
"name": "updateProtectedMakerModeConfig",
"accounts": [
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "protectedMakerModeConfig",
"isMut": true,
"isSigner": false
},
{
"name": "state",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "maxUsers",
"type": "u32"
},
{
"name": "reduceOnly",
"type": "bool"
}
]
}
],
"accounts": [
{
"name": "OpenbookV2FulfillmentConfig",
"type": {
"kind": "struct",
"fields": [
{
"name": "pubkey",
"type": "publicKey"
},
{
"name": "openbookV2ProgramId",
"type": "publicKey"
},
{
"name": "openbookV2Market",
"type": "publicKey"
},
{
"name": "openbookV2MarketAuthority",
"type": "publicKey"
},
{
"name": "openbookV2EventHeap",
"type": "publicKey"
},
{
"name": "openbookV2Bids",
"type": "publicKey"
},
{
"name": "openbookV2Asks",
"type": "publicKey"
},
{
"name": "openbookV2BaseVault",
"type": "publicKey"
},
{
"name": "openbookV2QuoteVault",
"type": "publicKey"
},
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "fulfillmentType",
"type": {
"defined": "SpotFulfillmentType"
}
},
{
"name": "status",
"type": {
"defined": "SpotFulfillmentConfigStatus"
}
},
{
"name": "padding",
"type": {
"array": [
"u8",
4
]
}
}
]
}
},
{
"name": "PhoenixV1FulfillmentConfig",
"type": {
"kind": "struct",
"fields": [
{
"name": "pubkey",
"type": "publicKey"
},
{
"name": "phoenixProgramId",
"type": "publicKey"
},
{
"name": "phoenixLogAuthority",
"type": "publicKey"
},
{
"name": "phoenixMarket",
"type": "publicKey"
},
{
"name": "phoenixBaseVault",
"type": "publicKey"
},
{
"name": "phoenixQuoteVault",
"type": "publicKey"
},
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "fulfillmentType",
"type": {
"defined": "SpotFulfillmentType"
}
},
{
"name": "status",
"type": {
"defined": "SpotFulfillmentConfigStatus"
}
},
{
"name": "padding",
"type": {
"array": [
"u8",
4
]
}
}
]
}
},
{
"name": "SerumV3FulfillmentConfig",
"type": {
"kind": "struct",
"fields": [
{
"name": "pubkey",
"type": "publicKey"
},
{
"name": "serumProgramId",
"type": "publicKey"
},
{
"name": "serumMarket",
"type": "publicKey"
},
{
"name": "serumRequestQueue",
"type": "publicKey"
},
{
"name": "serumEventQueue",
"type": "publicKey"
},
{
"name": "serumBids",
"type": "publicKey"
},
{
"name": "serumAsks",
"type": "publicKey"
},
{
"name": "serumBaseVault",
"type": "publicKey"
},
{
"name": "serumQuoteVault",
"type": "publicKey"
},
{
"name": "serumOpenOrders",
"type": "publicKey"
},
{
"name": "serumSignerNonce",
"type": "u64"
},
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "fulfillmentType",
"type": {
"defined": "SpotFulfillmentType"
}
},
{
"name": "status",
"type": {
"defined": "SpotFulfillmentConfigStatus"
}
},
{
"name": "padding",
"type": {
"array": [
"u8",
4
]
}
}
]
}
},
{
"name": "HighLeverageModeConfig",
"type": {
"kind": "struct",
"fields": [
{
"name": "maxUsers",
"type": "u32"
},
{
"name": "currentUsers",
"type": "u32"
},
{
"name": "reduceOnly",
"type": "u8"
},
{
"name": "padding",
"type": {
"array": [
"u8",
31
]
}
}
]
}
},
{
"name": "InsuranceFundStake",
"type": {
"kind": "struct",
"fields": [
{
"name": "authority",
"type": "publicKey"
},
{
"name": "ifShares",
"type": "u128"
},
{
"name": "lastWithdrawRequestShares",
"type": "u128"
},
{
"name": "ifBase",
"type": "u128"
},
{
"name": "lastValidTs",
"type": "i64"
},
{
"name": "lastWithdrawRequestValue",
"type": "u64"
},
{
"name": "lastWithdrawRequestTs",
"type": "i64"
},
{
"name": "costBasis",
"type": "i64"
},
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "padding",
"type": {
"array": [
"u8",
14
]
}
}
]
}
},
{
"name": "ProtocolIfSharesTransferConfig",
"type": {
"kind": "struct",
"fields": [
{
"name": "whitelistedSigners",
"type": {
"array": [
"publicKey",
4
]
}
},
{
"name": "maxTransferPerEpoch",
"type": "u128"
},
{
"name": "currentEpochTransfer",
"type": "u128"
},
{
"name": "nextEpochTs",
"type": "i64"
},
{
"name": "padding",
"type": {
"array": [
"u128",
8
]
}
}
]
}
},
{
"name": "PrelaunchOracle",
"type": {
"kind": "struct",
"fields": [
{
"name": "price",
"type": "i64"
},
{
"name": "maxPrice",
"type": "i64"
},
{
"name": "confidence",
"type": "u64"
},
{
"name": "lastUpdateSlot",
"type": "u64"
},
{
"name": "ammLastUpdateSlot",
"type": "u64"
},
{
"name": "perpMarketIndex",
"type": "u16"
},
{
"name": "padding",
"type": {
"array": [
"u8",
70
]
}
}
]
}
},
{
"name": "PerpMarket",
"type": {
"kind": "struct",
"fields": [
{
"name": "pubkey",
"docs": [
"The perp market's address. It is a pda of the market index"
],
"type": "publicKey"
},
{
"name": "amm",
"docs": [
"The automated market maker"
],
"type": {
"defined": "AMM"
}
},
{
"name": "pnlPool",
"docs": [
"The market's pnl pool. When users settle negative pnl, the balance increases.",
"When users settle positive pnl, the balance decreases. Can not go negative."
],
"type": {
"defined": "PoolBalance"
}
},
{
"name": "name",
"docs": [
"Encoded display name for the perp market e.g. SOL-PERP"
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "insuranceClaim",
"docs": [
"The perp market's claim on the insurance fund"
],
"type": {
"defined": "InsuranceClaim"
}
},
{
"name": "unrealizedPnlMaxImbalance",
"docs": [
"The max pnl imbalance before positive pnl asset weight is discounted",
"pnl imbalance is the difference between long and short pnl. When it's greater than 0,",
"the amm has negative pnl and the initial asset weight for positive pnl is discounted",
"precision = QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "expiryTs",
"docs": [
"The ts when the market will be expired. Only set if market is in reduce only mode"
],
"type": "i64"
},
{
"name": "expiryPrice",
"docs": [
"The price at which positions will be settled. Only set if market is expired",
"precision = PRICE_PRECISION"
],
"type": "i64"
},
{
"name": "nextFillRecordId",
"docs": [
"Every trade has a fill record id. This is the next id to be used"
],
"type": "u64"
},
{
"name": "nextFundingRateRecordId",
"docs": [
"Every funding rate update has a record id. This is the next id to be used"
],
"type": "u64"
},
{
"name": "nextCurveRecordId",
"docs": [
"Every amm k updated has a record id. This is the next id to be used"
],
"type": "u64"
},
{
"name": "imfFactor",
"docs": [
"The initial margin fraction factor. Used to increase margin ratio for large positions",
"precision: MARGIN_PRECISION"
],
"type": "u32"
},
{
"name": "unrealizedPnlImfFactor",
"docs": [
"The imf factor for unrealized pnl. Used to discount asset weight for large positive pnl",
"precision: MARGIN_PRECISION"
],
"type": "u32"
},
{
"name": "liquidatorFee",
"docs": [
"The fee the liquidator is paid for taking over perp position",
"precision: LIQUIDATOR_FEE_PRECISION"
],
"type": "u32"
},
{
"name": "ifLiquidationFee",
"docs": [
"The fee the insurance fund receives from liquidation",
"precision: LIQUIDATOR_FEE_PRECISION"
],
"type": "u32"
},
{
"name": "marginRatioInitial",
"docs": [
"The margin ratio which determines how much collateral is required to open a position",
"e.g. margin ratio of .1 means a user must have $100 of total collateral to open a $1000 position",
"precision: MARGIN_PRECISION"
],
"type": "u32"
},
{
"name": "marginRatioMaintenance",
"docs": [
"The margin ratio which determines when a user will be liquidated",
"e.g. margin ratio of .05 means a user must have $50 of total collateral to maintain a $1000 position",
"else they will be liquidated",
"precision: MARGIN_PRECISION"
],
"type": "u32"
},
{
"name": "unrealizedPnlInitialAssetWeight",
"docs": [
"The initial asset weight for positive pnl. Negative pnl always has an asset weight of 1",
"precision: SPOT_WEIGHT_PRECISION"
],
"type": "u32"
},
{
"name": "unrealizedPnlMaintenanceAssetWeight",
"docs": [
"The maintenance asset weight for positive pnl. Negative pnl always has an asset weight of 1",
"precision: SPOT_WEIGHT_PRECISION"
],
"type": "u32"
},
{
"name": "numberOfUsersWithBase",
"docs": [
"number of users in a position (base)"
],
"type": "u32"
},
{
"name": "numberOfUsers",
"docs": [
"number of users in a position (pnl) or pnl (quote)"
],
"type": "u32"
},
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "status",
"docs": [
"Whether a market is active, reduce only, expired, etc",
"Affects whether users can open/close positions"
],
"type": {
"defined": "MarketStatus"
}
},
{
"name": "contractType",
"docs": [
"Currently only Perpetual markets are supported"
],
"type": {
"defined": "ContractType"
}
},
{
"name": "contractTier",
"docs": [
"The contract tier determines how much insurance a market can receive, with more speculative markets receiving less insurance",
"It also influences the order perp markets can be liquidated, with less speculative markets being liquidated first"
],
"type": {
"defined": "ContractTier"
}
},
{
"name": "pausedOperations",
"type": "u8"
},
{
"name": "quoteSpotMarketIndex",
"docs": [
"The spot market that pnl is settled in"
],
"type": "u16"
},
{
"name": "feeAdjustment",
"docs": [
"Between -100 and 100, represents what % to increase/decrease the fee by",
"E.g. if this is -50 and the fee is 5bps, the new fee will be 2.5bps",
"if this is 50 and the fee is 5bps, the new fee will be 7.5bps"
],
"type": "i16"
},
{
"name": "fuelBoostPosition",
"docs": [
"fuel multiplier for perp funding",
"precision: 10"
],
"type": "u8"
},
{
"name": "fuelBoostTaker",
"docs": [
"fuel multiplier for perp taker",
"precision: 10"
],
"type": "u8"
},
{
"name": "fuelBoostMaker",
"docs": [
"fuel multiplier for perp maker",
"precision: 10"
],
"type": "u8"
},
{
"name": "poolId",
"type": "u8"
},
{
"name": "highLeverageMarginRatioInitial",
"type": "u16"
},
{
"name": "highLeverageMarginRatioMaintenance",
"type": "u16"
},
{
"name": "padding",
"type": {
"array": [
"u8",
38
]
}
}
]
}
},
{
"name": "ProtectedMakerModeConfig",
"type": {
"kind": "struct",
"fields": [
{
"name": "maxUsers",
"type": "u32"
},
{
"name": "currentUsers",
"type": "u32"
},
{
"name": "reduceOnly",
"type": "u8"
},
{
"name": "padding",
"type": {
"array": [
"u8",
31
]
}
}
]
}
},
{
"name": "PythLazerOracle",
"type": {
"kind": "struct",
"fields": [
{
"name": "price",
"type": "i64"
},
{
"name": "publishTime",
"type": "u64"
},
{
"name": "postedSlot",
"type": "u64"
},
{
"name": "exponent",
"type": "i32"
},
{
"name": "padding",
"type": {
"array": [
"u8",
4
]
}
},
{
"name": "conf",
"type": "u64"
}
]
}
},
{
"name": "RFQUser",
"type": {
"kind": "struct",
"fields": [
{
"name": "userPubkey",
"type": "publicKey"
},
{
"name": "rfqOrderData",
"type": {
"array": [
{
"defined": "RFQOrderId"
},
32
]
}
}
]
}
},
{
"name": "SpotMarket",
"type": {
"kind": "struct",
"fields": [
{
"name": "pubkey",
"docs": [
"The address of the spot market. It is a pda of the market index"
],
"type": "publicKey"
},
{
"name": "oracle",
"docs": [
"The oracle used to price the markets deposits/borrows"
],
"type": "publicKey"
},
{
"name": "mint",
"docs": [
"The token mint of the market"
],
"type": "publicKey"
},
{
"name": "vault",
"docs": [
"The vault used to store the market's deposits",
"The amount in the vault should be equal to or greater than deposits - borrows"
],
"type": "publicKey"
},
{
"name": "name",
"docs": [
"The encoded display name for the market e.g. SOL"
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "historicalOracleData",
"type": {
"defined": "HistoricalOracleData"
}
},
{
"name": "historicalIndexData",
"type": {
"defined": "HistoricalIndexData"
}
},
{
"name": "revenuePool",
"docs": [
"Revenue the protocol has collected in this markets token",
"e.g. for SOL-PERP, funds can be settled in usdc and will flow into the USDC revenue pool"
],
"type": {
"defined": "PoolBalance"
}
},
{
"name": "spotFeePool",
"docs": [
"The fees collected from swaps between this market and the quote market",
"Is settled to the quote markets revenue pool"
],
"type": {
"defined": "PoolBalance"
}
},
{
"name": "insuranceFund",
"docs": [
"Details on the insurance fund covering bankruptcies in this markets token",
"Covers bankruptcies for borrows with this markets token and perps settling in this markets token"
],
"type": {
"defined": "InsuranceFund"
}
},
{
"name": "totalSpotFee",
"docs": [
"The total spot fees collected for this market",
"precision: QUOTE_PRECISION"
],
"type": "u128"
},
{
"name": "depositBalance",
"docs": [
"The sum of the scaled balances for deposits across users and pool balances",
"To convert to the deposit token amount, multiply by the cumulative deposit interest",
"precision: SPOT_BALANCE_PRECISION"
],
"type": "u128"
},
{
"name": "borrowBalance",
"docs": [
"The sum of the scaled balances for borrows across users and pool balances",
"To convert to the borrow token amount, multiply by the cumulative borrow interest",
"precision: SPOT_BALANCE_PRECISION"
],
"type": "u128"
},
{
"name": "cumulativeDepositInterest",
"docs": [
"The cumulative interest earned by depositors",
"Used to calculate the deposit token amount from the deposit balance",
"precision: SPOT_CUMULATIVE_INTEREST_PRECISION"
],
"type": "u128"
},
{
"name": "cumulativeBorrowInterest",
"docs": [
"The cumulative interest earned by borrowers",
"Used to calculate the borrow token amount from the borrow balance",
"precision: SPOT_CUMULATIVE_INTEREST_PRECISION"
],
"type": "u128"
},
{
"name": "totalSocialLoss",
"docs": [
"The total socialized loss from borrows, in the mint's token",
"precision: token mint precision"
],
"type": "u128"
},
{
"name": "totalQuoteSocialLoss",
"docs": [
"The total socialized loss from borrows, in the quote market's token",
"preicision: QUOTE_PRECISION"
],
"type": "u128"
},
{
"name": "withdrawGuardThreshold",
"docs": [
"no withdraw limits/guards when deposits below this threshold",
"precision: token mint precision"
],
"type": "u64"
},
{
"name": "maxTokenDeposits",
"docs": [
"The max amount of token deposits in this market",
"0 if there is no limit",
"precision: token mint precision"
],
"type": "u64"
},
{
"name": "depositTokenTwap",
"docs": [
"24hr average of deposit token amount",
"precision: token mint precision"
],
"type": "u64"
},
{
"name": "borrowTokenTwap",
"docs": [
"24hr average of borrow token amount",
"precision: token mint precision"
],
"type": "u64"
},
{
"name": "utilizationTwap",
"docs": [
"24hr average of utilization",
"which is borrow amount over token amount",
"precision: SPOT_UTILIZATION_PRECISION"
],
"type": "u64"
},
{
"name": "lastInterestTs",
"docs": [
"Last time the cumulative deposit and borrow interest was updated"
],
"type": "u64"
},
{
"name": "lastTwapTs",
"docs": [
"Last time the deposit/borrow/utilization averages were updated"
],
"type": "u64"
},
{
"name": "expiryTs",
"docs": [
"The time the market is set to expire. Only set if market is in reduce only mode"
],
"type": "i64"
},
{
"name": "orderStepSize",
"docs": [
"Spot orders must be a multiple of the step size",
"precision: token mint precision"
],
"type": "u64"
},
{
"name": "orderTickSize",
"docs": [
"Spot orders must be a multiple of the tick size",
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "minOrderSize",
"docs": [
"The minimum order size",
"precision: token mint precision"
],
"type": "u64"
},
{
"name": "maxPositionSize",
"docs": [
"The maximum spot position size",
"if the limit is 0, there is no limit",
"precision: token mint precision"
],
"type": "u64"
},
{
"name": "nextFillRecordId",
"docs": [
"Every spot trade has a fill record id. This is the next id to use"
],
"type": "u64"
},
{
"name": "nextDepositRecordId",
"docs": [
"Every deposit has a deposit record id. This is the next id to use"
],
"type": "u64"
},
{
"name": "initialAssetWeight",
"docs": [
"The initial asset weight used to calculate a deposits contribution to a users initial total collateral",
"e.g. if the asset weight is .8, $100 of deposits contributes $80 to the users initial total collateral",
"precision: SPOT_WEIGHT_PRECISION"
],
"type": "u32"
},
{
"name": "maintenanceAssetWeight",
"docs": [
"The maintenance asset weight used to calculate a deposits contribution to a users maintenance total collateral",
"e.g. if the asset weight is .9, $100 of deposits contributes $90 to the users maintenance total collateral",
"precision: SPOT_WEIGHT_PRECISION"
],
"type": "u32"
},
{
"name": "initialLiabilityWeight",
"docs": [
"The initial liability weight used to calculate a borrows contribution to a users initial margin requirement",
"e.g. if the liability weight is .9, $100 of borrows contributes $90 to the users initial margin requirement",
"precision: SPOT_WEIGHT_PRECISION"
],
"type": "u32"
},
{
"name": "maintenanceLiabilityWeight",
"docs": [
"The maintenance liability weight used to calculate a borrows contribution to a users maintenance margin requirement",
"e.g. if the liability weight is .8, $100 of borrows contributes $80 to the users maintenance margin requirement",
"precision: SPOT_WEIGHT_PRECISION"
],
"type": "u32"
},
{
"name": "imfFactor",
"docs": [
"The initial margin fraction factor. Used to increase liability weight/decrease asset weight for large positions",
"precision: MARGIN_PRECISION"
],
"type": "u32"
},
{
"name": "liquidatorFee",
"docs": [
"The fee the liquidator is paid for taking over borrow/deposit",
"precision: LIQUIDATOR_FEE_PRECISION"
],
"type": "u32"
},
{
"name": "ifLiquidationFee",
"docs": [
"The fee the insurance fund receives from liquidation",
"precision: LIQUIDATOR_FEE_PRECISION"
],
"type": "u32"
},
{
"name": "optimalUtilization",
"docs": [
"The optimal utilization rate for this market.",
"Used to determine the markets borrow rate",
"precision: SPOT_UTILIZATION_PRECISION"
],
"type": "u32"
},
{
"name": "optimalBorrowRate",
"docs": [
"The borrow rate for this market when the market has optimal utilization",
"precision: SPOT_RATE_PRECISION"
],
"type": "u32"
},
{
"name": "maxBorrowRate",
"docs": [
"The borrow rate for this market when the market has 1000 utilization",
"precision: SPOT_RATE_PRECISION"
],
"type": "u32"
},
{
"name": "decimals",
"docs": [
"The market's token mint's decimals. To from decimals to a precision, 10^decimals"
],
"type": "u32"
},
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "ordersEnabled",
"docs": [
"Whether or not spot trading is enabled"
],
"type": "bool"
},
{
"name": "oracleSource",
"type": {
"defined": "OracleSource"
}
},
{
"name": "status",
"type": {
"defined": "MarketStatus"
}
},
{
"name": "assetTier",
"docs": [
"The asset tier affects how a deposit can be used as collateral and the priority for a borrow being liquidated"
],
"type": {
"defined": "AssetTier"
}
},
{
"name": "pausedOperations",
"type": "u8"
},
{
"name": "ifPausedOperations",
"type": "u8"
},
{
"name": "feeAdjustment",
"type": "i16"
},
{
"name": "maxTokenBorrowsFraction",
"docs": [
"What fraction of max_token_deposits",
"disabled when 0, 1 => 1/10000 => .01% of max_token_deposits",
"precision: X/10000"
],
"type": "u16"
},
{
"name": "flashLoanAmount",
"docs": [
"For swaps, the amount of token loaned out in the begin_swap ix",
"precision: token mint precision"
],
"type": "u64"
},
{
"name": "flashLoanInitialTokenAmount",
"docs": [
"For swaps, the amount in the users token account in the begin_swap ix",
"Used to calculate how much of the token left the system in end_swap ix",
"precision: token mint precision"
],
"type": "u64"
},
{
"name": "totalSwapFee",
"docs": [
"The total fees received from swaps",
"precision: token mint precision"
],
"type": "u64"
},
{
"name": "scaleInitialAssetWeightStart",
"docs": [
"When to begin scaling down the initial asset weight",
"disabled when 0",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "minBorrowRate",
"docs": [
"The min borrow rate for this market when the market regardless of utilization",
"1 => 1/200 => .5%",
"precision: X/200"
],
"type": "u8"
},
{
"name": "fuelBoostDeposits",
"docs": [
"fuel multiplier for spot deposits",
"precision: 10"
],
"type": "u8"
},
{
"name": "fuelBoostBorrows",
"docs": [
"fuel multiplier for spot borrows",
"precision: 10"
],
"type": "u8"
},
{
"name": "fuelBoostTaker",
"docs": [
"fuel multiplier for spot taker",
"precision: 10"
],
"type": "u8"
},
{
"name": "fuelBoostMaker",
"docs": [
"fuel multiplier for spot maker",
"precision: 10"
],
"type": "u8"
},
{
"name": "fuelBoostInsurance",
"docs": [
"fuel multiplier for spot insurance stake",
"precision: 10"
],
"type": "u8"
},
{
"name": "tokenProgram",
"type": "u8"
},
{
"name": "poolId",
"type": "u8"
},
{
"name": "padding",
"type": {
"array": [
"u8",
40
]
}
}
]
}
},
{
"name": "State",
"type": {
"kind": "struct",
"fields": [
{
"name": "admin",
"type": "publicKey"
},
{
"name": "whitelistMint",
"type": "publicKey"
},
{
"name": "discountMint",
"type": "publicKey"
},
{
"name": "signer",
"type": "publicKey"
},
{
"name": "srmVault",
"type": "publicKey"
},
{
"name": "perpFeeStructure",
"type": {
"defined": "FeeStructure"
}
},
{
"name": "spotFeeStructure",
"type": {
"defined": "FeeStructure"
}
},
{
"name": "oracleGuardRails",
"type": {
"defined": "OracleGuardRails"
}
},
{
"name": "numberOfAuthorities",
"type": "u64"
},
{
"name": "numberOfSubAccounts",
"type": "u64"
},
{
"name": "lpCooldownTime",
"type": "u64"
},
{
"name": "liquidationMarginBufferRatio",
"type": "u32"
},
{
"name": "settlementDuration",
"type": "u16"
},
{
"name": "numberOfMarkets",
"type": "u16"
},
{
"name": "numberOfSpotMarkets",
"type": "u16"
},
{
"name": "signerNonce",
"type": "u8"
},
{
"name": "minPerpAuctionDuration",
"type": "u8"
},
{
"name": "defaultMarketOrderTimeInForce",
"type": "u8"
},
{
"name": "defaultSpotAuctionDuration",
"type": "u8"
},
{
"name": "exchangeStatus",
"type": "u8"
},
{
"name": "liquidationDuration",
"type": "u8"
},
{
"name": "initialPctToLiquidate",
"type": "u16"
},
{
"name": "maxNumberOfSubAccounts",
"type": "u16"
},
{
"name": "maxInitializeUserFee",
"type": "u16"
},
{
"name": "padding",
"type": {
"array": [
"u8",
10
]
}
}
]
}
},
{
"name": "SwiftUserOrders",
"docs": [
"* This struct is a duplicate of SwiftUserOrdersZeroCopy\n * It is used to give anchor an struct to generate the idl for clients\n * The struct SwiftUserOrdersZeroCopy is used to load the data in efficiently"
],
"type": {
"kind": "struct",
"fields": [
{
"name": "userPubkey",
"type": "publicKey"
},
{
"name": "padding",
"type": "u32"
},
{
"name": "swiftOrderData",
"type": {
"vec": {
"defined": "SwiftOrderId"
}
}
}
]
}
},
{
"name": "User",
"type": {
"kind": "struct",
"fields": [
{
"name": "authority",
"docs": [
"The owner/authority of the account"
],
"type": "publicKey"
},
{
"name": "delegate",
"docs": [
"An addresses that can control the account on the authority's behalf. Has limited power, cant withdraw"
],
"type": "publicKey"
},
{
"name": "name",
"docs": [
"Encoded display name e.g. \"toly\""
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "spotPositions",
"docs": [
"The user's spot positions"
],
"type": {
"array": [
{
"defined": "SpotPosition"
},
8
]
}
},
{
"name": "perpPositions",
"docs": [
"The user's perp positions"
],
"type": {
"array": [
{
"defined": "PerpPosition"
},
8
]
}
},
{
"name": "orders",
"docs": [
"The user's orders"
],
"type": {
"array": [
{
"defined": "Order"
},
32
]
}
},
{
"name": "lastAddPerpLpSharesTs",
"docs": [
"The last time the user added perp lp positions"
],
"type": "i64"
},
{
"name": "totalDeposits",
"docs": [
"The total values of deposits the user has made",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "totalWithdraws",
"docs": [
"The total values of withdrawals the user has made",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "totalSocialLoss",
"docs": [
"The total socialized loss the users has incurred upon the protocol",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "settledPerpPnl",
"docs": [
"Fees (taker fees, maker rebate, referrer reward, filler reward) and pnl for perps",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "cumulativeSpotFees",
"docs": [
"Fees (taker fees, maker rebate, filler reward) for spot",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "cumulativePerpFunding",
"docs": [
"Cumulative funding paid/received for perps",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "liquidationMarginFreed",
"docs": [
"The amount of margin freed during liquidation. Used to force the liquidation to occur over a period of time",
"Defaults to zero when not being liquidated",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "lastActiveSlot",
"docs": [
"The last slot a user was active. Used to determine if a user is idle"
],
"type": "u64"
},
{
"name": "nextOrderId",
"docs": [
"Every user order has an order id. This is the next order id to be used"
],
"type": "u32"
},
{
"name": "maxMarginRatio",
"docs": [
"Custom max initial margin ratio for the user"
],
"type": "u32"
},
{
"name": "nextLiquidationId",
"docs": [
"The next liquidation id to be used for user"
],
"type": "u16"
},
{
"name": "subAccountId",
"docs": [
"The sub account id for this user"
],
"type": "u16"
},
{
"name": "status",
"docs": [
"Whether the user is active, being liquidated or bankrupt"
],
"type": "u8"
},
{
"name": "isMarginTradingEnabled",
"docs": [
"Whether the user has enabled margin trading"
],
"type": "bool"
},
{
"name": "idle",
"docs": [
"User is idle if they haven't interacted with the protocol in 1 week and they have no orders, perp positions or borrows",
"Off-chain keeper bots can ignore users that are idle"
],
"type": "bool"
},
{
"name": "openOrders",
"docs": [
"number of open orders"
],
"type": "u8"
},
{
"name": "hasOpenOrder",
"docs": [
"Whether or not user has open order"
],
"type": "bool"
},
{
"name": "openAuctions",
"docs": [
"number of open orders with auction"
],
"type": "u8"
},
{
"name": "hasOpenAuction",
"docs": [
"Whether or not user has open order with auction"
],
"type": "bool"
},
{
"name": "marginMode",
"type": {
"defined": "MarginMode"
}
},
{
"name": "poolId",
"type": "u8"
},
{
"name": "padding1",
"type": {
"array": [
"u8",
3
]
}
},
{
"name": "lastFuelBonusUpdateTs",
"type": "u32"
},
{
"name": "padding",
"type": {
"array": [
"u8",
12
]
}
}
]
}
},
{
"name": "UserStats",
"type": {
"kind": "struct",
"fields": [
{
"name": "authority",
"docs": [
"The authority for all of a users sub accounts"
],
"type": "publicKey"
},
{
"name": "referrer",
"docs": [
"The address that referred this user"
],
"type": "publicKey"
},
{
"name": "fees",
"docs": [
"Stats on the fees paid by the user"
],
"type": {
"defined": "UserFees"
}
},
{
"name": "nextEpochTs",
"docs": [
"The timestamp of the next epoch",
"Epoch is used to limit referrer rewards earned in single epoch"
],
"type": "i64"
},
{
"name": "makerVolume30d",
"docs": [
"Rolling 30day maker volume for user",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "takerVolume30d",
"docs": [
"Rolling 30day taker volume for user",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "fillerVolume30d",
"docs": [
"Rolling 30day filler volume for user",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "lastMakerVolume30dTs",
"docs": [
"last time the maker volume was updated"
],
"type": "i64"
},
{
"name": "lastTakerVolume30dTs",
"docs": [
"last time the taker volume was updated"
],
"type": "i64"
},
{
"name": "lastFillerVolume30dTs",
"docs": [
"last time the filler volume was updated"
],
"type": "i64"
},
{
"name": "ifStakedQuoteAssetAmount",
"docs": [
"The amount of tokens staked in the quote spot markets if"
],
"type": "u64"
},
{
"name": "numberOfSubAccounts",
"docs": [
"The current number of sub accounts"
],
"type": "u16"
},
{
"name": "numberOfSubAccountsCreated",
"docs": [
"The number of sub accounts created. Can be greater than the number of sub accounts if user",
"has deleted sub accounts"
],
"type": "u16"
},
{
"name": "referrerStatus",
"docs": [
"Flags for referrer status:",
"First bit (LSB): 1 if user is a referrer, 0 otherwise",
"Second bit: 1 if user was referred, 0 otherwise"
],
"type": "u8"
},
{
"name": "disableUpdatePerpBidAskTwap",
"type": "bool"
},
{
"name": "padding1",
"type": {
"array": [
"u8",
2
]
}
},
{
"name": "fuelInsurance",
"docs": [
"accumulated fuel for token amounts of insurance"
],
"type": "u32"
},
{
"name": "fuelDeposits",
"docs": [
"accumulated fuel for notional of deposits"
],
"type": "u32"
},
{
"name": "fuelBorrows",
"docs": [
"accumulate fuel bonus for notional of borrows"
],
"type": "u32"
},
{
"name": "fuelPositions",
"docs": [
"accumulated fuel for perp open interest"
],
"type": "u32"
},
{
"name": "fuelTaker",
"docs": [
"accumulate fuel bonus for taker volume"
],
"type": "u32"
},
{
"name": "fuelMaker",
"docs": [
"accumulate fuel bonus for maker volume"
],
"type": "u32"
},
{
"name": "ifStakedGovTokenAmount",
"docs": [
"The amount of tokens staked in the governance spot markets if"
],
"type": "u64"
},
{
"name": "lastFuelIfBonusUpdateTs",
"docs": [
"last unix ts user stats data was used to update if fuel (u32 to save space)"
],
"type": "u32"
},
{
"name": "padding",
"type": {
"array": [
"u8",
12
]
}
}
]
}
},
{
"name": "ReferrerName",
"type": {
"kind": "struct",
"fields": [
{
"name": "authority",
"type": "publicKey"
},
{
"name": "user",
"type": "publicKey"
},
{
"name": "userStats",
"type": "publicKey"
},
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
}
]
}
}
],
"types": [
{
"name": "UpdatePerpMarketSummaryStatsParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "quoteAssetAmountWithUnsettledLp",
"type": {
"option": "i64"
}
},
{
"name": "netUnsettledFundingPnl",
"type": {
"option": "i64"
}
},
{
"name": "updateAmmSummaryStats",
"type": {
"option": "bool"
}
}
]
}
},
{
"name": "LiquidatePerpRecord",
"type": {
"kind": "struct",
"fields": [
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "oraclePrice",
"type": "i64"
},
{
"name": "baseAssetAmount",
"type": "i64"
},
{
"name": "quoteAssetAmount",
"type": "i64"
},
{
"name": "lpShares",
"docs": [
"precision: AMM_RESERVE_PRECISION"
],
"type": "u64"
},
{
"name": "fillRecordId",
"type": "u64"
},
{
"name": "userOrderId",
"type": "u32"
},
{
"name": "liquidatorOrderId",
"type": "u32"
},
{
"name": "liquidatorFee",
"docs": [
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "ifFee",
"docs": [
"precision: QUOTE_PRECISION"
],
"type": "u64"
}
]
}
},
{
"name": "LiquidateSpotRecord",
"type": {
"kind": "struct",
"fields": [
{
"name": "assetMarketIndex",
"type": "u16"
},
{
"name": "assetPrice",
"type": "i64"
},
{
"name": "assetTransfer",
"type": "u128"
},
{
"name": "liabilityMarketIndex",
"type": "u16"
},
{
"name": "liabilityPrice",
"type": "i64"
},
{
"name": "liabilityTransfer",
"docs": [
"precision: token mint precision"
],
"type": "u128"
},
{
"name": "ifFee",
"docs": [
"precision: token mint precision"
],
"type": "u64"
}
]
}
},
{
"name": "LiquidateBorrowForPerpPnlRecord",
"type": {
"kind": "struct",
"fields": [
{
"name": "perpMarketIndex",
"type": "u16"
},
{
"name": "marketOraclePrice",
"type": "i64"
},
{
"name": "pnlTransfer",
"type": "u128"
},
{
"name": "liabilityMarketIndex",
"type": "u16"
},
{
"name": "liabilityPrice",
"type": "i64"
},
{
"name": "liabilityTransfer",
"type": "u128"
}
]
}
},
{
"name": "LiquidatePerpPnlForDepositRecord",
"type": {
"kind": "struct",
"fields": [
{
"name": "perpMarketIndex",
"type": "u16"
},
{
"name": "marketOraclePrice",
"type": "i64"
},
{
"name": "pnlTransfer",
"type": "u128"
},
{
"name": "assetMarketIndex",
"type": "u16"
},
{
"name": "assetPrice",
"type": "i64"
},
{
"name": "assetTransfer",
"type": "u128"
}
]
}
},
{
"name": "PerpBankruptcyRecord",
"type": {
"kind": "struct",
"fields": [
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "pnl",
"type": "i128"
},
{
"name": "ifPayment",
"type": "u128"
},
{
"name": "clawbackUser",
"type": {
"option": "publicKey"
}
},
{
"name": "clawbackUserPayment",
"type": {
"option": "u128"
}
},
{
"name": "cumulativeFundingRateDelta",
"type": "i128"
}
]
}
},
{
"name": "SpotBankruptcyRecord",
"type": {
"kind": "struct",
"fields": [
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "borrowAmount",
"type": "u128"
},
{
"name": "ifPayment",
"type": "u128"
},
{
"name": "cumulativeDepositInterestDelta",
"type": "u128"
}
]
}
},
{
"name": "MarketIdentifier",
"type": {
"kind": "struct",
"fields": [
{
"name": "marketType",
"type": {
"defined": "MarketType"
}
},
{
"name": "marketIndex",
"type": "u16"
}
]
}
},
{
"name": "HistoricalOracleData",
"type": {
"kind": "struct",
"fields": [
{
"name": "lastOraclePrice",
"docs": [
"precision: PRICE_PRECISION"
],
"type": "i64"
},
{
"name": "lastOracleConf",
"docs": [
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "lastOracleDelay",
"docs": [
"number of slots since last update"
],
"type": "i64"
},
{
"name": "lastOraclePriceTwap",
"docs": [
"precision: PRICE_PRECISION"
],
"type": "i64"
},
{
"name": "lastOraclePriceTwap5min",
"docs": [
"precision: PRICE_PRECISION"
],
"type": "i64"
},
{
"name": "lastOraclePriceTwapTs",
"docs": [
"unix_timestamp of last snapshot"
],
"type": "i64"
}
]
}
},
{
"name": "HistoricalIndexData",
"type": {
"kind": "struct",
"fields": [
{
"name": "lastIndexBidPrice",
"docs": [
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "lastIndexAskPrice",
"docs": [
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "lastIndexPriceTwap",
"docs": [
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "lastIndexPriceTwap5min",
"docs": [
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "lastIndexPriceTwapTs",
"docs": [
"unix_timestamp of last snapshot"
],
"type": "i64"
}
]
}
},
{
"name": "PrelaunchOracleParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "perpMarketIndex",
"type": "u16"
},
{
"name": "price",
"type": {
"option": "i64"
}
},
{
"name": "maxPrice",
"type": {
"option": "i64"
}
}
]
}
},
{
"name": "OrderParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "orderType",
"type": {
"defined": "OrderType"
}
},
{
"name": "marketType",
"type": {
"defined": "MarketType"
}
},
{
"name": "direction",
"type": {
"defined": "PositionDirection"
}
},
{
"name": "userOrderId",
"type": "u8"
},
{
"name": "baseAssetAmount",
"type": "u64"
},
{
"name": "price",
"type": "u64"
},
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "reduceOnly",
"type": "bool"
},
{
"name": "postOnly",
"type": {
"defined": "PostOnlyParam"
}
},
{
"name": "immediateOrCancel",
"type": "bool"
},
{
"name": "maxTs",
"type": {
"option": "i64"
}
},
{
"name": "triggerPrice",
"type": {
"option": "u64"
}
},
{
"name": "triggerCondition",
"type": {
"defined": "OrderTriggerCondition"
}
},
{
"name": "oraclePriceOffset",
"type": {
"option": "i32"
}
},
{
"name": "auctionDuration",
"type": {
"option": "u8"
}
},
{
"name": "auctionStartPrice",
"type": {
"option": "i64"
}
},
{
"name": "auctionEndPrice",
"type": {
"option": "i64"
}
}
]
}
},
{
"name": "SwiftServerMessage",
"type": {
"kind": "struct",
"fields": [
{
"name": "uuid",
"type": {
"array": [
"u8",
8
]
}
},
{
"name": "swiftOrderSignature",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "slot",
"type": "u64"
}
]
}
},
{
"name": "SwiftOrderParamsMessage",
"type": {
"kind": "struct",
"fields": [
{
"name": "swiftOrderParams",
"type": {
"defined": "OrderParams"
}
},
{
"name": "subAccountId",
"type": "u16"
},
{
"name": "takeProfitOrderParams",
"type": {
"option": {
"defined": "SwiftTriggerOrderParams"
}
}
},
{
"name": "stopLossOrderParams",
"type": {
"option": {
"defined": "SwiftTriggerOrderParams"
}
}
}
]
}
},
{
"name": "SwiftTriggerOrderParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "triggerPrice",
"type": "u64"
},
{
"name": "baseAssetAmount",
"type": "u64"
}
]
}
},
{
"name": "RFQMakerOrderParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "uuid",
"type": {
"array": [
"u8",
8
]
}
},
{
"name": "authority",
"type": "publicKey"
},
{
"name": "subAccountId",
"type": "u16"
},
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "marketType",
"type": {
"defined": "MarketType"
}
},
{
"name": "baseAssetAmount",
"type": "u64"
},
{
"name": "price",
"type": "u64"
},
{
"name": "direction",
"type": {
"defined": "PositionDirection"
}
},
{
"name": "maxTs",
"type": "i64"
}
]
}
},
{
"name": "RFQMakerMessage",
"type": {
"kind": "struct",
"fields": [
{
"name": "orderParams",
"type": {
"defined": "RFQMakerOrderParams"
}
},
{
"name": "signature",
"type": {
"array": [
"u8",
64
]
}
}
]
}
},
{
"name": "RFQMatch",
"type": {
"kind": "struct",
"fields": [
{
"name": "baseAssetAmount",
"type": "u64"
},
{
"name": "makerOrderParams",
"type": {
"defined": "RFQMakerOrderParams"
}
},
{
"name": "makerSignature",
"type": {
"array": [
"u8",
64
]
}
}
]
}
},
{
"name": "ModifyOrderParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "direction",
"type": {
"option": {
"defined": "PositionDirection"
}
}
},
{
"name": "baseAssetAmount",
"type": {
"option": "u64"
}
},
{
"name": "price",
"type": {
"option": "u64"
}
},
{
"name": "reduceOnly",
"type": {
"option": "bool"
}
},
{
"name": "postOnly",
"type": {
"option": {
"defined": "PostOnlyParam"
}
}
},
{
"name": "immediateOrCancel",
"type": {
"option": "bool"
}
},
{
"name": "maxTs",
"type": {
"option": "i64"
}
},
{
"name": "triggerPrice",
"type": {
"option": "u64"
}
},
{
"name": "triggerCondition",
"type": {
"option": {
"defined": "OrderTriggerCondition"
}
}
},
{
"name": "oraclePriceOffset",
"type": {
"option": "i32"
}
},
{
"name": "auctionDuration",
"type": {
"option": "u8"
}
},
{
"name": "auctionStartPrice",
"type": {
"option": "i64"
}
},
{
"name": "auctionEndPrice",
"type": {
"option": "i64"
}
},
{
"name": "policy",
"type": {
"option": "u8"
}
}
]
}
},
{
"name": "InsuranceClaim",
"type": {
"kind": "struct",
"fields": [
{
"name": "revenueWithdrawSinceLastSettle",
"docs": [
"The amount of revenue last settled",
"Positive if funds left the perp market,",
"negative if funds were pulled into the perp market",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "maxRevenueWithdrawPerPeriod",
"docs": [
"The max amount of revenue that can be withdrawn per period",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "quoteMaxInsurance",
"docs": [
"The max amount of insurance that perp market can use to resolve bankruptcy and pnl deficits",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "quoteSettledInsurance",
"docs": [
"The amount of insurance that has been used to resolve bankruptcy and pnl deficits",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "lastRevenueWithdrawTs",
"docs": [
"The last time revenue was settled in/out of market"
],
"type": "i64"
}
]
}
},
{
"name": "PoolBalance",
"type": {
"kind": "struct",
"fields": [
{
"name": "scaledBalance",
"docs": [
"To get the pool's token amount, you must multiply the scaled balance by the market's cumulative",
"deposit interest",
"precision: SPOT_BALANCE_PRECISION"
],
"type": "u128"
},
{
"name": "marketIndex",
"docs": [
"The spot market the pool is for"
],
"type": "u16"
},
{
"name": "padding",
"type": {
"array": [
"u8",
6
]
}
}
]
}
},
{
"name": "AMM",
"type": {
"kind": "struct",
"fields": [
{
"name": "oracle",
"docs": [
"oracle price data public key"
],
"type": "publicKey"
},
{
"name": "historicalOracleData",
"docs": [
"stores historically witnessed oracle data"
],
"type": {
"defined": "HistoricalOracleData"
}
},
{
"name": "baseAssetAmountPerLp",
"docs": [
"accumulated base asset amount since inception per lp share",
"precision: QUOTE_PRECISION"
],
"type": "i128"
},
{
"name": "quoteAssetAmountPerLp",
"docs": [
"accumulated quote asset amount since inception per lp share",
"precision: QUOTE_PRECISION"
],
"type": "i128"
},
{
"name": "feePool",
"docs": [
"partition of fees from perp market trading moved from pnl settlements"
],
"type": {
"defined": "PoolBalance"
}
},
{
"name": "baseAssetReserve",
"docs": [
"`x` reserves for constant product mm formula (x * y = k)",
"precision: AMM_RESERVE_PRECISION"
],
"type": "u128"
},
{
"name": "quoteAssetReserve",
"docs": [
"`y` reserves for constant product mm formula (x * y = k)",
"precision: AMM_RESERVE_PRECISION"
],
"type": "u128"
},
{
"name": "concentrationCoef",
"docs": [
"determines how close the min/max base asset reserve sit vs base reserves",
"allow for decreasing slippage without increasing liquidity and v.v.",
"precision: PERCENTAGE_PRECISION"
],
"type": "u128"
},
{
"name": "minBaseAssetReserve",
"docs": [
"minimum base_asset_reserve allowed before AMM is unavailable",
"precision: AMM_RESERVE_PRECISION"
],
"type": "u128"
},
{
"name": "maxBaseAssetReserve",
"docs": [
"maximum base_asset_reserve allowed before AMM is unavailable",
"precision: AMM_RESERVE_PRECISION"
],
"type": "u128"
},
{
"name": "sqrtK",
"docs": [
"`sqrt(k)` in constant product mm formula (x * y = k). stored to avoid drift caused by integer math issues",
"precision: AMM_RESERVE_PRECISION"
],
"type": "u128"
},
{
"name": "pegMultiplier",
"docs": [
"normalizing numerical factor for y, its use offers lowest slippage in cp-curve when market is balanced",
"precision: PEG_PRECISION"
],
"type": "u128"
},
{
"name": "terminalQuoteAssetReserve",
"docs": [
"y when market is balanced. stored to save computation",
"precision: AMM_RESERVE_PRECISION"
],
"type": "u128"
},
{
"name": "baseAssetAmountLong",
"docs": [
"always non-negative. tracks number of total longs in market (regardless of counterparty)",
"precision: BASE_PRECISION"
],
"type": "i128"
},
{
"name": "baseAssetAmountShort",
"docs": [
"always non-positive. tracks number of total shorts in market (regardless of counterparty)",
"precision: BASE_PRECISION"
],
"type": "i128"
},
{
"name": "baseAssetAmountWithAmm",
"docs": [
"tracks net position (longs-shorts) in market with AMM as counterparty",
"precision: BASE_PRECISION"
],
"type": "i128"
},
{
"name": "baseAssetAmountWithUnsettledLp",
"docs": [
"tracks net position (longs-shorts) in market with LPs as counterparty",
"precision: BASE_PRECISION"
],
"type": "i128"
},
{
"name": "maxOpenInterest",
"docs": [
"max allowed open interest, blocks trades that breach this value",
"precision: BASE_PRECISION"
],
"type": "u128"
},
{
"name": "quoteAssetAmount",
"docs": [
"sum of all user's perp quote_asset_amount in market",
"precision: QUOTE_PRECISION"
],
"type": "i128"
},
{
"name": "quoteEntryAmountLong",
"docs": [
"sum of all long user's quote_entry_amount in market",
"precision: QUOTE_PRECISION"
],
"type": "i128"
},
{
"name": "quoteEntryAmountShort",
"docs": [
"sum of all short user's quote_entry_amount in market",
"precision: QUOTE_PRECISION"
],
"type": "i128"
},
{
"name": "quoteBreakEvenAmountLong",
"docs": [
"sum of all long user's quote_break_even_amount in market",
"precision: QUOTE_PRECISION"
],
"type": "i128"
},
{
"name": "quoteBreakEvenAmountShort",
"docs": [
"sum of all short user's quote_break_even_amount in market",
"precision: QUOTE_PRECISION"
],
"type": "i128"
},
{
"name": "userLpShares",
"docs": [
"total user lp shares of sqrt_k (protocol owned liquidity = sqrt_k - last_funding_rate)",
"precision: AMM_RESERVE_PRECISION"
],
"type": "u128"
},
{
"name": "lastFundingRate",
"docs": [
"last funding rate in this perp market (unit is quote per base)",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "lastFundingRateLong",
"docs": [
"last funding rate for longs in this perp market (unit is quote per base)",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "lastFundingRateShort",
"docs": [
"last funding rate for shorts in this perp market (unit is quote per base)",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "last24hAvgFundingRate",
"docs": [
"estimate of last 24h of funding rate perp market (unit is quote per base)",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "totalFee",
"docs": [
"total fees collected by this perp market",
"precision: QUOTE_PRECISION"
],
"type": "i128"
},
{
"name": "totalMmFee",
"docs": [
"total fees collected by the vAMM's bid/ask spread",
"precision: QUOTE_PRECISION"
],
"type": "i128"
},
{
"name": "totalExchangeFee",
"docs": [
"total fees collected by exchange fee schedule",
"precision: QUOTE_PRECISION"
],
"type": "u128"
},
{
"name": "totalFeeMinusDistributions",
"docs": [
"total fees minus any recognized upnl and pool withdraws",
"precision: QUOTE_PRECISION"
],
"type": "i128"
},
{
"name": "totalFeeWithdrawn",
"docs": [
"sum of all fees from fee pool withdrawn to revenue pool",
"precision: QUOTE_PRECISION"
],
"type": "u128"
},
{
"name": "totalLiquidationFee",
"docs": [
"all fees collected by market for liquidations",
"precision: QUOTE_PRECISION"
],
"type": "u128"
},
{
"name": "cumulativeFundingRateLong",
"docs": [
"accumulated funding rate for longs since inception in market"
],
"type": "i128"
},
{
"name": "cumulativeFundingRateShort",
"docs": [
"accumulated funding rate for shorts since inception in market"
],
"type": "i128"
},
{
"name": "totalSocialLoss",
"docs": [
"accumulated social loss paid by users since inception in market"
],
"type": "u128"
},
{
"name": "askBaseAssetReserve",
"docs": [
"transformed base_asset_reserve for users going long",
"precision: AMM_RESERVE_PRECISION"
],
"type": "u128"
},
{
"name": "askQuoteAssetReserve",
"docs": [
"transformed quote_asset_reserve for users going long",
"precision: AMM_RESERVE_PRECISION"
],
"type": "u128"
},
{
"name": "bidBaseAssetReserve",
"docs": [
"transformed base_asset_reserve for users going short",
"precision: AMM_RESERVE_PRECISION"
],
"type": "u128"
},
{
"name": "bidQuoteAssetReserve",
"docs": [
"transformed quote_asset_reserve for users going short",
"precision: AMM_RESERVE_PRECISION"
],
"type": "u128"
},
{
"name": "lastOracleNormalisedPrice",
"docs": [
"the last seen oracle price partially shrunk toward the amm reserve price",
"precision: PRICE_PRECISION"
],
"type": "i64"
},
{
"name": "lastOracleReservePriceSpreadPct",
"docs": [
"the gap between the oracle price and the reserve price = y * peg_multiplier / x"
],
"type": "i64"
},
{
"name": "lastBidPriceTwap",
"docs": [
"average estimate of bid price over funding_period",
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "lastAskPriceTwap",
"docs": [
"average estimate of ask price over funding_period",
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "lastMarkPriceTwap",
"docs": [
"average estimate of (bid+ask)/2 price over funding_period",
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "lastMarkPriceTwap5min",
"docs": [
"average estimate of (bid+ask)/2 price over FIVE_MINUTES"
],
"type": "u64"
},
{
"name": "lastUpdateSlot",
"docs": [
"the last blockchain slot the amm was updated"
],
"type": "u64"
},
{
"name": "lastOracleConfPct",
"docs": [
"the pct size of the oracle confidence interval",
"precision: PERCENTAGE_PRECISION"
],
"type": "u64"
},
{
"name": "netRevenueSinceLastFunding",
"docs": [
"the total_fee_minus_distribution change since the last funding update",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "lastFundingRateTs",
"docs": [
"the last funding rate update unix_timestamp"
],
"type": "i64"
},
{
"name": "fundingPeriod",
"docs": [
"the peridocity of the funding rate updates"
],
"type": "i64"
},
{
"name": "orderStepSize",
"docs": [
"the base step size (increment) of orders",
"precision: BASE_PRECISION"
],
"type": "u64"
},
{
"name": "orderTickSize",
"docs": [
"the price tick size of orders",
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "minOrderSize",
"docs": [
"the minimum base size of an order",
"precision: BASE_PRECISION"
],
"type": "u64"
},
{
"name": "maxPositionSize",
"docs": [
"the max base size a single user can have",
"precision: BASE_PRECISION"
],
"type": "u64"
},
{
"name": "volume24h",
"docs": [
"estimated total of volume in market",
"QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "longIntensityVolume",
"docs": [
"the volume intensity of long fills against AMM"
],
"type": "u64"
},
{
"name": "shortIntensityVolume",
"docs": [
"the volume intensity of short fills against AMM"
],
"type": "u64"
},
{
"name": "lastTradeTs",
"docs": [
"the blockchain unix timestamp at the time of the last trade"
],
"type": "i64"
},
{
"name": "markStd",
"docs": [
"estimate of standard deviation of the fill (mark) prices",
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "oracleStd",
"docs": [
"estimate of standard deviation of the oracle price at each update",
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "lastMarkPriceTwapTs",
"docs": [
"the last unix_timestamp the mark twap was updated"
],
"type": "i64"
},
{
"name": "baseSpread",
"docs": [
"the minimum spread the AMM can quote. also used as step size for some spread logic increases."
],
"type": "u32"
},
{
"name": "maxSpread",
"docs": [
"the maximum spread the AMM can quote"
],
"type": "u32"
},
{
"name": "longSpread",
"docs": [
"the spread for asks vs the reserve price"
],
"type": "u32"
},
{
"name": "shortSpread",
"docs": [
"the spread for bids vs the reserve price"
],
"type": "u32"
},
{
"name": "longIntensityCount",
"docs": [
"the count intensity of long fills against AMM"
],
"type": "u32"
},
{
"name": "shortIntensityCount",
"docs": [
"the count intensity of short fills against AMM"
],
"type": "u32"
},
{
"name": "maxFillReserveFraction",
"docs": [
"the fraction of total available liquidity a single fill on the AMM can consume"
],
"type": "u16"
},
{
"name": "maxSlippageRatio",
"docs": [
"the maximum slippage a single fill on the AMM can push"
],
"type": "u16"
},
{
"name": "curveUpdateIntensity",
"docs": [
"the update intensity of AMM formulaic updates (adjusting k). 0-100"
],
"type": "u8"
},
{
"name": "ammJitIntensity",
"docs": [
"the jit intensity of AMM. larger intensity means larger participation in jit. 0 means no jit participation.",
"(0, 100] is intensity for protocol-owned AMM. (100, 200] is intensity for user LP-owned AMM."
],
"type": "u8"
},
{
"name": "oracleSource",
"docs": [
"the oracle provider information. used to decode/scale the oracle public key"
],
"type": {
"defined": "OracleSource"
}
},
{
"name": "lastOracleValid",
"docs": [
"tracks whether the oracle was considered valid at the last AMM update"
],
"type": "bool"
},
{
"name": "targetBaseAssetAmountPerLp",
"docs": [
"the target value for `base_asset_amount_per_lp`, used during AMM JIT with LP split",
"precision: BASE_PRECISION"
],
"type": "i32"
},
{
"name": "perLpBase",
"docs": [
"expo for unit of per_lp, base 10 (if per_lp_base=X, then per_lp unit is 10^X)"
],
"type": "i8"
},
{
"name": "padding1",
"type": "u8"
},
{
"name": "padding2",
"type": "u16"
},
{
"name": "totalFeeEarnedPerLp",
"type": "u64"
},
{
"name": "netUnsettledFundingPnl",
"type": "i64"
},
{
"name": "quoteAssetAmountWithUnsettledLp",
"type": "i64"
},
{
"name": "referencePriceOffset",
"type": "i32"
},
{
"name": "padding",
"type": {
"array": [
"u8",
12
]
}
}
]
}
},
{
"name": "RFQOrderId",
"type": {
"kind": "struct",
"fields": [
{
"name": "uuid",
"type": {
"array": [
"u8",
8
]
}
},
{
"name": "maxTs",
"type": "i64"
}
]
}
},
{
"name": "InsuranceFund",
"type": {
"kind": "struct",
"fields": [
{
"name": "vault",
"type": "publicKey"
},
{
"name": "totalShares",
"type": "u128"
},
{
"name": "userShares",
"type": "u128"
},
{
"name": "sharesBase",
"type": "u128"
},
{
"name": "unstakingPeriod",
"type": "i64"
},
{
"name": "lastRevenueSettleTs",
"type": "i64"
},
{
"name": "revenueSettlePeriod",
"type": "i64"
},
{
"name": "totalFactor",
"type": "u32"
},
{
"name": "userFactor",
"type": "u32"
}
]
}
},
{
"name": "OracleGuardRails",
"type": {
"kind": "struct",
"fields": [
{
"name": "priceDivergence",
"type": {
"defined": "PriceDivergenceGuardRails"
}
},
{
"name": "validity",
"type": {
"defined": "ValidityGuardRails"
}
}
]
}
},
{
"name": "PriceDivergenceGuardRails",
"type": {
"kind": "struct",
"fields": [
{
"name": "markOraclePercentDivergence",
"type": "u64"
},
{
"name": "oracleTwap5minPercentDivergence",
"type": "u64"
}
]
}
},
{
"name": "ValidityGuardRails",
"type": {
"kind": "struct",
"fields": [
{
"name": "slotsBeforeStaleForAmm",
"type": "i64"
},
{
"name": "slotsBeforeStaleForMargin",
"type": "i64"
},
{
"name": "confidenceIntervalMaxSize",
"type": "u64"
},
{
"name": "tooVolatileRatio",
"type": "i64"
}
]
}
},
{
"name": "FeeStructure",
"type": {
"kind": "struct",
"fields": [
{
"name": "feeTiers",
"type": {
"array": [
{
"defined": "FeeTier"
},
10
]
}
},
{
"name": "fillerRewardStructure",
"type": {
"defined": "OrderFillerRewardStructure"
}
},
{
"name": "referrerRewardEpochUpperBound",
"type": "u64"
},
{
"name": "flatFillerFee",
"type": "u64"
}
]
}
},
{
"name": "FeeTier",
"type": {
"kind": "struct",
"fields": [
{
"name": "feeNumerator",
"type": "u32"
},
{
"name": "feeDenominator",
"type": "u32"
},
{
"name": "makerRebateNumerator",
"type": "u32"
},
{
"name": "makerRebateDenominator",
"type": "u32"
},
{
"name": "referrerRewardNumerator",
"type": "u32"
},
{
"name": "referrerRewardDenominator",
"type": "u32"
},
{
"name": "refereeFeeNumerator",
"type": "u32"
},
{
"name": "refereeFeeDenominator",
"type": "u32"
}
]
}
},
{
"name": "OrderFillerRewardStructure",
"type": {
"kind": "struct",
"fields": [
{
"name": "rewardNumerator",
"type": "u32"
},
{
"name": "rewardDenominator",
"type": "u32"
},
{
"name": "timeBasedRewardLowerBound",
"type": "u128"
}
]
}
},
{
"name": "SwiftOrderId",
"type": {
"kind": "struct",
"fields": [
{
"name": "uuid",
"type": {
"array": [
"u8",
8
]
}
},
{
"name": "maxSlot",
"type": "u64"
},
{
"name": "orderId",
"type": "u32"
},
{
"name": "padding",
"type": "u32"
}
]
}
},
{
"name": "SwiftUserOrdersFixed",
"type": {
"kind": "struct",
"fields": [
{
"name": "userPubkey",
"type": "publicKey"
},
{
"name": "padding",
"type": "u32"
},
{
"name": "len",
"type": "u32"
}
]
}
},
{
"name": "UserFees",
"type": {
"kind": "struct",
"fields": [
{
"name": "totalFeePaid",
"docs": [
"Total taker fee paid",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "totalFeeRebate",
"docs": [
"Total maker fee rebate",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "totalTokenDiscount",
"docs": [
"Total discount from holding token",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "totalRefereeDiscount",
"docs": [
"Total discount from being referred",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "totalReferrerReward",
"docs": [
"Total reward to referrer",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "currentEpochReferrerReward",
"docs": [
"Total reward to referrer this epoch",
"precision: QUOTE_PRECISION"
],
"type": "u64"
}
]
}
},
{
"name": "SpotPosition",
"type": {
"kind": "struct",
"fields": [
{
"name": "scaledBalance",
"docs": [
"The scaled balance of the position. To get the token amount, multiply by the cumulative deposit/borrow",
"interest of corresponding market.",
"precision: SPOT_BALANCE_PRECISION"
],
"type": "u64"
},
{
"name": "openBids",
"docs": [
"How many spot bids the user has open",
"precision: token mint precision"
],
"type": "i64"
},
{
"name": "openAsks",
"docs": [
"How many spot asks the user has open",
"precision: token mint precision"
],
"type": "i64"
},
{
"name": "cumulativeDeposits",
"docs": [
"The cumulative deposits/borrows a user has made into a market",
"precision: token mint precision"
],
"type": "i64"
},
{
"name": "marketIndex",
"docs": [
"The market index of the corresponding spot market"
],
"type": "u16"
},
{
"name": "balanceType",
"docs": [
"Whether the position is deposit or borrow"
],
"type": {
"defined": "SpotBalanceType"
}
},
{
"name": "openOrders",
"docs": [
"Number of open orders"
],
"type": "u8"
},
{
"name": "padding",
"type": {
"array": [
"u8",
4
]
}
}
]
}
},
{
"name": "PerpPosition",
"type": {
"kind": "struct",
"fields": [
{
"name": "lastCumulativeFundingRate",
"docs": [
"The perp market's last cumulative funding rate. Used to calculate the funding payment owed to user",
"precision: FUNDING_RATE_PRECISION"
],
"type": "i64"
},
{
"name": "baseAssetAmount",
"docs": [
"the size of the users perp position",
"precision: BASE_PRECISION"
],
"type": "i64"
},
{
"name": "quoteAssetAmount",
"docs": [
"Used to calculate the users pnl. Upon entry, is equal to base_asset_amount * avg entry price - fees",
"Updated when the user open/closes position or settles pnl. Includes fees/funding",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "quoteBreakEvenAmount",
"docs": [
"The amount of quote the user would need to exit their position at to break even",
"Updated when the user open/closes position or settles pnl. Includes fees/funding",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "quoteEntryAmount",
"docs": [
"The amount quote the user entered the position with. Equal to base asset amount * avg entry price",
"Updated when the user open/closes position. Excludes fees/funding",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "openBids",
"docs": [
"The amount of open bids the user has in this perp market",
"precision: BASE_PRECISION"
],
"type": "i64"
},
{
"name": "openAsks",
"docs": [
"The amount of open asks the user has in this perp market",
"precision: BASE_PRECISION"
],
"type": "i64"
},
{
"name": "settledPnl",
"docs": [
"The amount of pnl settled in this market since opening the position",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "lpShares",
"docs": [
"The number of lp (liquidity provider) shares the user has in this perp market",
"LP shares allow users to provide liquidity via the AMM",
"precision: BASE_PRECISION"
],
"type": "u64"
},
{
"name": "lastBaseAssetAmountPerLp",
"docs": [
"The last base asset amount per lp the amm had",
"Used to settle the users lp position",
"precision: BASE_PRECISION"
],
"type": "i64"
},
{
"name": "lastQuoteAssetAmountPerLp",
"docs": [
"The last quote asset amount per lp the amm had",
"Used to settle the users lp position",
"precision: QUOTE_PRECISION"
],
"type": "i64"
},
{
"name": "remainderBaseAssetAmount",
"docs": [
"Settling LP position can lead to a small amount of base asset being left over smaller than step size",
"This records that remainder so it can be settled later on",
"precision: BASE_PRECISION"
],
"type": "i32"
},
{
"name": "marketIndex",
"docs": [
"The market index for the perp market"
],
"type": "u16"
},
{
"name": "openOrders",
"docs": [
"The number of open orders"
],
"type": "u8"
},
{
"name": "perLpBase",
"type": "i8"
}
]
}
},
{
"name": "Order",
"type": {
"kind": "struct",
"fields": [
{
"name": "slot",
"docs": [
"The slot the order was placed"
],
"type": "u64"
},
{
"name": "price",
"docs": [
"The limit price for the order (can be 0 for market orders)",
"For orders with an auction, this price isn't used until the auction is complete",
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "baseAssetAmount",
"docs": [
"The size of the order",
"precision for perps: BASE_PRECISION",
"precision for spot: token mint precision"
],
"type": "u64"
},
{
"name": "baseAssetAmountFilled",
"docs": [
"The amount of the order filled",
"precision for perps: BASE_PRECISION",
"precision for spot: token mint precision"
],
"type": "u64"
},
{
"name": "quoteAssetAmountFilled",
"docs": [
"The amount of quote filled for the order",
"precision: QUOTE_PRECISION"
],
"type": "u64"
},
{
"name": "triggerPrice",
"docs": [
"At what price the order will be triggered. Only relevant for trigger orders",
"precision: PRICE_PRECISION"
],
"type": "u64"
},
{
"name": "auctionStartPrice",
"docs": [
"The start price for the auction. Only relevant for market/oracle orders",
"precision: PRICE_PRECISION"
],
"type": "i64"
},
{
"name": "auctionEndPrice",
"docs": [
"The end price for the auction. Only relevant for market/oracle orders",
"precision: PRICE_PRECISION"
],
"type": "i64"
},
{
"name": "maxTs",
"docs": [
"The time when the order will expire"
],
"type": "i64"
},
{
"name": "oraclePriceOffset",
"docs": [
"If set, the order limit price is the oracle price + this offset",
"precision: PRICE_PRECISION"
],
"type": "i32"
},
{
"name": "orderId",
"docs": [
"The id for the order. Each users has their own order id space"
],
"type": "u32"
},
{
"name": "marketIndex",
"docs": [
"The perp/spot market index"
],
"type": "u16"
},
{
"name": "status",
"docs": [
"Whether the order is open or unused"
],
"type": {
"defined": "OrderStatus"
}
},
{
"name": "orderType",
"docs": [
"The type of order"
],
"type": {
"defined": "OrderType"
}
},
{
"name": "marketType",
"docs": [
"Whether market is spot or perp"
],
"type": {
"defined": "MarketType"
}
},
{
"name": "userOrderId",
"docs": [
"User generated order id. Can make it easier to place/cancel orders"
],
"type": "u8"
},
{
"name": "existingPositionDirection",
"docs": [
"What the users position was when the order was placed"
],
"type": {
"defined": "PositionDirection"
}
},
{
"name": "direction",
"docs": [
"Whether the user is going long or short. LONG = bid, SHORT = ask"
],
"type": {
"defined": "PositionDirection"
}
},
{
"name": "reduceOnly",
"docs": [
"Whether the order is allowed to only reduce position size"
],
"type": "bool"
},
{
"name": "postOnly",
"docs": [
"Whether the order must be a maker"
],
"type": "bool"
},
{
"name": "immediateOrCancel",
"docs": [
"Whether the order must be canceled the same slot it is placed"
],
"type": "bool"
},
{
"name": "triggerCondition",
"docs": [
"Whether the order is triggered above or below the trigger price. Only relevant for trigger orders"
],
"type": {
"defined": "OrderTriggerCondition"
}
},
{
"name": "auctionDuration",
"docs": [
"How many slots the auction lasts"
],
"type": "u8"
},
{
"name": "padding",
"type": {
"array": [
"u8",
3
]
}
}
]
}
},
{
"name": "SwapDirection",
"type": {
"kind": "enum",
"variants": [
{
"name": "Add"
},
{
"name": "Remove"
}
]
}
},
{
"name": "ModifyOrderId",
"type": {
"kind": "enum",
"variants": [
{
"name": "UserOrderId",
"fields": [
"u8"
]
},
{
"name": "OrderId",
"fields": [
"u32"
]
}
]
}
},
{
"name": "PositionDirection",
"type": {
"kind": "enum",
"variants": [
{
"name": "Long"
},
{
"name": "Short"
}
]
}
},
{
"name": "SpotFulfillmentType",
"type": {
"kind": "enum",
"variants": [
{
"name": "SerumV3"
},
{
"name": "Match"
},
{
"name": "PhoenixV1"
},
{
"name": "OpenbookV2"
}
]
}
},
{
"name": "SwapReduceOnly",
"type": {
"kind": "enum",
"variants": [
{
"name": "In"
},
{
"name": "Out"
}
]
}
},
{
"name": "TwapPeriod",
"type": {
"kind": "enum",
"variants": [
{
"name": "FundingPeriod"
},
{
"name": "FiveMin"
}
]
}
},
{
"name": "LiquidationMultiplierType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Discount"
},
{
"name": "Premium"
}
]
}
},
{
"name": "MarginRequirementType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Initial"
},
{
"name": "Fill"
},
{
"name": "Maintenance"
}
]
}
},
{
"name": "OracleValidity",
"type": {
"kind": "enum",
"variants": [
{
"name": "NonPositive"
},
{
"name": "TooVolatile"
},
{
"name": "TooUncertain"
},
{
"name": "StaleForMargin"
},
{
"name": "InsufficientDataPoints"
},
{
"name": "StaleForAMM"
},
{
"name": "Valid"
}
]
}
},
{
"name": "DriftAction",
"type": {
"kind": "enum",
"variants": [
{
"name": "UpdateFunding"
},
{
"name": "SettlePnl"
},
{
"name": "TriggerOrder"
},
{
"name": "FillOrderMatch"
},
{
"name": "FillOrderAmm"
},
{
"name": "Liquidate"
},
{
"name": "MarginCalc"
},
{
"name": "UpdateTwap"
},
{
"name": "UpdateAMMCurve"
},
{
"name": "OracleOrderPrice"
}
]
}
},
{
"name": "PositionUpdateType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Open"
},
{
"name": "Increase"
},
{
"name": "Reduce"
},
{
"name": "Close"
},
{
"name": "Flip"
}
]
}
},
{
"name": "DepositExplanation",
"type": {
"kind": "enum",
"variants": [
{
"name": "None"
},
{
"name": "Transfer"
},
{
"name": "Borrow"
},
{
"name": "RepayBorrow"
}
]
}
},
{
"name": "DepositDirection",
"type": {
"kind": "enum",
"variants": [
{
"name": "Deposit"
},
{
"name": "Withdraw"
}
]
}
},
{
"name": "OrderAction",
"type": {
"kind": "enum",
"variants": [
{
"name": "Place"
},
{
"name": "Cancel"
},
{
"name": "Fill"
},
{
"name": "Trigger"
},
{
"name": "Expire"
}
]
}
},
{
"name": "OrderActionExplanation",
"type": {
"kind": "enum",
"variants": [
{
"name": "None"
},
{
"name": "InsufficientFreeCollateral"
},
{
"name": "OraclePriceBreachedLimitPrice"
},
{
"name": "MarketOrderFilledToLimitPrice"
},
{
"name": "OrderExpired"
},
{
"name": "Liquidation"
},
{
"name": "OrderFilledWithAMM"
},
{
"name": "OrderFilledWithAMMJit"
},
{
"name": "OrderFilledWithMatch"
},
{
"name": "OrderFilledWithMatchJit"
},
{
"name": "MarketExpired"
},
{
"name": "RiskingIncreasingOrder"
},
{
"name": "ReduceOnlyOrderIncreasedPosition"
},
{
"name": "OrderFillWithSerum"
},
{
"name": "NoBorrowLiquidity"
},
{
"name": "OrderFillWithPhoenix"
},
{
"name": "OrderFilledWithAMMJitLPSplit"
},
{
"name": "OrderFilledWithLPJit"
},
{
"name": "DeriskLp"
},
{
"name": "OrderFilledWithOpenbookV2"
}
]
}
},
{
"name": "LPAction",
"type": {
"kind": "enum",
"variants": [
{
"name": "AddLiquidity"
},
{
"name": "RemoveLiquidity"
},
{
"name": "SettleLiquidity"
},
{
"name": "RemoveLiquidityDerisk"
}
]
}
},
{
"name": "LiquidationType",
"type": {
"kind": "enum",
"variants": [
{
"name": "LiquidatePerp"
},
{
"name": "LiquidateSpot"
},
{
"name": "LiquidateBorrowForPerpPnl"
},
{
"name": "LiquidatePerpPnlForDeposit"
},
{
"name": "PerpBankruptcy"
},
{
"name": "SpotBankruptcy"
}
]
}
},
{
"name": "SettlePnlExplanation",
"type": {
"kind": "enum",
"variants": [
{
"name": "None"
},
{
"name": "ExpiredPosition"
}
]
}
},
{
"name": "StakeAction",
"type": {
"kind": "enum",
"variants": [
{
"name": "Stake"
},
{
"name": "UnstakeRequest"
},
{
"name": "UnstakeCancelRequest"
},
{
"name": "Unstake"
},
{
"name": "UnstakeTransfer"
},
{
"name": "StakeTransfer"
}
]
}
},
{
"name": "FillMode",
"type": {
"kind": "enum",
"variants": [
{
"name": "Fill"
},
{
"name": "PlaceAndMake"
},
{
"name": "PlaceAndTake",
"fields": [
"bool",
"u8"
]
},
{
"name": "Liquidation"
},
{
"name": "RFQ"
}
]
}
},
{
"name": "PerpFulfillmentMethod",
"type": {
"kind": "enum",
"variants": [
{
"name": "AMM",
"fields": [
{
"option": "u64"
}
]
},
{
"name": "Match",
"fields": [
"publicKey",
"u16"
]
}
]
}
},
{
"name": "SpotFulfillmentMethod",
"type": {
"kind": "enum",
"variants": [
{
"name": "ExternalMarket"
},
{
"name": "Match",
"fields": [
"publicKey",
"u16"
]
}
]
}
},
{
"name": "MarginCalculationMode",
"type": {
"kind": "enum",
"variants": [
{
"name": "Standard",
"fields": [
{
"name": "trackOpenOrdersFraction",
"type": "bool"
}
]
},
{
"name": "Liquidation",
"fields": [
{
"name": "marketToTrackMarginRequirement",
"type": {
"option": {
"defined": "MarketIdentifier"
}
}
}
]
}
]
}
},
{
"name": "OracleSource",
"type": {
"kind": "enum",
"variants": [
{
"name": "Pyth"
},
{
"name": "Switchboard"
},
{
"name": "QuoteAsset"
},
{
"name": "Pyth1K"
},
{
"name": "Pyth1M"
},
{
"name": "PythStableCoin"
},
{
"name": "Prelaunch"
},
{
"name": "PythPull"
},
{
"name": "Pyth1KPull"
},
{
"name": "Pyth1MPull"
},
{
"name": "PythStableCoinPull"
},
{
"name": "SwitchboardOnDemand"
},
{
"name": "PythLazer"
}
]
}
},
{
"name": "PostOnlyParam",
"type": {
"kind": "enum",
"variants": [
{
"name": "None"
},
{
"name": "MustPostOnly"
},
{
"name": "TryPostOnly"
},
{
"name": "Slide"
}
]
}
},
{
"name": "ModifyOrderPolicy",
"type": {
"kind": "enum",
"variants": [
{
"name": "MustModify"
},
{
"name": "ExcludePreviousFill"
}
]
}
},
{
"name": "PlaceAndTakeOrderSuccessCondition",
"type": {
"kind": "enum",
"variants": [
{
"name": "PartialFill"
},
{
"name": "FullFill"
}
]
}
},
{
"name": "PerpOperation",
"type": {
"kind": "enum",
"variants": [
{
"name": "UpdateFunding"
},
{
"name": "AmmFill"
},
{
"name": "Fill"
},
{
"name": "SettlePnl"
},
{
"name": "SettlePnlWithPosition"
},
{
"name": "Liquidation"
},
{
"name": "AmmImmediateFill"
}
]
}
},
{
"name": "SpotOperation",
"type": {
"kind": "enum",
"variants": [
{
"name": "UpdateCumulativeInterest"
},
{
"name": "Fill"
},
{
"name": "Deposit"
},
{
"name": "Withdraw"
},
{
"name": "Liquidation"
}
]
}
},
{
"name": "InsuranceFundOperation",
"type": {
"kind": "enum",
"variants": [
{
"name": "Init"
},
{
"name": "Add"
},
{
"name": "RequestRemove"
},
{
"name": "Remove"
}
]
}
},
{
"name": "MarketStatus",
"type": {
"kind": "enum",
"variants": [
{
"name": "Initialized"
},
{
"name": "Active"
},
{
"name": "FundingPaused"
},
{
"name": "AmmPaused"
},
{
"name": "FillPaused"
},
{
"name": "WithdrawPaused"
},
{
"name": "ReduceOnly"
},
{
"name": "Settlement"
},
{
"name": "Delisted"
}
]
}
},
{
"name": "ContractType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Perpetual"
},
{
"name": "Future"
},
{
"name": "Prediction"
}
]
}
},
{
"name": "ContractTier",
"type": {
"kind": "enum",
"variants": [
{
"name": "A"
},
{
"name": "B"
},
{
"name": "C"
},
{
"name": "Speculative"
},
{
"name": "HighlySpeculative"
},
{
"name": "Isolated"
}
]
}
},
{
"name": "AMMLiquiditySplit",
"type": {
"kind": "enum",
"variants": [
{
"name": "ProtocolOwned"
},
{
"name": "LPOwned"
},
{
"name": "Shared"
}
]
}
},
{
"name": "AMMAvailability",
"type": {
"kind": "enum",
"variants": [
{
"name": "Immediate"
},
{
"name": "AfterMinDuration"
},
{
"name": "Unavailable"
}
]
}
},
{
"name": "SettlePnlMode",
"type": {
"kind": "enum",
"variants": [
{
"name": "MustSettle"
},
{
"name": "TrySettle"
}
]
}
},
{
"name": "SpotBalanceType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Deposit"
},
{
"name": "Borrow"
}
]
}
},
{
"name": "SpotFulfillmentConfigStatus",
"type": {
"kind": "enum",
"variants": [
{
"name": "Enabled"
},
{
"name": "Disabled"
}
]
}
},
{
"name": "AssetTier",
"type": {
"kind": "enum",
"variants": [
{
"name": "Collateral"
},
{
"name": "Protected"
},
{
"name": "Cross"
},
{
"name": "Isolated"
},
{
"name": "Unlisted"
}
]
}
},
{
"name": "ExchangeStatus",
"type": {
"kind": "enum",
"variants": [
{
"name": "DepositPaused"
},
{
"name": "WithdrawPaused"
},
{
"name": "AmmPaused"
},
{
"name": "FillPaused"
},
{
"name": "LiqPaused"
},
{
"name": "FundingPaused"
},
{
"name": "SettlePnlPaused"
},
{
"name": "AmmImmediateFillPaused"
}
]
}
},
{
"name": "UserStatus",
"type": {
"kind": "enum",
"variants": [
{
"name": "BeingLiquidated"
},
{
"name": "Bankrupt"
},
{
"name": "ReduceOnly"
},
{
"name": "AdvancedLp"
},
{
"name": "ProtectedMakerOrders"
}
]
}
},
{
"name": "AssetType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Base"
},
{
"name": "Quote"
}
]
}
},
{
"name": "OrderStatus",
"type": {
"kind": "enum",
"variants": [
{
"name": "Init"
},
{
"name": "Open"
},
{
"name": "Filled"
},
{
"name": "Canceled"
}
]
}
},
{
"name": "OrderType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Market"
},
{
"name": "Limit"
},
{
"name": "TriggerMarket"
},
{
"name": "TriggerLimit"
},
{
"name": "Oracle"
}
]
}
},
{
"name": "OrderTriggerCondition",
"type": {
"kind": "enum",
"variants": [
{
"name": "Above"
},
{
"name": "Below"
},
{
"name": "TriggeredAbove"
},
{
"name": "TriggeredBelow"
}
]
}
},
{
"name": "MarketType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Spot"
},
{
"name": "Perp"
}
]
}
},
{
"name": "ReferrerStatus",
"type": {
"kind": "enum",
"variants": [
{
"name": "IsReferrer"
},
{
"name": "IsReferred"
}
]
}
},
{
"name": "MarginMode",
"type": {
"kind": "enum",
"variants": [
{
"name": "Default"
},
{
"name": "HighLeverage"
}
]
}
}
],
"events": [
{
"name": "NewUserRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "userAuthority",
"type": "publicKey",
"index": false
},
{
"name": "user",
"type": "publicKey",
"index": false
},
{
"name": "subAccountId",
"type": "u16",
"index": false
},
{
"name": "name",
"type": {
"array": [
"u8",
32
]
},
"index": false
},
{
"name": "referrer",
"type": "publicKey",
"index": false
}
]
},
{
"name": "DepositRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "userAuthority",
"type": "publicKey",
"index": false
},
{
"name": "user",
"type": "publicKey",
"index": false
},
{
"name": "direction",
"type": {
"defined": "DepositDirection"
},
"index": false
},
{
"name": "depositRecordId",
"type": "u64",
"index": false
},
{
"name": "amount",
"type": "u64",
"index": false
},
{
"name": "marketIndex",
"type": "u16",
"index": false
},
{
"name": "oraclePrice",
"type": "i64",
"index": false
},
{
"name": "marketDepositBalance",
"type": "u128",
"index": false
},
{
"name": "marketWithdrawBalance",
"type": "u128",
"index": false
},
{
"name": "marketCumulativeDepositInterest",
"type": "u128",
"index": false
},
{
"name": "marketCumulativeBorrowInterest",
"type": "u128",
"index": false
},
{
"name": "totalDepositsAfter",
"type": "u64",
"index": false
},
{
"name": "totalWithdrawsAfter",
"type": "u64",
"index": false
},
{
"name": "explanation",
"type": {
"defined": "DepositExplanation"
},
"index": false
},
{
"name": "transferUser",
"type": {
"option": "publicKey"
},
"index": false
}
]
},
{
"name": "SpotInterestRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "marketIndex",
"type": "u16",
"index": false
},
{
"name": "depositBalance",
"type": "u128",
"index": false
},
{
"name": "cumulativeDepositInterest",
"type": "u128",
"index": false
},
{
"name": "borrowBalance",
"type": "u128",
"index": false
},
{
"name": "cumulativeBorrowInterest",
"type": "u128",
"index": false
},
{
"name": "optimalUtilization",
"type": "u32",
"index": false
},
{
"name": "optimalBorrowRate",
"type": "u32",
"index": false
},
{
"name": "maxBorrowRate",
"type": "u32",
"index": false
}
]
},
{
"name": "FundingPaymentRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "userAuthority",
"type": "publicKey",
"index": false
},
{
"name": "user",
"type": "publicKey",
"index": false
},
{
"name": "marketIndex",
"type": "u16",
"index": false
},
{
"name": "fundingPayment",
"type": "i64",
"index": false
},
{
"name": "baseAssetAmount",
"type": "i64",
"index": false
},
{
"name": "userLastCumulativeFunding",
"type": "i64",
"index": false
},
{
"name": "ammCumulativeFundingLong",
"type": "i128",
"index": false
},
{
"name": "ammCumulativeFundingShort",
"type": "i128",
"index": false
}
]
},
{
"name": "FundingRateRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "recordId",
"type": "u64",
"index": false
},
{
"name": "marketIndex",
"type": "u16",
"index": false
},
{
"name": "fundingRate",
"type": "i64",
"index": false
},
{
"name": "fundingRateLong",
"type": "i128",
"index": false
},
{
"name": "fundingRateShort",
"type": "i128",
"index": false
},
{
"name": "cumulativeFundingRateLong",
"type": "i128",
"index": false
},
{
"name": "cumulativeFundingRateShort",
"type": "i128",
"index": false
},
{
"name": "oraclePriceTwap",
"type": "i64",
"index": false
},
{
"name": "markPriceTwap",
"type": "u64",
"index": false
},
{
"name": "periodRevenue",
"type": "i64",
"index": false
},
{
"name": "baseAssetAmountWithAmm",
"type": "i128",
"index": false
},
{
"name": "baseAssetAmountWithUnsettledLp",
"type": "i128",
"index": false
}
]
},
{
"name": "CurveRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "recordId",
"type": "u64",
"index": false
},
{
"name": "pegMultiplierBefore",
"type": "u128",
"index": false
},
{
"name": "baseAssetReserveBefore",
"type": "u128",
"index": false
},
{
"name": "quoteAssetReserveBefore",
"type": "u128",
"index": false
},
{
"name": "sqrtKBefore",
"type": "u128",
"index": false
},
{
"name": "pegMultiplierAfter",
"type": "u128",
"index": false
},
{
"name": "baseAssetReserveAfter",
"type": "u128",
"index": false
},
{
"name": "quoteAssetReserveAfter",
"type": "u128",
"index": false
},
{
"name": "sqrtKAfter",
"type": "u128",
"index": false
},
{
"name": "baseAssetAmountLong",
"type": "u128",
"index": false
},
{
"name": "baseAssetAmountShort",
"type": "u128",
"index": false
},
{
"name": "baseAssetAmountWithAmm",
"type": "i128",
"index": false
},
{
"name": "totalFee",
"type": "i128",
"index": false
},
{
"name": "totalFeeMinusDistributions",
"type": "i128",
"index": false
},
{
"name": "adjustmentCost",
"type": "i128",
"index": false
},
{
"name": "oraclePrice",
"type": "i64",
"index": false
},
{
"name": "fillRecord",
"type": "u128",
"index": false
},
{
"name": "numberOfUsers",
"type": "u32",
"index": false
},
{
"name": "marketIndex",
"type": "u16",
"index": false
}
]
},
{
"name": "SwiftOrderRecord",
"fields": [
{
"name": "user",
"type": "publicKey",
"index": false
},
{
"name": "hash",
"type": "string",
"index": false
},
{
"name": "matchingOrderParams",
"type": {
"defined": "OrderParams"
},
"index": false
},
{
"name": "userOrderId",
"type": "u32",
"index": false
},
{
"name": "swiftOrderMaxSlot",
"type": "u64",
"index": false
},
{
"name": "swiftOrderUuid",
"type": {
"array": [
"u8",
8
]
},
"index": false
},
{
"name": "ts",
"type": "i64",
"index": false
}
]
},
{
"name": "OrderRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "user",
"type": "publicKey",
"index": false
},
{
"name": "order",
"type": {
"defined": "Order"
},
"index": false
}
]
},
{
"name": "OrderActionRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "action",
"type": {
"defined": "OrderAction"
},
"index": false
},
{
"name": "actionExplanation",
"type": {
"defined": "OrderActionExplanation"
},
"index": false
},
{
"name": "marketIndex",
"type": "u16",
"index": false
},
{
"name": "marketType",
"type": {
"defined": "MarketType"
},
"index": false
},
{
"name": "filler",
"type": {
"option": "publicKey"
},
"index": false
},
{
"name": "fillerReward",
"type": {
"option": "u64"
},
"index": false
},
{
"name": "fillRecordId",
"type": {
"option": "u64"
},
"index": false
},
{
"name": "baseAssetAmountFilled",
"type": {
"option": "u64"
},
"index": false
},
{
"name": "quoteAssetAmountFilled",
"type": {
"option": "u64"
},
"index": false
},
{
"name": "takerFee",
"type": {
"option": "u64"
},
"index": false
},
{
"name": "makerFee",
"type": {
"option": "i64"
},
"index": false
},
{
"name": "referrerReward",
"type": {
"option": "u32"
},
"index": false
},
{
"name": "quoteAssetAmountSurplus",
"type": {
"option": "i64"
},
"index": false
},
{
"name": "spotFulfillmentMethodFee",
"type": {
"option": "u64"
},
"index": false
},
{
"name": "taker",
"type": {
"option": "publicKey"
},
"index": false
},
{
"name": "takerOrderId",
"type": {
"option": "u32"
},
"index": false
},
{
"name": "takerOrderDirection",
"type": {
"option": {
"defined": "PositionDirection"
}
},
"index": false
},
{
"name": "takerOrderBaseAssetAmount",
"type": {
"option": "u64"
},
"index": false
},
{
"name": "takerOrderCumulativeBaseAssetAmountFilled",
"type": {
"option": "u64"
},
"index": false
},
{
"name": "takerOrderCumulativeQuoteAssetAmountFilled",
"type": {
"option": "u64"
},
"index": false
},
{
"name": "maker",
"type": {
"option": "publicKey"
},
"index": false
},
{
"name": "makerOrderId",
"type": {
"option": "u32"
},
"index": false
},
{
"name": "makerOrderDirection",
"type": {
"option": {
"defined": "PositionDirection"
}
},
"index": false
},
{
"name": "makerOrderBaseAssetAmount",
"type": {
"option": "u64"
},
"index": false
},
{
"name": "makerOrderCumulativeBaseAssetAmountFilled",
"type": {
"option": "u64"
},
"index": false
},
{
"name": "makerOrderCumulativeQuoteAssetAmountFilled",
"type": {
"option": "u64"
},
"index": false
},
{
"name": "oraclePrice",
"type": "i64",
"index": false
}
]
},
{
"name": "LPRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "user",
"type": "publicKey",
"index": false
},
{
"name": "action",
"type": {
"defined": "LPAction"
},
"index": false
},
{
"name": "nShares",
"type": "u64",
"index": false
},
{
"name": "marketIndex",
"type": "u16",
"index": false
},
{
"name": "deltaBaseAssetAmount",
"type": "i64",
"index": false
},
{
"name": "deltaQuoteAssetAmount",
"type": "i64",
"index": false
},
{
"name": "pnl",
"type": "i64",
"index": false
}
]
},
{
"name": "LiquidationRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "liquidationType",
"type": {
"defined": "LiquidationType"
},
"index": false
},
{
"name": "user",
"type": "publicKey",
"index": false
},
{
"name": "liquidator",
"type": "publicKey",
"index": false
},
{
"name": "marginRequirement",
"type": "u128",
"index": false
},
{
"name": "totalCollateral",
"type": "i128",
"index": false
},
{
"name": "marginFreed",
"type": "u64",
"index": false
},
{
"name": "liquidationId",
"type": "u16",
"index": false
},
{
"name": "bankrupt",
"type": "bool",
"index": false
},
{
"name": "canceledOrderIds",
"type": {
"vec": "u32"
},
"index": false
},
{
"name": "liquidatePerp",
"type": {
"defined": "LiquidatePerpRecord"
},
"index": false
},
{
"name": "liquidateSpot",
"type": {
"defined": "LiquidateSpotRecord"
},
"index": false
},
{
"name": "liquidateBorrowForPerpPnl",
"type": {
"defined": "LiquidateBorrowForPerpPnlRecord"
},
"index": false
},
{
"name": "liquidatePerpPnlForDeposit",
"type": {
"defined": "LiquidatePerpPnlForDepositRecord"
},
"index": false
},
{
"name": "perpBankruptcy",
"type": {
"defined": "PerpBankruptcyRecord"
},
"index": false
},
{
"name": "spotBankruptcy",
"type": {
"defined": "SpotBankruptcyRecord"
},
"index": false
}
]
},
{
"name": "SettlePnlRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "user",
"type": "publicKey",
"index": false
},
{
"name": "marketIndex",
"type": "u16",
"index": false
},
{
"name": "pnl",
"type": "i128",
"index": false
},
{
"name": "baseAssetAmount",
"type": "i64",
"index": false
},
{
"name": "quoteAssetAmountAfter",
"type": "i64",
"index": false
},
{
"name": "quoteEntryAmount",
"type": "i64",
"index": false
},
{
"name": "settlePrice",
"type": "i64",
"index": false
},
{
"name": "explanation",
"type": {
"defined": "SettlePnlExplanation"
},
"index": false
}
]
},
{
"name": "InsuranceFundRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "spotMarketIndex",
"type": "u16",
"index": false
},
{
"name": "perpMarketIndex",
"type": "u16",
"index": false
},
{
"name": "userIfFactor",
"type": "u32",
"index": false
},
{
"name": "totalIfFactor",
"type": "u32",
"index": false
},
{
"name": "vaultAmountBefore",
"type": "u64",
"index": false
},
{
"name": "insuranceVaultAmountBefore",
"type": "u64",
"index": false
},
{
"name": "totalIfSharesBefore",
"type": "u128",
"index": false
},
{
"name": "totalIfSharesAfter",
"type": "u128",
"index": false
},
{
"name": "amount",
"type": "i64",
"index": false
}
]
},
{
"name": "InsuranceFundStakeRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "userAuthority",
"type": "publicKey",
"index": false
},
{
"name": "action",
"type": {
"defined": "StakeAction"
},
"index": false
},
{
"name": "amount",
"type": "u64",
"index": false
},
{
"name": "marketIndex",
"type": "u16",
"index": false
},
{
"name": "insuranceVaultAmountBefore",
"type": "u64",
"index": false
},
{
"name": "ifSharesBefore",
"type": "u128",
"index": false
},
{
"name": "userIfSharesBefore",
"type": "u128",
"index": false
},
{
"name": "totalIfSharesBefore",
"type": "u128",
"index": false
},
{
"name": "ifSharesAfter",
"type": "u128",
"index": false
},
{
"name": "userIfSharesAfter",
"type": "u128",
"index": false
},
{
"name": "totalIfSharesAfter",
"type": "u128",
"index": false
}
]
},
{
"name": "SwapRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "user",
"type": "publicKey",
"index": false
},
{
"name": "amountOut",
"type": "u64",
"index": false
},
{
"name": "amountIn",
"type": "u64",
"index": false
},
{
"name": "outMarketIndex",
"type": "u16",
"index": false
},
{
"name": "inMarketIndex",
"type": "u16",
"index": false
},
{
"name": "outOraclePrice",
"type": "i64",
"index": false
},
{
"name": "inOraclePrice",
"type": "i64",
"index": false
},
{
"name": "fee",
"type": "u64",
"index": false
}
]
},
{
"name": "SpotMarketVaultDepositRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "marketIndex",
"type": "u16",
"index": false
},
{
"name": "depositBalance",
"type": "u128",
"index": false
},
{
"name": "cumulativeDepositInterestBefore",
"type": "u128",
"index": false
},
{
"name": "cumulativeDepositInterestAfter",
"type": "u128",
"index": false
},
{
"name": "depositTokenAmountBefore",
"type": "u64",
"index": false
},
{
"name": "amount",
"type": "u64",
"index": false
}
]
},
{
"name": "DeleteUserRecord",
"fields": [
{
"name": "ts",
"type": "i64",
"index": false
},
{
"name": "userAuthority",
"type": "publicKey",
"index": false
},
{
"name": "user",
"type": "publicKey",
"index": false
},
{
"name": "subAccountId",
"type": "u16",
"index": false
},
{
"name": "keeper",
"type": {
"option": "publicKey"
},
"index": false
}
]
}
],
"errors": [
{
"code": 6000,
"name": "InvalidSpotMarketAuthority",
"msg": "Invalid Spot Market Authority"
},
{
"code": 6001,
"name": "InvalidInsuranceFundAuthority",
"msg": "Clearing house not insurance fund authority"
},
{
"code": 6002,
"name": "InsufficientDeposit",
"msg": "Insufficient deposit"
},
{
"code": 6003,
"name": "InsufficientCollateral",
"msg": "Insufficient collateral"
},
{
"code": 6004,
"name": "SufficientCollateral",
"msg": "Sufficient collateral"
},
{
"code": 6005,
"name": "MaxNumberOfPositions",
"msg": "Max number of positions taken"
},
{
"code": 6006,
"name": "AdminControlsPricesDisabled",
"msg": "Admin Controls Prices Disabled"
},
{
"code": 6007,
"name": "MarketDelisted",
"msg": "Market Delisted"
},
{
"code": 6008,
"name": "MarketIndexAlreadyInitialized",
"msg": "Market Index Already Initialized"
},
{
"code": 6009,
"name": "UserAccountAndUserPositionsAccountMismatch",
"msg": "User Account And User Positions Account Mismatch"
},
{
"code": 6010,
"name": "UserHasNoPositionInMarket",
"msg": "User Has No Position In Market"
},
{
"code": 6011,
"name": "InvalidInitialPeg",
"msg": "Invalid Initial Peg"
},
{
"code": 6012,
"name": "InvalidRepegRedundant",
"msg": "AMM repeg already configured with amt given"
},
{
"code": 6013,
"name": "InvalidRepegDirection",
"msg": "AMM repeg incorrect repeg direction"
},
{
"code": 6014,
"name": "InvalidRepegProfitability",
"msg": "AMM repeg out of bounds pnl"
},
{
"code": 6015,
"name": "SlippageOutsideLimit",
"msg": "Slippage Outside Limit Price"
},
{
"code": 6016,
"name": "OrderSizeTooSmall",
"msg": "Order Size Too Small"
},
{
"code": 6017,
"name": "InvalidUpdateK",
"msg": "Price change too large when updating K"
},
{
"code": 6018,
"name": "AdminWithdrawTooLarge",
"msg": "Admin tried to withdraw amount larger than fees collected"
},
{
"code": 6019,
"name": "MathError",
"msg": "Math Error"
},
{
"code": 6020,
"name": "BnConversionError",
"msg": "Conversion to u128/u64 failed with an overflow or underflow"
},
{
"code": 6021,
"name": "ClockUnavailable",
"msg": "Clock unavailable"
},
{
"code": 6022,
"name": "UnableToLoadOracle",
"msg": "Unable To Load Oracles"
},
{
"code": 6023,
"name": "PriceBandsBreached",
"msg": "Price Bands Breached"
},
{
"code": 6024,
"name": "ExchangePaused",
"msg": "Exchange is paused"
},
{
"code": 6025,
"name": "InvalidWhitelistToken",
"msg": "Invalid whitelist token"
},
{
"code": 6026,
"name": "WhitelistTokenNotFound",
"msg": "Whitelist token not found"
},
{
"code": 6027,
"name": "InvalidDiscountToken",
"msg": "Invalid discount token"
},
{
"code": 6028,
"name": "DiscountTokenNotFound",
"msg": "Discount token not found"
},
{
"code": 6029,
"name": "ReferrerNotFound",
"msg": "Referrer not found"
},
{
"code": 6030,
"name": "ReferrerStatsNotFound",
"msg": "ReferrerNotFound"
},
{
"code": 6031,
"name": "ReferrerMustBeWritable",
"msg": "ReferrerMustBeWritable"
},
{
"code": 6032,
"name": "ReferrerStatsMustBeWritable",
"msg": "ReferrerMustBeWritable"
},
{
"code": 6033,
"name": "ReferrerAndReferrerStatsAuthorityUnequal",
"msg": "ReferrerAndReferrerStatsAuthorityUnequal"
},
{
"code": 6034,
"name": "InvalidReferrer",
"msg": "InvalidReferrer"
},
{
"code": 6035,
"name": "InvalidOracle",
"msg": "InvalidOracle"
},
{
"code": 6036,
"name": "OracleNotFound",
"msg": "OracleNotFound"
},
{
"code": 6037,
"name": "LiquidationsBlockedByOracle",
"msg": "Liquidations Blocked By Oracle"
},
{
"code": 6038,
"name": "MaxDeposit",
"msg": "Can not deposit more than max deposit"
},
{
"code": 6039,
"name": "CantDeleteUserWithCollateral",
"msg": "Can not delete user that still has collateral"
},
{
"code": 6040,
"name": "InvalidFundingProfitability",
"msg": "AMM funding out of bounds pnl"
},
{
"code": 6041,
"name": "CastingFailure",
"msg": "Casting Failure"
},
{
"code": 6042,
"name": "InvalidOrder",
"msg": "InvalidOrder"
},
{
"code": 6043,
"name": "InvalidOrderMaxTs",
"msg": "InvalidOrderMaxTs"
},
{
"code": 6044,
"name": "InvalidOrderMarketType",
"msg": "InvalidOrderMarketType"
},
{
"code": 6045,
"name": "InvalidOrderForInitialMarginReq",
"msg": "InvalidOrderForInitialMarginReq"
},
{
"code": 6046,
"name": "InvalidOrderNotRiskReducing",
"msg": "InvalidOrderNotRiskReducing"
},
{
"code": 6047,
"name": "InvalidOrderSizeTooSmall",
"msg": "InvalidOrderSizeTooSmall"
},
{
"code": 6048,
"name": "InvalidOrderNotStepSizeMultiple",
"msg": "InvalidOrderNotStepSizeMultiple"
},
{
"code": 6049,
"name": "InvalidOrderBaseQuoteAsset",
"msg": "InvalidOrderBaseQuoteAsset"
},
{
"code": 6050,
"name": "InvalidOrderIOC",
"msg": "InvalidOrderIOC"
},
{
"code": 6051,
"name": "InvalidOrderPostOnly",
"msg": "InvalidOrderPostOnly"
},
{
"code": 6052,
"name": "InvalidOrderIOCPostOnly",
"msg": "InvalidOrderIOCPostOnly"
},
{
"code": 6053,
"name": "InvalidOrderTrigger",
"msg": "InvalidOrderTrigger"
},
{
"code": 6054,
"name": "InvalidOrderAuction",
"msg": "InvalidOrderAuction"
},
{
"code": 6055,
"name": "InvalidOrderOracleOffset",
"msg": "InvalidOrderOracleOffset"
},
{
"code": 6056,
"name": "InvalidOrderMinOrderSize",
"msg": "InvalidOrderMinOrderSize"
},
{
"code": 6057,
"name": "PlacePostOnlyLimitFailure",
"msg": "Failed to Place Post-Only Limit Order"
},
{
"code": 6058,
"name": "UserHasNoOrder",
"msg": "User has no order"
},
{
"code": 6059,
"name": "OrderAmountTooSmall",
"msg": "Order Amount Too Small"
},
{
"code": 6060,
"name": "MaxNumberOfOrders",
"msg": "Max number of orders taken"
},
{
"code": 6061,
"name": "OrderDoesNotExist",
"msg": "Order does not exist"
},
{
"code": 6062,
"name": "OrderNotOpen",
"msg": "Order not open"
},
{
"code": 6063,
"name": "FillOrderDidNotUpdateState",
"msg": "FillOrderDidNotUpdateState"
},
{
"code": 6064,
"name": "ReduceOnlyOrderIncreasedRisk",
"msg": "Reduce only order increased risk"
},
{
"code": 6065,
"name": "UnableToLoadAccountLoader",
"msg": "Unable to load AccountLoader"
},
{
"code": 6066,
"name": "TradeSizeTooLarge",
"msg": "Trade Size Too Large"
},
{
"code": 6067,
"name": "UserCantReferThemselves",
"msg": "User cant refer themselves"
},
{
"code": 6068,
"name": "DidNotReceiveExpectedReferrer",
"msg": "Did not receive expected referrer"
},
{
"code": 6069,
"name": "CouldNotDeserializeReferrer",
"msg": "Could not deserialize referrer"
},
{
"code": 6070,
"name": "CouldNotDeserializeReferrerStats",
"msg": "Could not deserialize referrer stats"
},
{
"code": 6071,
"name": "UserOrderIdAlreadyInUse",
"msg": "User Order Id Already In Use"
},
{
"code": 6072,
"name": "NoPositionsLiquidatable",
"msg": "No positions liquidatable"
},
{
"code": 6073,
"name": "InvalidMarginRatio",
"msg": "Invalid Margin Ratio"
},
{
"code": 6074,
"name": "CantCancelPostOnlyOrder",
"msg": "Cant Cancel Post Only Order"
},
{
"code": 6075,
"name": "InvalidOracleOffset",
"msg": "InvalidOracleOffset"
},
{
"code": 6076,
"name": "CantExpireOrders",
"msg": "CantExpireOrders"
},
{
"code": 6077,
"name": "CouldNotLoadMarketData",
"msg": "CouldNotLoadMarketData"
},
{
"code": 6078,
"name": "PerpMarketNotFound",
"msg": "PerpMarketNotFound"
},
{
"code": 6079,
"name": "InvalidMarketAccount",
"msg": "InvalidMarketAccount"
},
{
"code": 6080,
"name": "UnableToLoadPerpMarketAccount",
"msg": "UnableToLoadMarketAccount"
},
{
"code": 6081,
"name": "MarketWrongMutability",
"msg": "MarketWrongMutability"
},
{
"code": 6082,
"name": "UnableToCastUnixTime",
"msg": "UnableToCastUnixTime"
},
{
"code": 6083,
"name": "CouldNotFindSpotPosition",
"msg": "CouldNotFindSpotPosition"
},
{
"code": 6084,
"name": "NoSpotPositionAvailable",
"msg": "NoSpotPositionAvailable"
},
{
"code": 6085,
"name": "InvalidSpotMarketInitialization",
"msg": "InvalidSpotMarketInitialization"
},
{
"code": 6086,
"name": "CouldNotLoadSpotMarketData",
"msg": "CouldNotLoadSpotMarketData"
},
{
"code": 6087,
"name": "SpotMarketNotFound",
"msg": "SpotMarketNotFound"
},
{
"code": 6088,
"name": "InvalidSpotMarketAccount",
"msg": "InvalidSpotMarketAccount"
},
{
"code": 6089,
"name": "UnableToLoadSpotMarketAccount",
"msg": "UnableToLoadSpotMarketAccount"
},
{
"code": 6090,
"name": "SpotMarketWrongMutability",
"msg": "SpotMarketWrongMutability"
},
{
"code": 6091,
"name": "SpotMarketInterestNotUpToDate",
"msg": "SpotInterestNotUpToDate"
},
{
"code": 6092,
"name": "SpotMarketInsufficientDeposits",
"msg": "SpotMarketInsufficientDeposits"
},
{
"code": 6093,
"name": "UserMustSettleTheirOwnPositiveUnsettledPNL",
"msg": "UserMustSettleTheirOwnPositiveUnsettledPNL"
},
{
"code": 6094,
"name": "CantUpdatePoolBalanceType",
"msg": "CantUpdatePoolBalanceType"
},
{
"code": 6095,
"name": "InsufficientCollateralForSettlingPNL",
"msg": "InsufficientCollateralForSettlingPNL"
},
{
"code": 6096,
"name": "AMMNotUpdatedInSameSlot",
"msg": "AMMNotUpdatedInSameSlot"
},
{
"code": 6097,
"name": "AuctionNotComplete",
"msg": "AuctionNotComplete"
},
{
"code": 6098,
"name": "MakerNotFound",
"msg": "MakerNotFound"
},
{
"code": 6099,
"name": "MakerStatsNotFound",
"msg": "MakerNotFound"
},
{
"code": 6100,
"name": "MakerMustBeWritable",
"msg": "MakerMustBeWritable"
},
{
"code": 6101,
"name": "MakerStatsMustBeWritable",
"msg": "MakerMustBeWritable"
},
{
"code": 6102,
"name": "MakerOrderNotFound",
"msg": "MakerOrderNotFound"
},
{
"code": 6103,
"name": "CouldNotDeserializeMaker",
"msg": "CouldNotDeserializeMaker"
},
{
"code": 6104,
"name": "CouldNotDeserializeMakerStats",
"msg": "CouldNotDeserializeMaker"
},
{
"code": 6105,
"name": "AuctionPriceDoesNotSatisfyMaker",
"msg": "AuctionPriceDoesNotSatisfyMaker"
},
{
"code": 6106,
"name": "MakerCantFulfillOwnOrder",
"msg": "MakerCantFulfillOwnOrder"
},
{
"code": 6107,
"name": "MakerOrderMustBePostOnly",
"msg": "MakerOrderMustBePostOnly"
},
{
"code": 6108,
"name": "CantMatchTwoPostOnlys",
"msg": "CantMatchTwoPostOnlys"
},
{
"code": 6109,
"name": "OrderBreachesOraclePriceLimits",
"msg": "OrderBreachesOraclePriceLimits"
},
{
"code": 6110,
"name": "OrderMustBeTriggeredFirst",
"msg": "OrderMustBeTriggeredFirst"
},
{
"code": 6111,
"name": "OrderNotTriggerable",
"msg": "OrderNotTriggerable"
},
{
"code": 6112,
"name": "OrderDidNotSatisfyTriggerCondition",
"msg": "OrderDidNotSatisfyTriggerCondition"
},
{
"code": 6113,
"name": "PositionAlreadyBeingLiquidated",
"msg": "PositionAlreadyBeingLiquidated"
},
{
"code": 6114,
"name": "PositionDoesntHaveOpenPositionOrOrders",
"msg": "PositionDoesntHaveOpenPositionOrOrders"
},
{
"code": 6115,
"name": "AllOrdersAreAlreadyLiquidations",
"msg": "AllOrdersAreAlreadyLiquidations"
},
{
"code": 6116,
"name": "CantCancelLiquidationOrder",
"msg": "CantCancelLiquidationOrder"
},
{
"code": 6117,
"name": "UserIsBeingLiquidated",
"msg": "UserIsBeingLiquidated"
},
{
"code": 6118,
"name": "LiquidationsOngoing",
"msg": "LiquidationsOngoing"
},
{
"code": 6119,
"name": "WrongSpotBalanceType",
"msg": "WrongSpotBalanceType"
},
{
"code": 6120,
"name": "UserCantLiquidateThemself",
"msg": "UserCantLiquidateThemself"
},
{
"code": 6121,
"name": "InvalidPerpPositionToLiquidate",
"msg": "InvalidPerpPositionToLiquidate"
},
{
"code": 6122,
"name": "InvalidBaseAssetAmountForLiquidatePerp",
"msg": "InvalidBaseAssetAmountForLiquidatePerp"
},
{
"code": 6123,
"name": "InvalidPositionLastFundingRate",
"msg": "InvalidPositionLastFundingRate"
},
{
"code": 6124,
"name": "InvalidPositionDelta",
"msg": "InvalidPositionDelta"
},
{
"code": 6125,
"name": "UserBankrupt",
"msg": "UserBankrupt"
},
{
"code": 6126,
"name": "UserNotBankrupt",
"msg": "UserNotBankrupt"
},
{
"code": 6127,
"name": "UserHasInvalidBorrow",
"msg": "UserHasInvalidBorrow"
},
{
"code": 6128,
"name": "DailyWithdrawLimit",
"msg": "DailyWithdrawLimit"
},
{
"code": 6129,
"name": "DefaultError",
"msg": "DefaultError"
},
{
"code": 6130,
"name": "InsufficientLPTokens",
"msg": "Insufficient LP tokens"
},
{
"code": 6131,
"name": "CantLPWithPerpPosition",
"msg": "Cant LP with a market position"
},
{
"code": 6132,
"name": "UnableToBurnLPTokens",
"msg": "Unable to burn LP tokens"
},
{
"code": 6133,
"name": "TryingToRemoveLiquidityTooFast",
"msg": "Trying to remove liqudity too fast after adding it"
},
{
"code": 6134,
"name": "InvalidSpotMarketVault",
"msg": "Invalid Spot Market Vault"
},
{
"code": 6135,
"name": "InvalidSpotMarketState",
"msg": "Invalid Spot Market State"
},
{
"code": 6136,
"name": "InvalidSerumProgram",
"msg": "InvalidSerumProgram"
},
{
"code": 6137,
"name": "InvalidSerumMarket",
"msg": "InvalidSerumMarket"
},
{
"code": 6138,
"name": "InvalidSerumBids",
"msg": "InvalidSerumBids"
},
{
"code": 6139,
"name": "InvalidSerumAsks",
"msg": "InvalidSerumAsks"
},
{
"code": 6140,
"name": "InvalidSerumOpenOrders",
"msg": "InvalidSerumOpenOrders"
},
{
"code": 6141,
"name": "FailedSerumCPI",
"msg": "FailedSerumCPI"
},
{
"code": 6142,
"name": "FailedToFillOnExternalMarket",
"msg": "FailedToFillOnExternalMarket"
},
{
"code": 6143,
"name": "InvalidFulfillmentConfig",
"msg": "InvalidFulfillmentConfig"
},
{
"code": 6144,
"name": "InvalidFeeStructure",
"msg": "InvalidFeeStructure"
},
{
"code": 6145,
"name": "InsufficientIFShares",
"msg": "Insufficient IF shares"
},
{
"code": 6146,
"name": "MarketActionPaused",
"msg": "the Market has paused this action"
},
{
"code": 6147,
"name": "MarketPlaceOrderPaused",
"msg": "the Market status doesnt allow placing orders"
},
{
"code": 6148,
"name": "MarketFillOrderPaused",
"msg": "the Market status doesnt allow filling orders"
},
{
"code": 6149,
"name": "MarketWithdrawPaused",
"msg": "the Market status doesnt allow withdraws"
},
{
"code": 6150,
"name": "ProtectedAssetTierViolation",
"msg": "Action violates the Protected Asset Tier rules"
},
{
"code": 6151,
"name": "IsolatedAssetTierViolation",
"msg": "Action violates the Isolated Asset Tier rules"
},
{
"code": 6152,
"name": "UserCantBeDeleted",
"msg": "User Cant Be Deleted"
},
{
"code": 6153,
"name": "ReduceOnlyWithdrawIncreasedRisk",
"msg": "Reduce Only Withdraw Increased Risk"
},
{
"code": 6154,
"name": "MaxOpenInterest",
"msg": "Max Open Interest"
},
{
"code": 6155,
"name": "CantResolvePerpBankruptcy",
"msg": "Cant Resolve Perp Bankruptcy"
},
{
"code": 6156,
"name": "LiquidationDoesntSatisfyLimitPrice",
"msg": "Liquidation Doesnt Satisfy Limit Price"
},
{
"code": 6157,
"name": "MarginTradingDisabled",
"msg": "Margin Trading Disabled"
},
{
"code": 6158,
"name": "InvalidMarketStatusToSettlePnl",
"msg": "Invalid Market Status to Settle Perp Pnl"
},
{
"code": 6159,
"name": "PerpMarketNotInSettlement",
"msg": "PerpMarketNotInSettlement"
},
{
"code": 6160,
"name": "PerpMarketNotInReduceOnly",
"msg": "PerpMarketNotInReduceOnly"
},
{
"code": 6161,
"name": "PerpMarketSettlementBufferNotReached",
"msg": "PerpMarketSettlementBufferNotReached"
},
{
"code": 6162,
"name": "PerpMarketSettlementUserHasOpenOrders",
"msg": "PerpMarketSettlementUserHasOpenOrders"
},
{
"code": 6163,
"name": "PerpMarketSettlementUserHasActiveLP",
"msg": "PerpMarketSettlementUserHasActiveLP"
},
{
"code": 6164,
"name": "UnableToSettleExpiredUserPosition",
"msg": "UnableToSettleExpiredUserPosition"
},
{
"code": 6165,
"name": "UnequalMarketIndexForSpotTransfer",
"msg": "UnequalMarketIndexForSpotTransfer"
},
{
"code": 6166,
"name": "InvalidPerpPositionDetected",
"msg": "InvalidPerpPositionDetected"
},
{
"code": 6167,
"name": "InvalidSpotPositionDetected",
"msg": "InvalidSpotPositionDetected"
},
{
"code": 6168,
"name": "InvalidAmmDetected",
"msg": "InvalidAmmDetected"
},
{
"code": 6169,
"name": "InvalidAmmForFillDetected",
"msg": "InvalidAmmForFillDetected"
},
{
"code": 6170,
"name": "InvalidAmmLimitPriceOverride",
"msg": "InvalidAmmLimitPriceOverride"
},
{
"code": 6171,
"name": "InvalidOrderFillPrice",
"msg": "InvalidOrderFillPrice"
},
{
"code": 6172,
"name": "SpotMarketBalanceInvariantViolated",
"msg": "SpotMarketBalanceInvariantViolated"
},
{
"code": 6173,
"name": "SpotMarketVaultInvariantViolated",
"msg": "SpotMarketVaultInvariantViolated"
},
{
"code": 6174,
"name": "InvalidPDA",
"msg": "InvalidPDA"
},
{
"code": 6175,
"name": "InvalidPDASigner",
"msg": "InvalidPDASigner"
},
{
"code": 6176,
"name": "RevenueSettingsCannotSettleToIF",
"msg": "RevenueSettingsCannotSettleToIF"
},
{
"code": 6177,
"name": "NoRevenueToSettleToIF",
"msg": "NoRevenueToSettleToIF"
},
{
"code": 6178,
"name": "NoAmmPerpPnlDeficit",
"msg": "NoAmmPerpPnlDeficit"
},
{
"code": 6179,
"name": "SufficientPerpPnlPool",
"msg": "SufficientPerpPnlPool"
},
{
"code": 6180,
"name": "InsufficientPerpPnlPool",
"msg": "InsufficientPerpPnlPool"
},
{
"code": 6181,
"name": "PerpPnlDeficitBelowThreshold",
"msg": "PerpPnlDeficitBelowThreshold"
},
{
"code": 6182,
"name": "MaxRevenueWithdrawPerPeriodReached",
"msg": "MaxRevenueWithdrawPerPeriodReached"
},
{
"code": 6183,
"name": "MaxIFWithdrawReached",
"msg": "InvalidSpotPositionDetected"
},
{
"code": 6184,
"name": "NoIFWithdrawAvailable",
"msg": "NoIFWithdrawAvailable"
},
{
"code": 6185,
"name": "InvalidIFUnstake",
"msg": "InvalidIFUnstake"
},
{
"code": 6186,
"name": "InvalidIFUnstakeSize",
"msg": "InvalidIFUnstakeSize"
},
{
"code": 6187,
"name": "InvalidIFUnstakeCancel",
"msg": "InvalidIFUnstakeCancel"
},
{
"code": 6188,
"name": "InvalidIFForNewStakes",
"msg": "InvalidIFForNewStakes"
},
{
"code": 6189,
"name": "InvalidIFRebase",
"msg": "InvalidIFRebase"
},
{
"code": 6190,
"name": "InvalidInsuranceUnstakeSize",
"msg": "InvalidInsuranceUnstakeSize"
},
{
"code": 6191,
"name": "InvalidOrderLimitPrice",
"msg": "InvalidOrderLimitPrice"
},
{
"code": 6192,
"name": "InvalidIFDetected",
"msg": "InvalidIFDetected"
},
{
"code": 6193,
"name": "InvalidAmmMaxSpreadDetected",
"msg": "InvalidAmmMaxSpreadDetected"
},
{
"code": 6194,
"name": "InvalidConcentrationCoef",
"msg": "InvalidConcentrationCoef"
},
{
"code": 6195,
"name": "InvalidSrmVault",
"msg": "InvalidSrmVault"
},
{
"code": 6196,
"name": "InvalidVaultOwner",
"msg": "InvalidVaultOwner"
},
{
"code": 6197,
"name": "InvalidMarketStatusForFills",
"msg": "InvalidMarketStatusForFills"
},
{
"code": 6198,
"name": "IFWithdrawRequestInProgress",
"msg": "IFWithdrawRequestInProgress"
},
{
"code": 6199,
"name": "NoIFWithdrawRequestInProgress",
"msg": "NoIFWithdrawRequestInProgress"
},
{
"code": 6200,
"name": "IFWithdrawRequestTooSmall",
"msg": "IFWithdrawRequestTooSmall"
},
{
"code": 6201,
"name": "IncorrectSpotMarketAccountPassed",
"msg": "IncorrectSpotMarketAccountPassed"
},
{
"code": 6202,
"name": "BlockchainClockInconsistency",
"msg": "BlockchainClockInconsistency"
},
{
"code": 6203,
"name": "InvalidIFSharesDetected",
"msg": "InvalidIFSharesDetected"
},
{
"code": 6204,
"name": "NewLPSizeTooSmall",
"msg": "NewLPSizeTooSmall"
},
{
"code": 6205,
"name": "MarketStatusInvalidForNewLP",
"msg": "MarketStatusInvalidForNewLP"
},
{
"code": 6206,
"name": "InvalidMarkTwapUpdateDetected",
"msg": "InvalidMarkTwapUpdateDetected"
},
{
"code": 6207,
"name": "MarketSettlementAttemptOnActiveMarket",
"msg": "MarketSettlementAttemptOnActiveMarket"
},
{
"code": 6208,
"name": "MarketSettlementRequiresSettledLP",
"msg": "MarketSettlementRequiresSettledLP"
},
{
"code": 6209,
"name": "MarketSettlementAttemptTooEarly",
"msg": "MarketSettlementAttemptTooEarly"
},
{
"code": 6210,
"name": "MarketSettlementTargetPriceInvalid",
"msg": "MarketSettlementTargetPriceInvalid"
},
{
"code": 6211,
"name": "UnsupportedSpotMarket",
"msg": "UnsupportedSpotMarket"
},
{
"code": 6212,
"name": "SpotOrdersDisabled",
"msg": "SpotOrdersDisabled"
},
{
"code": 6213,
"name": "MarketBeingInitialized",
"msg": "Market Being Initialized"
},
{
"code": 6214,
"name": "InvalidUserSubAccountId",
"msg": "Invalid Sub Account Id"
},
{
"code": 6215,
"name": "InvalidTriggerOrderCondition",
"msg": "Invalid Trigger Order Condition"
},
{
"code": 6216,
"name": "InvalidSpotPosition",
"msg": "Invalid Spot Position"
},
{
"code": 6217,
"name": "CantTransferBetweenSameUserAccount",
"msg": "Cant transfer between same user account"
},
{
"code": 6218,
"name": "InvalidPerpPosition",
"msg": "Invalid Perp Position"
},
{
"code": 6219,
"name": "UnableToGetLimitPrice",
"msg": "Unable To Get Limit Price"
},
{
"code": 6220,
"name": "InvalidLiquidation",
"msg": "Invalid Liquidation"
},
{
"code": 6221,
"name": "SpotFulfillmentConfigDisabled",
"msg": "Spot Fulfillment Config Disabled"
},
{
"code": 6222,
"name": "InvalidMaker",
"msg": "Invalid Maker"
},
{
"code": 6223,
"name": "FailedUnwrap",
"msg": "Failed Unwrap"
},
{
"code": 6224,
"name": "MaxNumberOfUsers",
"msg": "Max Number Of Users"
},
{
"code": 6225,
"name": "InvalidOracleForSettlePnl",
"msg": "InvalidOracleForSettlePnl"
},
{
"code": 6226,
"name": "MarginOrdersOpen",
"msg": "MarginOrdersOpen"
},
{
"code": 6227,
"name": "TierViolationLiquidatingPerpPnl",
"msg": "TierViolationLiquidatingPerpPnl"
},
{
"code": 6228,
"name": "CouldNotLoadUserData",
"msg": "CouldNotLoadUserData"
},
{
"code": 6229,
"name": "UserWrongMutability",
"msg": "UserWrongMutability"
},
{
"code": 6230,
"name": "InvalidUserAccount",
"msg": "InvalidUserAccount"
},
{
"code": 6231,
"name": "CouldNotLoadUserStatsData",
"msg": "CouldNotLoadUserData"
},
{
"code": 6232,
"name": "UserStatsWrongMutability",
"msg": "UserWrongMutability"
},
{
"code": 6233,
"name": "InvalidUserStatsAccount",
"msg": "InvalidUserAccount"
},
{
"code": 6234,
"name": "UserNotFound",
"msg": "UserNotFound"
},
{
"code": 6235,
"name": "UnableToLoadUserAccount",
"msg": "UnableToLoadUserAccount"
},
{
"code": 6236,
"name": "UserStatsNotFound",
"msg": "UserStatsNotFound"
},
{
"code": 6237,
"name": "UnableToLoadUserStatsAccount",
"msg": "UnableToLoadUserStatsAccount"
},
{
"code": 6238,
"name": "UserNotInactive",
"msg": "User Not Inactive"
},
{
"code": 6239,
"name": "RevertFill",
"msg": "RevertFill"
},
{
"code": 6240,
"name": "InvalidMarketAccountforDeletion",
"msg": "Invalid MarketAccount for Deletion"
},
{
"code": 6241,
"name": "InvalidSpotFulfillmentParams",
"msg": "Invalid Spot Fulfillment Params"
},
{
"code": 6242,
"name": "FailedToGetMint",
"msg": "Failed to Get Mint"
},
{
"code": 6243,
"name": "FailedPhoenixCPI",
"msg": "FailedPhoenixCPI"
},
{
"code": 6244,
"name": "FailedToDeserializePhoenixMarket",
"msg": "FailedToDeserializePhoenixMarket"
},
{
"code": 6245,
"name": "InvalidPricePrecision",
"msg": "InvalidPricePrecision"
},
{
"code": 6246,
"name": "InvalidPhoenixProgram",
"msg": "InvalidPhoenixProgram"
},
{
"code": 6247,
"name": "InvalidPhoenixMarket",
"msg": "InvalidPhoenixMarket"
},
{
"code": 6248,
"name": "InvalidSwap",
"msg": "InvalidSwap"
},
{
"code": 6249,
"name": "SwapLimitPriceBreached",
"msg": "SwapLimitPriceBreached"
},
{
"code": 6250,
"name": "SpotMarketReduceOnly",
"msg": "SpotMarketReduceOnly"
},
{
"code": 6251,
"name": "FundingWasNotUpdated",
"msg": "FundingWasNotUpdated"
},
{
"code": 6252,
"name": "ImpossibleFill",
"msg": "ImpossibleFill"
},
{
"code": 6253,
"name": "CantUpdatePerpBidAskTwap",
"msg": "CantUpdatePerpBidAskTwap"
},
{
"code": 6254,
"name": "UserReduceOnly",
"msg": "UserReduceOnly"
},
{
"code": 6255,
"name": "InvalidMarginCalculation",
"msg": "InvalidMarginCalculation"
},
{
"code": 6256,
"name": "CantPayUserInitFee",
"msg": "CantPayUserInitFee"
},
{
"code": 6257,
"name": "CantReclaimRent",
"msg": "CantReclaimRent"
},
{
"code": 6258,
"name": "InsuranceFundOperationPaused",
"msg": "InsuranceFundOperationPaused"
},
{
"code": 6259,
"name": "NoUnsettledPnl",
"msg": "NoUnsettledPnl"
},
{
"code": 6260,
"name": "PnlPoolCantSettleUser",
"msg": "PnlPoolCantSettleUser"
},
{
"code": 6261,
"name": "OracleNonPositive",
"msg": "OracleInvalid"
},
{
"code": 6262,
"name": "OracleTooVolatile",
"msg": "OracleTooVolatile"
},
{
"code": 6263,
"name": "OracleTooUncertain",
"msg": "OracleTooUncertain"
},
{
"code": 6264,
"name": "OracleStaleForMargin",
"msg": "OracleStaleForMargin"
},
{
"code": 6265,
"name": "OracleInsufficientDataPoints",
"msg": "OracleInsufficientDataPoints"
},
{
"code": 6266,
"name": "OracleStaleForAMM",
"msg": "OracleStaleForAMM"
},
{
"code": 6267,
"name": "UnableToParsePullOracleMessage",
"msg": "Unable to parse pull oracle message"
},
{
"code": 6268,
"name": "MaxBorrows",
"msg": "Can not borow more than max borrows"
},
{
"code": 6269,
"name": "OracleUpdatesNotMonotonic",
"msg": "Updates must be monotonically increasing"
},
{
"code": 6270,
"name": "OraclePriceFeedMessageMismatch",
"msg": "Trying to update price feed with the wrong feed id"
},
{
"code": 6271,
"name": "OracleUnsupportedMessageType",
"msg": "The message in the update must be a PriceFeedMessage"
},
{
"code": 6272,
"name": "OracleDeserializeMessageFailed",
"msg": "Could not deserialize the message in the update"
},
{
"code": 6273,
"name": "OracleWrongGuardianSetOwner",
"msg": "Wrong guardian set owner in update price atomic"
},
{
"code": 6274,
"name": "OracleWrongWriteAuthority",
"msg": "Oracle post update atomic price feed account must be drift program"
},
{
"code": 6275,
"name": "OracleWrongVaaOwner",
"msg": "Oracle vaa owner must be wormhole program"
},
{
"code": 6276,
"name": "OracleTooManyPriceAccountUpdates",
"msg": "Multi updates must have 2 or fewer accounts passed in remaining accounts"
},
{
"code": 6277,
"name": "OracleMismatchedVaaAndPriceUpdates",
"msg": "Don't have the same remaining accounts number and pyth updates left"
},
{
"code": 6278,
"name": "OracleBadRemainingAccountPublicKey",
"msg": "Remaining account passed does not match oracle update derived pda"
},
{
"code": 6279,
"name": "FailedOpenbookV2CPI",
"msg": "FailedOpenbookV2CPI"
},
{
"code": 6280,
"name": "InvalidOpenbookV2Program",
"msg": "InvalidOpenbookV2Program"
},
{
"code": 6281,
"name": "InvalidOpenbookV2Market",
"msg": "InvalidOpenbookV2Market"
},
{
"code": 6282,
"name": "NonZeroTransferFee",
"msg": "Non zero transfer fee"
},
{
"code": 6283,
"name": "LiquidationOrderFailedToFill",
"msg": "Liquidation order failed to fill"
},
{
"code": 6284,
"name": "InvalidPredictionMarketOrder",
"msg": "Invalid prediction market order"
},
{
"code": 6285,
"name": "InvalidVerificationIxIndex",
"msg": "Ed25519 Ix must be before place and make swift order ix"
},
{
"code": 6286,
"name": "SigVerificationFailed",
"msg": "Swift message verificaiton failed"
},
{
"code": 6287,
"name": "MismatchedSwiftOrderParamsMarketIndex",
"msg": "Market index mismatched b/w taker and maker swift order params"
},
{
"code": 6288,
"name": "InvalidSwiftOrderParam",
"msg": "Swift only available for market/oracle perp orders"
},
{
"code": 6289,
"name": "PlaceAndTakeOrderSuccessConditionFailed",
"msg": "Place and take order success condition failed"
},
{
"code": 6290,
"name": "InvalidHighLeverageModeConfig",
"msg": "Invalid High Leverage Mode Config"
},
{
"code": 6291,
"name": "InvalidRFQUserAccount",
"msg": "Invalid RFQ User Account"
},
{
"code": 6292,
"name": "RFQUserAccountWrongMutability",
"msg": "RFQUserAccount should be mutable"
},
{
"code": 6293,
"name": "RFQUserAccountFull",
"msg": "RFQUserAccount has too many active RFQs"
},
{
"code": 6294,
"name": "RFQOrderNotFilled",
"msg": "RFQ order not filled as expected"
},
{
"code": 6295,
"name": "InvalidRFQOrder",
"msg": "RFQ orders must be jit makers"
},
{
"code": 6296,
"name": "InvalidRFQMatch",
"msg": "RFQ matches must be valid"
},
{
"code": 6297,
"name": "InvalidSwiftUserAccount",
"msg": "Invalid swift user account"
},
{
"code": 6298,
"name": "SwiftUserAccountWrongMutability",
"msg": "Swift account wrong mutability"
},
{
"code": 6299,
"name": "SwiftUserOrdersAccountFull",
"msg": "SwiftUserAccount has too many active orders"
},
{
"code": 6300,
"name": "SwiftOrderDoesNotExist",
"msg": "Order with swift uuid does not exist"
},
{
"code": 6301,
"name": "InvalidSwiftOrderId",
"msg": "Swift order id cannot be 0s"
},
{
"code": 6302,
"name": "InvalidPoolId",
"msg": "Invalid pool id"
},
{
"code": 6303,
"name": "InvalidProtectedMakerModeConfig",
"msg": "Invalid Protected Maker Mode Config"
},
{
"code": 6304,
"name": "InvalidPythLazerStorageOwner",
"msg": "Invalid pyth lazer storage owner"
},
{
"code": 6305,
"name": "UnverifiedPythLazerMessage",
"msg": "Verification of pyth lazer message failed"
},
{
"code": 6306,
"name": "InvalidPythLazerMessage",
"msg": "Invalid pyth lazer message"
},
{
"code": 6307,
"name": "PythLazerMessagePriceFeedMismatch",
"msg": "Pyth lazer message does not correspond to correct fed id"
}
],
"metadata": {
"address": "dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH"
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/idl/switchboard.json
|
{
"version": "0.1.0",
"name": "switchboard_v2",
"instructions": [
{
"name": "viewVersion",
"accounts": [],
"args": []
},
{
"name": "aggregatorClose",
"accounts": [
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "permission",
"isMut": true,
"isSigner": false
},
{
"name": "lease",
"isMut": true,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "oracleQueue",
"isMut": false,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "solDest",
"isMut": false,
"isSigner": false
},
{
"name": "escrowDest",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "crank",
"isMut": true,
"isSigner": false,
"isOptional": true,
"docs": [
"Optional accounts"
]
},
{
"name": "dataBuffer",
"isMut": true,
"isSigner": false,
"isOptional": true
},
{
"name": "slidingWindow",
"isMut": true,
"isSigner": false,
"isOptional": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorCloseParams"
}
}
]
},
{
"name": "setBumps",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "SetBumpsParams"
}
}
]
},
{
"name": "aggregatorAddJob",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "job",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorAddJobParams"
}
}
]
},
{
"name": "aggregatorInit",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": false
},
{
"name": "queue",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorInitParams"
}
}
]
},
{
"name": "aggregatorFunctionUpsert",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "function",
"isMut": false,
"isSigner": false
},
{
"name": "functionEnclaveSigner",
"isMut": false,
"isSigner": true
},
{
"name": "verifier",
"isMut": false,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorFunctionUpsertParams"
}
}
]
},
{
"name": "aggregatorLock",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorLockParams"
}
}
]
},
{
"name": "aggregatorOpenRound",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "lease",
"isMut": true,
"isSigner": false
},
{
"name": "oracleQueue",
"isMut": true,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "permission",
"isMut": true,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "payoutWallet",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "dataBuffer",
"isMut": false,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorOpenRoundParams"
}
}
]
},
{
"name": "aggregatorRemoveJob",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "job",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorRemoveJobParams"
}
}
]
},
{
"name": "aggregatorSaveResult",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": true,
"isSigner": false
},
{
"name": "oracleAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "oracleQueue",
"isMut": false,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "feedPermission",
"isMut": true,
"isSigner": false
},
{
"name": "oraclePermission",
"isMut": false,
"isSigner": false
},
{
"name": "lease",
"isMut": true,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "historyBuffer",
"isMut": true,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorSaveResultParams"
}
}
]
},
{
"name": "aggregatorSaveResultV2",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": true,
"isSigner": false
},
{
"name": "oracleAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "oracleQueue",
"isMut": false,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "feedPermission",
"isMut": true,
"isSigner": false
},
{
"name": "oraclePermission",
"isMut": false,
"isSigner": false
},
{
"name": "lease",
"isMut": true,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "historyBuffer",
"isMut": true,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorSaveResultParams"
}
}
]
},
{
"name": "aggregatorTeeSaveResult",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "oracle",
"isMut": true,
"isSigner": false
},
{
"name": "oracleAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "oracleQueue",
"isMut": false,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "feedPermission",
"isMut": true,
"isSigner": false
},
{
"name": "oraclePermission",
"isMut": false,
"isSigner": false
},
{
"name": "lease",
"isMut": true,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "historyBuffer",
"isMut": true,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
},
{
"name": "slider",
"isMut": true,
"isSigner": false
},
{
"name": "quote",
"isMut": false,
"isSigner": true
},
{
"name": "rewardWallet",
"isMut": true,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorTeeSaveResultParams"
}
}
]
},
{
"name": "aggregatorSetAuthority",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "newAuthority",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorSetAuthorityParams"
}
}
]
},
{
"name": "aggregatorSetConfig",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorSetConfigParams"
}
}
]
},
{
"name": "aggregatorSetResolutionMode",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "slidingWindow",
"isMut": true,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorSetResolutionModeParams"
}
}
]
},
{
"name": "aggregatorSetHistoryBuffer",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "buffer",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorSetHistoryBufferParams"
}
}
]
},
{
"name": "aggregatorSetQueue",
"accounts": [
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "queue",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "AggregatorSetQueueParams"
}
}
]
},
{
"name": "bufferRelayerInit",
"accounts": [
{
"name": "bufferRelayer",
"isMut": true,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": false
},
{
"name": "queue",
"isMut": false,
"isSigner": false
},
{
"name": "job",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "associatedTokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "BufferRelayerInitParams"
}
}
]
},
{
"name": "bufferRelayerOpenRound",
"accounts": [
{
"name": "bufferRelayer",
"isMut": true,
"isSigner": false
},
{
"name": "oracleQueue",
"isMut": true,
"isSigner": false
},
{
"name": "dataBuffer",
"isMut": true,
"isSigner": false
},
{
"name": "permission",
"isMut": true,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "BufferRelayerOpenRoundParams"
}
}
]
},
{
"name": "bufferRelayerSaveResult",
"accounts": [
{
"name": "bufferRelayer",
"isMut": true,
"isSigner": false
},
{
"name": "oracleAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
},
{
"name": "oracleQueue",
"isMut": true,
"isSigner": false
},
{
"name": "dataBuffer",
"isMut": true,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "permission",
"isMut": true,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "oracleWallet",
"isMut": true,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "BufferRelayerSaveResultParams"
}
}
]
},
{
"name": "crankInit",
"accounts": [
{
"name": "crank",
"isMut": true,
"isSigner": true
},
{
"name": "queue",
"isMut": false,
"isSigner": false
},
{
"name": "buffer",
"isMut": true,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "CrankInitParams"
}
}
]
},
{
"name": "crankPop",
"accounts": [
{
"name": "crank",
"isMut": true,
"isSigner": false
},
{
"name": "oracleQueue",
"isMut": true,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "payoutWallet",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "crankDataBuffer",
"isMut": true,
"isSigner": false
},
{
"name": "queueDataBuffer",
"isMut": false,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "CrankPopParams"
}
}
]
},
{
"name": "crankPopV2",
"accounts": [
{
"name": "crank",
"isMut": true,
"isSigner": false
},
{
"name": "oracleQueue",
"isMut": true,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "payoutWallet",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "crankDataBuffer",
"isMut": true,
"isSigner": false
},
{
"name": "queueDataBuffer",
"isMut": false,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "CrankPopParamsV2"
}
}
]
},
{
"name": "crankPush",
"accounts": [
{
"name": "crank",
"isMut": true,
"isSigner": false
},
{
"name": "aggregator",
"isMut": true,
"isSigner": false
},
{
"name": "oracleQueue",
"isMut": true,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "permission",
"isMut": false,
"isSigner": false
},
{
"name": "lease",
"isMut": true,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "dataBuffer",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "CrankPushParams"
}
}
]
},
{
"name": "jobInit",
"accounts": [
{
"name": "job",
"isMut": true,
"isSigner": true
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "JobInitParams"
}
}
]
},
{
"name": "jobSetData",
"accounts": [
{
"name": "job",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "JobSetDataParams"
}
}
]
},
{
"name": "leaseExtend",
"accounts": [
{
"name": "lease",
"isMut": true,
"isSigner": false
},
{
"name": "aggregator",
"isMut": false,
"isSigner": false
},
{
"name": "queue",
"isMut": false,
"isSigner": false
},
{
"name": "funder",
"isMut": true,
"isSigner": false
},
{
"name": "owner",
"isMut": true,
"isSigner": true
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "LeaseExtendParams"
}
}
]
},
{
"name": "leaseInit",
"accounts": [
{
"name": "lease",
"isMut": true,
"isSigner": false
},
{
"name": "queue",
"isMut": true,
"isSigner": false
},
{
"name": "aggregator",
"isMut": false,
"isSigner": false
},
{
"name": "funder",
"isMut": true,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "owner",
"isMut": true,
"isSigner": true
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "LeaseInitParams"
}
}
]
},
{
"name": "leaseSetAuthority",
"accounts": [
{
"name": "lease",
"isMut": true,
"isSigner": false
},
{
"name": "withdrawAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "newAuthority",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "LeaseSetAuthorityParams"
}
}
]
},
{
"name": "leaseWithdraw",
"accounts": [
{
"name": "lease",
"isMut": true,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "aggregator",
"isMut": false,
"isSigner": false
},
{
"name": "queue",
"isMut": false,
"isSigner": false
},
{
"name": "withdrawAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "withdrawAccount",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "LeaseWithdrawParams"
}
}
]
},
{
"name": "oracleHeartbeat",
"accounts": [
{
"name": "oracle",
"isMut": true,
"isSigner": false
},
{
"name": "oracleAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "tokenAccount",
"isMut": false,
"isSigner": false
},
{
"name": "gcOracle",
"isMut": true,
"isSigner": false
},
{
"name": "oracleQueue",
"isMut": true,
"isSigner": false
},
{
"name": "permission",
"isMut": false,
"isSigner": false
},
{
"name": "dataBuffer",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "OracleHeartbeatParams"
}
}
]
},
{
"name": "oracleTeeHeartbeat",
"accounts": [
{
"name": "oracle",
"isMut": true,
"isSigner": false
},
{
"name": "oracleAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "tokenAccount",
"isMut": false,
"isSigner": false
},
{
"name": "gcOracle",
"isMut": true,
"isSigner": false
},
{
"name": "oracleQueue",
"isMut": true,
"isSigner": false
},
{
"name": "permission",
"isMut": false,
"isSigner": false
},
{
"name": "dataBuffer",
"isMut": true,
"isSigner": false
},
{
"name": "quote",
"isMut": false,
"isSigner": true
},
{
"name": "programState",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "OracleTeeHeartbeatParams"
}
}
]
},
{
"name": "oracleInit",
"accounts": [
{
"name": "oracle",
"isMut": true,
"isSigner": false
},
{
"name": "oracleAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "wallet",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "queue",
"isMut": false,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "OracleInitParams"
}
}
]
},
{
"name": "oracleQueueInit",
"accounts": [
{
"name": "oracleQueue",
"isMut": true,
"isSigner": true
},
{
"name": "authority",
"isMut": false,
"isSigner": false
},
{
"name": "buffer",
"isMut": true,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "OracleQueueInitParams"
}
}
]
},
{
"name": "oracleQueueSetConfig",
"accounts": [
{
"name": "queue",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "OracleQueueSetConfigParams"
}
}
]
},
{
"name": "oracleWithdraw",
"accounts": [
{
"name": "oracle",
"isMut": true,
"isSigner": false
},
{
"name": "oracleAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "tokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "withdrawAccount",
"isMut": true,
"isSigner": false
},
{
"name": "oracleQueue",
"isMut": true,
"isSigner": false
},
{
"name": "permission",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "OracleWithdrawParams"
}
}
]
},
{
"name": "permissionInit",
"accounts": [
{
"name": "permission",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": false
},
{
"name": "granter",
"isMut": false,
"isSigner": false
},
{
"name": "grantee",
"isMut": false,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "PermissionInitParams"
}
}
]
},
{
"name": "permissionSet",
"accounts": [
{
"name": "permission",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "PermissionSetParams"
}
}
]
},
{
"name": "programConfig",
"accounts": [
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "programState",
"isMut": true,
"isSigner": false
},
{
"name": "daoMint",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "ProgramConfigParams"
}
}
]
},
{
"name": "programInit",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": false
},
{
"name": "tokenMint",
"isMut": true,
"isSigner": false
},
{
"name": "vault",
"isMut": true,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "daoMint",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "ProgramInitParams"
}
}
]
},
{
"name": "vaultTransfer",
"accounts": [
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "to",
"isMut": true,
"isSigner": false
},
{
"name": "vault",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VaultTransferParams"
}
}
]
},
{
"name": "vrfInit",
"accounts": [
{
"name": "vrf",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": false
},
{
"name": "oracleQueue",
"isMut": false,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VrfInitParams"
}
}
]
},
{
"name": "vrfCloseAction",
"accounts": [
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "vrf",
"isMut": true,
"isSigner": false
},
{
"name": "permission",
"isMut": true,
"isSigner": false
},
{
"name": "oracleQueue",
"isMut": false,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "solDest",
"isMut": false,
"isSigner": false
},
{
"name": "escrowDest",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VrfCloseParams"
}
}
]
},
{
"name": "vrfLiteCloseAction",
"accounts": [
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "vrfLite",
"isMut": true,
"isSigner": false
},
{
"name": "permission",
"isMut": true,
"isSigner": false
},
{
"name": "queue",
"isMut": false,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "solDest",
"isMut": false,
"isSigner": false
},
{
"name": "escrowDest",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VrfLiteCloseParams"
}
}
]
},
{
"name": "vrfLiteInit",
"accounts": [
{
"name": "authority",
"isMut": false,
"isSigner": false
},
{
"name": "vrf",
"isMut": true,
"isSigner": true
},
{
"name": "mint",
"isMut": false,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "queue",
"isMut": false,
"isSigner": false
},
{
"name": "permission",
"isMut": true,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "associatedTokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VrfLiteInitParams"
}
}
]
},
{
"name": "vrfLiteProveAndVerify",
"accounts": [
{
"name": "vrfLite",
"isMut": true,
"isSigner": false
},
{
"name": "callbackPid",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
},
{
"name": "oracleAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "oracleWallet",
"isMut": true,
"isSigner": false
},
{
"name": "instructionsSysvar",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VrfLiteProveAndVerifyParams"
}
}
]
},
{
"name": "vrfLiteRequestRandomness",
"accounts": [
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "vrfLite",
"isMut": true,
"isSigner": false
},
{
"name": "queue",
"isMut": true,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "dataBuffer",
"isMut": false,
"isSigner": false
},
{
"name": "permission",
"isMut": true,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "recentBlockhashes",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VrfLiteRequestRandomnessParams"
}
}
]
},
{
"name": "vrfPoolInit",
"accounts": [
{
"name": "authority",
"isMut": false,
"isSigner": false
},
{
"name": "vrfPool",
"isMut": true,
"isSigner": false
},
{
"name": "queue",
"isMut": false,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "associatedTokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VrfPoolInitParams"
}
}
]
},
{
"name": "vrfPoolRemove",
"accounts": [
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "vrfPool",
"isMut": true,
"isSigner": false
},
{
"name": "queue",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VrfPoolRemoveParams"
}
}
]
},
{
"name": "vrfPoolAdd",
"accounts": [
{
"name": "authority",
"isMut": false,
"isSigner": false
},
{
"name": "vrfPool",
"isMut": true,
"isSigner": false
},
{
"name": "vrfLite",
"isMut": true,
"isSigner": false
},
{
"name": "queue",
"isMut": false,
"isSigner": false
},
{
"name": "permission",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VrfPoolAddParams"
}
}
]
},
{
"name": "vrfPoolRequest",
"accounts": [
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "vrfPool",
"isMut": true,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
},
{
"name": "queue",
"isMut": true,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "dataBuffer",
"isMut": false,
"isSigner": false
},
{
"name": "recentBlockhashes",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VrfPoolRequestParams"
}
}
]
},
{
"name": "vrfProveAndVerify",
"accounts": [
{
"name": "vrf",
"isMut": true,
"isSigner": false
},
{
"name": "callbackPid",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "oracle",
"isMut": false,
"isSigner": false
},
{
"name": "oracleAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "oracleWallet",
"isMut": true,
"isSigner": false
},
{
"name": "instructionsSysvar",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VrfProveAndVerifyParams"
}
}
]
},
{
"name": "vrfRequestRandomness",
"accounts": [
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "vrf",
"isMut": true,
"isSigner": false
},
{
"name": "oracleQueue",
"isMut": true,
"isSigner": false
},
{
"name": "queueAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "dataBuffer",
"isMut": false,
"isSigner": false
},
{
"name": "permission",
"isMut": true,
"isSigner": false
},
{
"name": "escrow",
"isMut": true,
"isSigner": false
},
{
"name": "payerWallet",
"isMut": true,
"isSigner": false
},
{
"name": "payerAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "recentBlockhashes",
"isMut": false,
"isSigner": false
},
{
"name": "programState",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VrfRequestRandomnessParams"
}
}
]
},
{
"name": "vrfSetCallback",
"accounts": [
{
"name": "vrf",
"isMut": true,
"isSigner": false
},
{
"name": "authority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "VrfSetCallbackParams"
}
}
]
}
],
"accounts": [
{
"name": "SbState",
"type": {
"kind": "struct",
"fields": [
{
"name": "authority",
"docs": [
"The account authority permitted to make account changes."
],
"type": "publicKey"
},
{
"name": "tokenMint",
"docs": [
"The token mint used for oracle rewards, aggregator leases, and other reward incentives."
],
"type": "publicKey"
},
{
"name": "tokenVault",
"docs": [
"Token vault used by the program to receive kickbacks."
],
"type": "publicKey"
},
{
"name": "daoMint",
"docs": [
"The token mint used by the DAO."
],
"type": "publicKey"
},
{
"name": "bump",
"docs": [
"The PDA bump to derive the pubkey."
],
"type": "u8"
},
{
"name": "mrEnclaves",
"docs": [
"Permitted enclave measurements"
],
"type": {
"array": [
{
"array": [
"u8",
32
]
},
6
]
}
},
{
"name": "ebuf",
"docs": [
"Reserved for future info."
],
"type": {
"array": [
"u8",
799
]
}
}
]
}
},
{
"name": "TaskSpecRecord",
"type": {
"kind": "struct",
"fields": [
{
"name": "hash",
"type": {
"defined": "Hash"
}
}
]
}
},
{
"name": "AggregatorAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"docs": [
"Name of the aggregator to store on-chain."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "metadata",
"docs": [
"Metadata of the aggregator to store on-chain."
],
"type": {
"array": [
"u8",
128
]
}
},
{
"name": "reserved1",
"docs": [
"Reserved."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "queuePubkey",
"docs": [
"Pubkey of the queue the aggregator belongs to."
],
"type": "publicKey"
},
{
"name": "oracleRequestBatchSize",
"docs": [
"CONFIGS",
"Number of oracles assigned to an update request."
],
"type": "u32"
},
{
"name": "minOracleResults",
"docs": [
"Minimum number of oracle responses required before a round is validated."
],
"type": "u32"
},
{
"name": "minJobResults",
"docs": [
"Minimum number of job results before an oracle accepts a result."
],
"type": "u32"
},
{
"name": "minUpdateDelaySeconds",
"docs": [
"Minimum number of seconds required between aggregator rounds."
],
"type": "u32"
},
{
"name": "startAfter",
"docs": [
"Unix timestamp for which no feed update will occur before."
],
"type": "i64"
},
{
"name": "varianceThreshold",
"docs": [
"Change percentage required between a previous round and the current round. If variance percentage is not met, reject new oracle responses."
],
"type": {
"defined": "SwitchboardDecimal"
}
},
{
"name": "forceReportPeriod",
"docs": [
"Number of seconds for which, even if the variance threshold is not passed, accept new responses from oracles."
],
"type": "i64"
},
{
"name": "expiration",
"docs": [
"Timestamp when the feed is no longer needed."
],
"type": "i64"
},
{
"name": "consecutiveFailureCount",
"docs": [
"Counter for the number of consecutive failures before a feed is removed from a queue. If set to 0, failed feeds will remain on the queue."
],
"type": "u64"
},
{
"name": "nextAllowedUpdateTime",
"docs": [
"Timestamp when the next update request will be available."
],
"type": "i64"
},
{
"name": "isLocked",
"docs": [
"Flag for whether an aggregators configuration is locked for editing."
],
"type": "bool"
},
{
"name": "crankPubkey",
"docs": [
"Optional, public key of the crank the aggregator is currently using. Event based feeds do not need a crank."
],
"type": "publicKey"
},
{
"name": "latestConfirmedRound",
"docs": [
"Latest confirmed update request result that has been accepted as valid."
],
"type": {
"defined": "AggregatorRound"
}
},
{
"name": "currentRound",
"docs": [
"Oracle results from the current round of update request that has not been accepted as valid yet."
],
"type": {
"defined": "AggregatorRound"
}
},
{
"name": "jobPubkeysData",
"docs": [
"List of public keys containing the job definitions for how data is sourced off-chain by oracles."
],
"type": {
"array": [
"publicKey",
16
]
}
},
{
"name": "jobHashes",
"docs": [
"Used to protect against malicious RPC nodes providing incorrect task definitions to oracles before fulfillment."
],
"type": {
"array": [
{
"defined": "Hash"
},
16
]
}
},
{
"name": "jobPubkeysSize",
"docs": [
"Number of jobs assigned to an oracle."
],
"type": "u32"
},
{
"name": "jobsChecksum",
"docs": [
"Used to protect against malicious RPC nodes providing incorrect task definitions to oracles before fulfillment."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "authority",
"docs": [
"The account delegated as the authority for making account changes."
],
"type": "publicKey"
},
{
"name": "historyBuffer",
"docs": [
"Optional, public key of a history buffer account storing the last N accepted results and their timestamps."
],
"type": "publicKey"
},
{
"name": "previousConfirmedRoundResult",
"docs": [
"The previous confirmed round result."
],
"type": {
"defined": "SwitchboardDecimal"
}
},
{
"name": "previousConfirmedRoundSlot",
"docs": [
"The slot when the previous confirmed round was opened."
],
"type": "u64"
},
{
"name": "disableCrank",
"docs": [
"Whether an aggregator is permitted to join a crank."
],
"type": "bool"
},
{
"name": "jobWeights",
"docs": [
"Job weights used for the weighted median of the aggregator's assigned job accounts."
],
"type": {
"array": [
"u8",
16
]
}
},
{
"name": "creationTimestamp",
"docs": [
"Unix timestamp when the feed was created."
],
"type": "i64"
},
{
"name": "resolutionMode",
"docs": [
"Use sliding window or round based resolution",
"NOTE: This changes result propogation in latest_round_result"
],
"type": {
"defined": "AggregatorResolutionMode"
}
},
{
"name": "basePriorityFee",
"type": "u32"
},
{
"name": "priorityFeeBump",
"type": "u32"
},
{
"name": "priorityFeeBumpPeriod",
"type": "u32"
},
{
"name": "maxPriorityFeeMultiplier",
"type": "u32"
},
{
"name": "parentFunction",
"type": "publicKey"
},
{
"name": "ebuf",
"docs": [
"Reserved for future info."
],
"type": {
"array": [
"u8",
90
]
}
}
]
}
},
{
"name": "SlidingResultAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "data",
"type": {
"array": [
{
"defined": "SlidingWindowElement"
},
16
]
}
},
{
"name": "bump",
"type": "u8"
},
{
"name": "ebuf",
"type": {
"array": [
"u8",
512
]
}
}
]
}
},
{
"name": "PermissionAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "authority",
"docs": [
"The authority that is allowed to set permissions for this account."
],
"type": "publicKey"
},
{
"name": "permissions",
"docs": [
"The SwitchboardPermission enumeration assigned by the granter to the grantee."
],
"type": "u32"
},
{
"name": "granter",
"docs": [
"Public key of account that is granting permissions to use its resources."
],
"type": "publicKey"
},
{
"name": "grantee",
"docs": [
"Public key of account that is being assigned permissions to use a granters resources."
],
"type": "publicKey"
},
{
"name": "expiration",
"docs": [
"unused currently. may want permission PDA per permission for",
"unique expiration periods, BUT currently only one permission",
"per account makes sense for the infra. Dont over engineer."
],
"type": "i64"
},
{
"name": "bump",
"docs": [
"The PDA bump to derive the pubkey."
],
"type": "u8"
},
{
"name": "ebuf",
"docs": [
"Reserved for future info."
],
"type": {
"array": [
"u8",
255
]
}
}
]
}
},
{
"name": "RealmSpawnRecordAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "ebuf",
"type": {
"array": [
"u8",
256
]
}
}
]
}
},
{
"name": "LeaseAccountData",
"docs": [
"This should be any ccount that links a permission to an escrow"
],
"type": {
"kind": "struct",
"fields": [
{
"name": "escrow",
"docs": [
"Public key of the token account holding the lease contract funds until rewarded to oracles for successfully processing updates"
],
"type": "publicKey"
},
{
"name": "queue",
"docs": [
"Public key of the oracle queue that the lease contract is applicable for."
],
"type": "publicKey"
},
{
"name": "aggregator",
"docs": [
"Public key of the aggregator that the lease contract is applicable for"
],
"type": "publicKey"
},
{
"name": "tokenProgram",
"docs": [
"Public key of the Solana token program ID."
],
"type": "publicKey"
},
{
"name": "isActive",
"docs": [
"Whether the lease contract is still active."
],
"type": "bool"
},
{
"name": "crankRowCount",
"docs": [
"Index of an aggregators position on a crank."
],
"type": "u32"
},
{
"name": "createdAt",
"docs": [
"Timestamp when the lease contract was created."
],
"type": "i64"
},
{
"name": "updateCount",
"docs": [
"Counter keeping track of the number of updates for the given aggregator."
],
"type": "u128"
},
{
"name": "withdrawAuthority",
"docs": [
"Public key of keypair that may withdraw funds from the lease at any time"
],
"type": "publicKey"
},
{
"name": "bump",
"docs": [
"The PDA bump to derive the pubkey."
],
"type": "u8"
},
{
"name": "ebuf",
"type": {
"array": [
"u8",
255
]
}
}
]
}
},
{
"name": "OracleQueueAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"docs": [
"Name of the queue to store on-chain."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "metadata",
"docs": [
"Metadata of the queue to store on-chain."
],
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "authority",
"docs": [
"The account delegated as the authority for making account changes or assigning permissions targeted at the queue."
],
"type": "publicKey"
},
{
"name": "oracleTimeout",
"docs": [
"Interval when stale oracles will be removed if they fail to heartbeat."
],
"type": "u32"
},
{
"name": "reward",
"docs": [
"Rewards to provide oracles and round openers on this queue."
],
"type": "u64"
},
{
"name": "minStake",
"docs": [
"The minimum amount of stake oracles must present to remain on the queue."
],
"type": "u64"
},
{
"name": "slashingEnabled",
"docs": [
"Whether slashing is enabled on this queue."
],
"type": "bool"
},
{
"name": "varianceToleranceMultiplier",
"docs": [
"The tolerated variance amount oracle results can have from the accepted round result before being slashed.",
"slashBound = varianceToleranceMultiplier * stdDeviation Default: 2"
],
"type": {
"defined": "SwitchboardDecimal"
}
},
{
"name": "feedProbationPeriod",
"docs": [
"Number of update rounds new feeds are on probation for.",
"If a feed returns 429s within probation period, auto disable permissions."
],
"type": "u32"
},
{
"name": "currIdx",
"docs": [
"Current index of the oracle rotation."
],
"type": "u32"
},
{
"name": "size",
"docs": [
"Current number of oracles on a queue."
],
"type": "u32"
},
{
"name": "gcIdx",
"docs": [
"Garbage collection index."
],
"type": "u32"
},
{
"name": "consecutiveFeedFailureLimit",
"docs": [
"Consecutive failure limit for a feed before feed permission is revoked."
],
"type": "u64"
},
{
"name": "consecutiveOracleFailureLimit",
"docs": [
"Consecutive failure limit for an oracle before oracle permission is revoked."
],
"type": "u64"
},
{
"name": "unpermissionedFeedsEnabled",
"docs": [
"Enabling this setting means data feeds do not need explicit permission to join the queue and request new values from its oracles."
],
"type": "bool"
},
{
"name": "unpermissionedVrfEnabled",
"docs": [
"Enabling this setting means VRF accounts do not need explicit permission to join the queue and request new values from its oracles."
],
"type": "bool"
},
{
"name": "curatorRewardCut",
"docs": [
"TODO: Revenue percentage rewarded to job curators overall."
],
"type": {
"defined": "SwitchboardDecimal"
}
},
{
"name": "lockLeaseFunding",
"docs": [
"Prevent new leases from being funded n this queue.",
"Useful to turn down a queue for migrations, since authority is always immutable."
],
"type": "bool"
},
{
"name": "mint",
"docs": [
"Token mint used for the oracle queue rewards and slashing."
],
"type": "publicKey"
},
{
"name": "enableBufferRelayers",
"docs": [
"Whether oracles are permitted to fulfill buffer relayer update request."
],
"type": "bool"
},
{
"name": "enableTeeOnly",
"type": "bool"
},
{
"name": "ebuf",
"docs": [
"Reserved for future info."
],
"type": {
"array": [
"u8",
967
]
}
},
{
"name": "maxSize",
"docs": [
"Maximum number of oracles a queue can support."
],
"type": "u32"
},
{
"name": "dataBuffer",
"docs": [
"The public key of the OracleQueueBuffer account holding a collection of Oracle pubkeys that haver successfully heartbeated before the queues `oracleTimeout`."
],
"type": "publicKey"
}
]
}
},
{
"name": "CrankAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"docs": [
"Name of the crank to store on-chain."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "metadata",
"docs": [
"Metadata of the crank to store on-chain."
],
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "queuePubkey",
"docs": [
"Public key of the oracle queue who owns the crank."
],
"type": "publicKey"
},
{
"name": "pqSize",
"docs": [
"Number of aggregators added to the crank."
],
"type": "u32"
},
{
"name": "maxRows",
"docs": [
"Maximum number of aggregators allowed to be added to a crank."
],
"type": "u32"
},
{
"name": "jitterModifier",
"docs": [
"Pseudorandom value added to next aggregator update time."
],
"type": "u8"
},
{
"name": "ebuf",
"docs": [
"Reserved for future info."
],
"type": {
"array": [
"u8",
255
]
}
},
{
"name": "dataBuffer",
"docs": [
"The public key of the CrankBuffer account holding a collection of Aggregator pubkeys and their next allowed update time."
],
"type": "publicKey"
}
]
}
},
{
"name": "OracleAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"docs": [
"Name of the oracle to store on-chain."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "metadata",
"docs": [
"Metadata of the oracle to store on-chain."
],
"type": {
"array": [
"u8",
128
]
}
},
{
"name": "oracleAuthority",
"docs": [
"The account delegated as the authority for making account changes or withdrawing funds from a staking wallet."
],
"type": "publicKey"
},
{
"name": "lastHeartbeat",
"docs": [
"Unix timestamp when the oracle last heartbeated"
],
"type": "i64"
},
{
"name": "numInUse",
"docs": [
"Flag dictating if an oracle is active and has heartbeated before the queue's oracle timeout parameter."
],
"type": "u32"
},
{
"name": "tokenAccount",
"docs": [
"Stake account and reward/slashing wallet."
],
"type": "publicKey"
},
{
"name": "queuePubkey",
"docs": [
"Public key of the oracle queue who has granted it permission to use its resources."
],
"type": "publicKey"
},
{
"name": "metrics",
"docs": [
"Oracle track record."
],
"type": {
"defined": "OracleMetrics"
}
},
{
"name": "bump",
"docs": [
"The PDA bump to derive the pubkey."
],
"type": "u8"
},
{
"name": "ebuf",
"docs": [
"Reserved for future info."
],
"type": {
"array": [
"u8",
255
]
}
}
]
}
},
{
"name": "JobAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"docs": [
"Name of the job to store on-chain."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "metadata",
"docs": [
"Metadata of the job to store on-chain."
],
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "authority",
"docs": [
"The account delegated as the authority for making account changes."
],
"type": "publicKey"
},
{
"name": "expiration",
"docs": [
"Unix timestamp when the job is considered invalid"
],
"type": "i64"
},
{
"name": "hash",
"docs": [
"Hash of the serialized data to prevent tampering."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "data",
"docs": [
"Serialized protobuf containing the collection of task to retrieve data off-chain."
],
"type": "bytes"
},
{
"name": "referenceCount",
"docs": [
"The number of data feeds referencing the job account.."
],
"type": "u32"
},
{
"name": "totalSpent",
"docs": [
"The token amount funded into a feed that contains this job account."
],
"type": "u64"
},
{
"name": "createdAt",
"docs": [
"Unix timestamp when the job was created on-chain."
],
"type": "i64"
},
{
"name": "isInitializing",
"type": "u8"
}
]
}
},
{
"name": "VrfAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "status",
"docs": [
"The current status of the VRF account."
],
"type": {
"defined": "VrfStatus"
}
},
{
"name": "counter",
"docs": [
"Incremental counter for tracking VRF rounds."
],
"type": "u128"
},
{
"name": "authority",
"docs": [
"On-chain account delegated for making account changes."
],
"type": "publicKey"
},
{
"name": "oracleQueue",
"docs": [
"The OracleQueueAccountData that is assigned to fulfill VRF update request."
],
"type": "publicKey"
},
{
"name": "escrow",
"docs": [
"The token account used to hold funds for VRF update request."
],
"type": "publicKey"
},
{
"name": "callback",
"docs": [
"The callback that is invoked when an update request is successfully verified."
],
"type": {
"defined": "CallbackZC"
}
},
{
"name": "batchSize",
"docs": [
"The number of oracles assigned to a VRF update request."
],
"type": "u32"
},
{
"name": "builders",
"docs": [
"Struct containing the intermediate state between VRF crank actions."
],
"type": {
"array": [
{
"defined": "VrfBuilder"
},
8
]
}
},
{
"name": "buildersLen",
"docs": [
"The number of builders."
],
"type": "u32"
},
{
"name": "testMode",
"type": "bool"
},
{
"name": "currentRound",
"docs": [
"Oracle results from the current round of update request that has not been accepted as valid yet"
],
"type": {
"defined": "VrfRound"
}
},
{
"name": "ebuf",
"docs": [
"Reserved for future info."
],
"type": {
"array": [
"u8",
1024
]
}
}
]
}
},
{
"name": "VrfLiteAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"docs": [
"The bump used to derive the SbState account."
],
"type": "u8"
},
{
"name": "permissionBump",
"docs": [
"The bump used to derive the permission account."
],
"type": "u8"
},
{
"name": "vrfPool",
"docs": [
"The VrfPool the account belongs to."
],
"type": "publicKey"
},
{
"name": "status",
"docs": [
"The current status of the VRF account."
],
"type": {
"defined": "VrfStatus"
}
},
{
"name": "result",
"docs": [
"The VRF round result. Will be zeroized if still awaiting fulfillment."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "counter",
"docs": [
"Incremental counter for tracking VRF rounds."
],
"type": "u128"
},
{
"name": "alpha",
"docs": [
"The alpha bytes used to calculate the VRF proof."
],
"type": {
"array": [
"u8",
256
]
}
},
{
"name": "alphaLen",
"docs": [
"The number of bytes in the alpha buffer."
],
"type": "u32"
},
{
"name": "requestSlot",
"docs": [
"The Slot when the VRF round was opened."
],
"type": "u64"
},
{
"name": "requestTimestamp",
"docs": [
"The unix timestamp when the VRF round was opened."
],
"type": "i64"
},
{
"name": "authority",
"docs": [
"On-chain account delegated for making account changes."
],
"type": "publicKey"
},
{
"name": "queue",
"docs": [
"The OracleQueueAccountData that is assigned to fulfill VRF update request."
],
"type": "publicKey"
},
{
"name": "escrow",
"docs": [
"The token account used to hold funds for VRF update request."
],
"type": "publicKey"
},
{
"name": "callback",
"docs": [
"The callback that is invoked when an update request is successfully verified."
],
"type": {
"defined": "CallbackZC"
}
},
{
"name": "builder",
"docs": [
"The incremental VRF proof calculation."
],
"type": {
"defined": "VrfBuilder"
}
},
{
"name": "expiration",
"type": "i64"
},
{
"name": "ebuf",
"type": {
"array": [
"u8",
1024
]
}
}
]
}
},
{
"name": "VrfPoolAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "authority",
"docs": [
"ACCOUNTS"
],
"type": "publicKey"
},
{
"name": "queue",
"type": "publicKey"
},
{
"name": "escrow",
"type": "publicKey"
},
{
"name": "minInterval",
"type": "u32"
},
{
"name": "maxRows",
"type": "u32"
},
{
"name": "size",
"type": "u32"
},
{
"name": "idx",
"type": "u32"
},
{
"name": "stateBump",
"type": "u8"
},
{
"name": "ebuf",
"type": {
"array": [
"u8",
135
]
}
}
]
}
},
{
"name": "BufferRelayerAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"docs": [
"Name of the buffer account to store on-chain."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "queuePubkey",
"docs": [
"Public key of the OracleQueueAccountData that is currently assigned to fulfill buffer relayer update request."
],
"type": "publicKey"
},
{
"name": "escrow",
"docs": [
"Token account to reward oracles for completing update request."
],
"type": "publicKey"
},
{
"name": "authority",
"docs": [
"The account delegated as the authority for making account changes."
],
"type": "publicKey"
},
{
"name": "jobPubkey",
"docs": [
"Public key of the JobAccountData that defines how the buffer relayer is updated."
],
"type": "publicKey"
},
{
"name": "jobHash",
"docs": [
"Used to protect against malicious RPC nodes providing incorrect task definitions to oracles before fulfillment"
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "minUpdateDelaySeconds",
"docs": [
"Minimum delay between update request."
],
"type": "u32"
},
{
"name": "isLocked",
"docs": [
"Whether buffer relayer config is locked for further changes."
],
"type": "bool"
},
{
"name": "currentRound",
"docs": [
"The current buffer relayer update round that is yet to be confirmed."
],
"type": {
"defined": "BufferRelayerRound"
}
},
{
"name": "latestConfirmedRound",
"docs": [
"The latest confirmed buffer relayer update round."
],
"type": {
"defined": "BufferRelayerRound"
}
},
{
"name": "result",
"docs": [
"The buffer holding the latest confirmed result."
],
"type": "bytes"
}
]
}
}
],
"types": [
{
"name": "AggregatorAddJobParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "weight",
"type": {
"option": "u8"
}
}
]
}
},
{
"name": "AggregatorCloseParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"type": "u8"
},
{
"name": "permissionBump",
"type": "u8"
},
{
"name": "leaseBump",
"type": "u8"
}
]
}
},
{
"name": "AggregatorFunctionUpsertParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "value",
"type": {
"defined": "BorshDecimal"
}
}
]
}
},
{
"name": "AggregatorInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "metadata",
"type": {
"array": [
"u8",
128
]
}
},
{
"name": "batchSize",
"type": "u32"
},
{
"name": "minOracleResults",
"type": "u32"
},
{
"name": "minJobResults",
"type": "u32"
},
{
"name": "minUpdateDelaySeconds",
"type": "u32"
},
{
"name": "startAfter",
"type": "i64"
},
{
"name": "varianceThreshold",
"type": {
"defined": "BorshDecimal"
}
},
{
"name": "forceReportPeriod",
"type": "i64"
},
{
"name": "expiration",
"type": "i64"
},
{
"name": "stateBump",
"type": "u8"
},
{
"name": "disableCrank",
"type": "bool"
}
]
}
},
{
"name": "AggregatorLockParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "AggregatorOpenRoundParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"type": "u8"
},
{
"name": "leaseBump",
"type": "u8"
},
{
"name": "permissionBump",
"type": "u8"
},
{
"name": "jitter",
"type": "u8"
}
]
}
},
{
"name": "AggregatorRemoveJobParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "jobIdx",
"type": "u32"
}
]
}
},
{
"name": "AggregatorSaveResultParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "oracleIdx",
"type": "u32"
},
{
"name": "error",
"type": "bool"
},
{
"name": "value",
"type": {
"defined": "BorshDecimal"
}
},
{
"name": "jobsChecksum",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "minResponse",
"type": {
"defined": "BorshDecimal"
}
},
{
"name": "maxResponse",
"type": {
"defined": "BorshDecimal"
}
},
{
"name": "feedPermissionBump",
"type": "u8"
},
{
"name": "oraclePermissionBump",
"type": "u8"
},
{
"name": "leaseBump",
"type": "u8"
},
{
"name": "stateBump",
"type": "u8"
}
]
}
},
{
"name": "AggregatorSaveResultParamsV2",
"type": {
"kind": "struct",
"fields": [
{
"name": "oracleIdx",
"type": "u32"
},
{
"name": "error",
"type": "bool"
},
{
"name": "value",
"type": {
"defined": "BorshDecimal"
}
},
{
"name": "jobsChecksum",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "minResponse",
"type": {
"defined": "BorshDecimal"
}
},
{
"name": "maxResponse",
"type": {
"defined": "BorshDecimal"
}
},
{
"name": "feedPermissionBump",
"type": "u8"
},
{
"name": "oraclePermissionBump",
"type": "u8"
},
{
"name": "leaseBump",
"type": "u8"
},
{
"name": "stateBump",
"type": "u8"
},
{
"name": "jobValues",
"type": {
"vec": {
"option": {
"defined": "BorshDecimal"
}
}
}
}
]
}
},
{
"name": "AggregatorSetAuthorityParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "AggregatorSetBatchSizeParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "batchSize",
"type": "u32"
}
]
}
},
{
"name": "AggregatorSetConfigParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": {
"option": {
"array": [
"u8",
32
]
}
}
},
{
"name": "metadata",
"type": {
"option": {
"array": [
"u8",
128
]
}
}
},
{
"name": "minUpdateDelaySeconds",
"type": {
"option": "u32"
}
},
{
"name": "minJobResults",
"type": {
"option": "u32"
}
},
{
"name": "batchSize",
"type": {
"option": "u32"
}
},
{
"name": "minOracleResults",
"type": {
"option": "u32"
}
},
{
"name": "forceReportPeriod",
"type": {
"option": "u32"
}
},
{
"name": "varianceThreshold",
"type": {
"option": {
"defined": "BorshDecimal"
}
}
},
{
"name": "basePriorityFee",
"type": {
"option": "u32"
}
},
{
"name": "priorityFeeBump",
"type": {
"option": "u32"
}
},
{
"name": "priorityFeeBumpPeriod",
"type": {
"option": "u32"
}
},
{
"name": "maxPriorityFeeMultiplier",
"type": {
"option": "u32"
}
},
{
"name": "disableCrank",
"type": {
"option": "bool"
}
}
]
}
},
{
"name": "AggregatorSetForceReportPeriodParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "forceReportPeriod",
"type": "u32"
}
]
}
},
{
"name": "AggregatorSetHistoryBufferParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "AggregatorSetMinJobsParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "minJobResults",
"type": "u32"
}
]
}
},
{
"name": "AggregatorSetMinOraclesParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "minOracleResults",
"type": "u32"
}
]
}
},
{
"name": "AggregatorSetQueueParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "AggregatorSetResolutionModeParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "mode",
"type": "u8"
}
]
}
},
{
"name": "AggregatorSetUpdateIntervalParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "newInterval",
"type": "u32"
}
]
}
},
{
"name": "AggregatorSetVarianceThresholdParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "varianceThreshold",
"type": {
"defined": "BorshDecimal"
}
}
]
}
},
{
"name": "AggregatorTeeSaveResultParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "value",
"type": {
"defined": "BorshDecimal"
}
},
{
"name": "jobsChecksum",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "minResponse",
"type": {
"defined": "BorshDecimal"
}
},
{
"name": "maxResponse",
"type": {
"defined": "BorshDecimal"
}
},
{
"name": "feedPermissionBump",
"type": "u8"
},
{
"name": "oraclePermissionBump",
"type": "u8"
},
{
"name": "leaseBump",
"type": "u8"
},
{
"name": "stateBump",
"type": "u8"
}
]
}
},
{
"name": "BufferRelayerInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "minUpdateDelaySeconds",
"type": "u32"
},
{
"name": "stateBump",
"type": "u8"
}
]
}
},
{
"name": "BufferRelayerOpenRoundParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"type": "u8"
},
{
"name": "permissionBump",
"type": "u8"
}
]
}
},
{
"name": "BufferRelayerSaveResultParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"type": "u8"
},
{
"name": "permissionBump",
"type": "u8"
},
{
"name": "result",
"type": "bytes"
},
{
"name": "success",
"type": "bool"
}
]
}
},
{
"name": "CrankInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": "bytes"
},
{
"name": "metadata",
"type": "bytes"
},
{
"name": "crankSize",
"type": "u32"
}
]
}
},
{
"name": "CrankPopParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"type": "u8"
},
{
"name": "leaseBumps",
"type": "bytes"
},
{
"name": "permissionBumps",
"type": "bytes"
},
{
"name": "nonce",
"type": {
"option": "u32"
}
},
{
"name": "failOpenOnAccountMismatch",
"type": {
"option": "bool"
}
}
]
}
},
{
"name": "CrankPopParamsV2",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"type": "u8"
},
{
"name": "leaseBumps",
"type": "bytes"
},
{
"name": "permissionBumps",
"type": "bytes"
},
{
"name": "nonce",
"type": {
"option": "u32"
}
},
{
"name": "failOpenOnAccountMismatch",
"type": {
"option": "bool"
}
},
{
"name": "popIdx",
"type": {
"option": "u32"
}
}
]
}
},
{
"name": "CrankPushParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"type": "u8"
},
{
"name": "permissionBump",
"type": "u8"
},
{
"name": "notifiRef",
"type": {
"option": {
"array": [
"u8",
64
]
}
}
}
]
}
},
{
"name": "JobInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "expiration",
"type": "i64"
},
{
"name": "stateBump",
"type": "u8"
},
{
"name": "data",
"type": "bytes"
},
{
"name": "size",
"type": {
"option": "u32"
}
}
]
}
},
{
"name": "JobSetDataParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "data",
"type": "bytes"
},
{
"name": "chunkIdx",
"type": "u8"
}
]
}
},
{
"name": "LeaseExtendParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "loadAmount",
"type": "u64"
},
{
"name": "leaseBump",
"type": "u8"
},
{
"name": "stateBump",
"type": "u8"
},
{
"name": "walletBumps",
"type": "bytes"
}
]
}
},
{
"name": "LeaseInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "loadAmount",
"type": "u64"
},
{
"name": "withdrawAuthority",
"type": "publicKey"
},
{
"name": "leaseBump",
"type": "u8"
},
{
"name": "stateBump",
"type": "u8"
},
{
"name": "walletBumps",
"type": "bytes"
}
]
}
},
{
"name": "LeaseSetAuthorityParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "LeaseWithdrawParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"type": "u8"
},
{
"name": "leaseBump",
"type": "u8"
},
{
"name": "amount",
"type": "u64"
}
]
}
},
{
"name": "OracleHeartbeatParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "permissionBump",
"type": "u8"
}
]
}
},
{
"name": "OracleInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": "bytes"
},
{
"name": "metadata",
"type": "bytes"
},
{
"name": "stateBump",
"type": "u8"
},
{
"name": "oracleBump",
"type": "u8"
}
]
}
},
{
"name": "OracleQueueInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "metadata",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "reward",
"type": "u64"
},
{
"name": "minStake",
"type": "u64"
},
{
"name": "feedProbationPeriod",
"type": "u32"
},
{
"name": "oracleTimeout",
"type": "u32"
},
{
"name": "slashingEnabled",
"type": "bool"
},
{
"name": "varianceToleranceMultiplier",
"type": {
"defined": "BorshDecimal"
}
},
{
"name": "consecutiveFeedFailureLimit",
"type": "u64"
},
{
"name": "consecutiveOracleFailureLimit",
"type": "u64"
},
{
"name": "queueSize",
"type": "u32"
},
{
"name": "unpermissionedFeeds",
"type": "bool"
},
{
"name": "unpermissionedVrf",
"type": "bool"
},
{
"name": "enableBufferRelayers",
"type": "bool"
},
{
"name": "enableTeeOnly",
"type": "bool"
}
]
}
},
{
"name": "OracleQueueSetConfigParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": {
"option": {
"array": [
"u8",
32
]
}
}
},
{
"name": "metadata",
"type": {
"option": {
"array": [
"u8",
64
]
}
}
},
{
"name": "unpermissionedFeedsEnabled",
"type": {
"option": "bool"
}
},
{
"name": "unpermissionedVrfEnabled",
"type": {
"option": "bool"
}
},
{
"name": "enableBufferRelayers",
"type": {
"option": "bool"
}
},
{
"name": "varianceToleranceMultiplier",
"type": {
"option": {
"defined": "BorshDecimal"
}
}
},
{
"name": "slashingEnabled",
"type": {
"option": "bool"
}
},
{
"name": "reward",
"type": {
"option": "u64"
}
},
{
"name": "minStake",
"type": {
"option": "u64"
}
},
{
"name": "oracleTimeout",
"type": {
"option": "u32"
}
},
{
"name": "consecutiveFeedFailureLimit",
"type": {
"option": "u64"
}
},
{
"name": "consecutiveOracleFailureLimit",
"type": {
"option": "u64"
}
},
{
"name": "enableTeeOnly",
"type": {
"option": "bool"
}
}
]
}
},
{
"name": "OracleQueueSetRewardsParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "rewards",
"type": "u64"
}
]
}
},
{
"name": "OracleTeeHeartbeatParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "permissionBump",
"type": "u8"
}
]
}
},
{
"name": "OracleWithdrawParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"type": "u8"
},
{
"name": "permissionBump",
"type": "u8"
},
{
"name": "amount",
"type": "u64"
}
]
}
},
{
"name": "PermissionInitParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "PermissionSetParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "permission",
"type": {
"defined": "SwitchboardPermission"
}
},
{
"name": "enable",
"type": "bool"
}
]
}
},
{
"name": "ProgramConfigParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "token",
"type": "publicKey"
},
{
"name": "bump",
"type": "u8"
},
{
"name": "daoMint",
"type": "publicKey"
},
{
"name": "addEnclaves",
"type": {
"vec": {
"array": [
"u8",
32
]
}
}
},
{
"name": "rmEnclaves",
"type": {
"vec": {
"array": [
"u8",
32
]
}
}
}
]
}
},
{
"name": "ProgramInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"type": "u8"
}
]
}
},
{
"name": "SetBumpsParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"type": "u8"
}
]
}
},
{
"name": "VaultTransferParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"type": "u8"
},
{
"name": "amount",
"type": "u64"
}
]
}
},
{
"name": "VrfCloseParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateBump",
"type": "u8"
},
{
"name": "permissionBump",
"type": "u8"
}
]
}
},
{
"name": "VrfInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "callback",
"type": {
"defined": "Callback"
}
},
{
"name": "stateBump",
"type": "u8"
}
]
}
},
{
"name": "VrfLiteCloseParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "VrfLiteInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "callback",
"type": {
"option": {
"defined": "Callback"
}
}
},
{
"name": "stateBump",
"type": "u8"
},
{
"name": "expiration",
"type": {
"option": "i64"
}
}
]
}
},
{
"name": "VrfLiteProveAndVerifyParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "nonce",
"type": {
"option": "u32"
}
},
{
"name": "proof",
"type": "bytes"
},
{
"name": "proofEncoded",
"type": "string"
},
{
"name": "counter",
"type": "u128"
}
]
}
},
{
"name": "VrfLiteRequestRandomnessParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "callback",
"type": {
"option": {
"defined": "Callback"
}
}
}
]
}
},
{
"name": "VrfPoolAddParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "VrfPoolInitParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "maxRows",
"type": "u32"
},
{
"name": "minInterval",
"type": "u32"
},
{
"name": "stateBump",
"type": "u8"
}
]
}
},
{
"name": "VrfPoolRemoveParams",
"type": {
"kind": "struct",
"fields": []
}
},
{
"name": "VrfPoolRequestParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "callback",
"type": {
"option": {
"defined": "Callback"
}
}
}
]
}
},
{
"name": "VrfProveParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "proof",
"type": "bytes"
},
{
"name": "idx",
"type": "u32"
}
]
}
},
{
"name": "VrfProveAndVerifyParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "nonce",
"type": {
"option": "u32"
}
},
{
"name": "stateBump",
"type": "u8"
},
{
"name": "idx",
"type": "u32"
},
{
"name": "proof",
"type": "bytes"
},
{
"name": "proofEncoded",
"type": "string"
},
{
"name": "counter",
"type": "u128"
}
]
}
},
{
"name": "VrfRequestRandomnessParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "permissionBump",
"type": "u8"
},
{
"name": "stateBump",
"type": "u8"
}
]
}
},
{
"name": "VrfSetCallbackParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "callback",
"type": {
"defined": "Callback"
}
}
]
}
},
{
"name": "Callback",
"type": {
"kind": "struct",
"fields": [
{
"name": "programId",
"type": "publicKey"
},
{
"name": "accounts",
"type": {
"vec": {
"defined": "AccountMetaBorsh"
}
}
},
{
"name": "ixData",
"type": "bytes"
}
]
}
},
{
"name": "EcvrfProofZC",
"type": {
"kind": "struct",
"fields": [
{
"name": "gamma",
"type": {
"defined": "EdwardsPointZC"
}
},
{
"name": "c",
"type": {
"defined": "Scalar"
}
},
{
"name": "s",
"type": {
"defined": "Scalar"
}
}
]
}
},
{
"name": "Scalar",
"docs": [
"The `Scalar` struct holds an integer \\\\(s < 2\\^{255} \\\\) which",
"represents an element of \\\\(\\mathbb Z / \\ell\\\\)."
],
"type": {
"kind": "struct",
"fields": [
{
"name": "bytes",
"docs": [
"`bytes` is a little-endian byte encoding of an integer representing a scalar modulo the",
"group order.",
"",
"# Invariant",
"",
"The integer representing this scalar must be bounded above by \\\\(2\\^{255}\\\\), or",
"equivalently the high bit of `bytes[31]` must be zero.",
"",
"This ensures that there is room for a carry bit when computing a NAF representation."
],
"type": {
"array": [
"u8",
32
]
}
}
]
}
},
{
"name": "FieldElementZC",
"type": {
"kind": "struct",
"fields": [
{
"name": "bytes",
"type": {
"array": [
"u64",
5
]
}
}
]
}
},
{
"name": "CompletedPointZC",
"type": {
"kind": "struct",
"fields": [
{
"name": "x",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "y",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "z",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "t",
"type": {
"defined": "FieldElementZC"
}
}
]
}
},
{
"name": "EdwardsPointZC",
"type": {
"kind": "struct",
"fields": [
{
"name": "x",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "y",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "z",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "t",
"type": {
"defined": "FieldElementZC"
}
}
]
}
},
{
"name": "ProjectivePointZC",
"type": {
"kind": "struct",
"fields": [
{
"name": "x",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "y",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "z",
"type": {
"defined": "FieldElementZC"
}
}
]
}
},
{
"name": "EcvrfIntermediate",
"type": {
"kind": "struct",
"fields": [
{
"name": "r",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "nS",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "d",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "t13",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "t15",
"type": {
"defined": "FieldElementZC"
}
}
]
}
},
{
"name": "BorshDecimal",
"type": {
"kind": "struct",
"fields": [
{
"name": "mantissa",
"type": "i128"
},
{
"name": "scale",
"type": "u32"
}
]
}
},
{
"name": "Quote",
"type": {
"kind": "struct",
"fields": [
{
"name": "enclaveSigner",
"docs": [
"The address of the signer generated within an enclave."
],
"type": "publicKey"
},
{
"name": "mrEnclave",
"docs": [
"The quotes MRENCLAVE measurement dictating the contents of the secure enclave."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "verificationStatus",
"docs": [
"The VerificationStatus of the quote."
],
"type": "u8"
},
{
"name": "verificationTimestamp",
"docs": [
"The unix timestamp when the quote was last verified."
],
"type": "i64"
},
{
"name": "validUntil",
"docs": [
"The unix timestamp when the quotes verification status expires."
],
"type": "i64"
},
{
"name": "quoteRegistry",
"docs": [
"The off-chain registry where the verifiers quote can be located."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "registryKey",
"docs": [
"Key to lookup the buffer data on IPFS or an alternative decentralized storage solution."
],
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "ebuf",
"docs": [
"Reserved."
],
"type": {
"array": [
"u8",
256
]
}
}
]
}
},
{
"name": "VerifierAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "enclave",
"docs": [
"Represents the state of the quote verifiers enclave."
],
"type": {
"defined": "Quote"
}
},
{
"name": "authority",
"docs": [
"The authority of the EnclaveAccount which is permitted to make account changes."
],
"type": "publicKey"
},
{
"name": "attestationQueue",
"docs": [
"Queue used for attestation to verify a MRENCLAVE measurement."
],
"type": "publicKey"
},
{
"name": "createdAt",
"docs": [
"The unix timestamp when the quote was created."
],
"type": "i64"
},
{
"name": "isOnQueue",
"docs": [
"Whether the quote is located on the AttestationQueues buffer."
],
"type": "bool"
},
{
"name": "lastHeartbeat",
"docs": [
"The last time the quote heartbeated on-chain."
],
"type": "i64"
},
{
"name": "rewardEscrow",
"docs": [
"The SwitchboardWallet account containing the reward escrow for verifying quotes on-chain.",
"We should set this whenever the operator changes so we dont need to pass another account and can verify with has_one."
],
"type": "publicKey"
},
{
"name": "stakeWallet",
"docs": [
"The SwitchboardWallet account containing the queues required min_stake.",
"Needs to be separate from the reward_escrow. Allows easier 3rd party management of stake from rewards."
],
"type": "publicKey"
},
{
"name": "ebuf",
"docs": [
"Reserved."
],
"type": {
"array": [
"u8",
1024
]
}
}
]
}
},
{
"name": "Hash",
"type": {
"kind": "struct",
"fields": [
{
"name": "data",
"docs": [
"The bytes used to derive the hash."
],
"type": {
"array": [
"u8",
32
]
}
}
]
}
},
{
"name": "SlidingWindowElement",
"type": {
"kind": "struct",
"fields": [
{
"name": "oracleKey",
"type": "publicKey"
},
{
"name": "value",
"type": {
"defined": "SwitchboardDecimal"
}
},
{
"name": "slot",
"type": "u64"
},
{
"name": "timestamp",
"type": "i64"
}
]
}
},
{
"name": "AggregatorRound",
"type": {
"kind": "struct",
"fields": [
{
"name": "numSuccess",
"docs": [
"Maintains the number of successful responses received from nodes.",
"Nodes can submit one successful response per round."
],
"type": "u32"
},
{
"name": "numError",
"docs": [
"Number of error responses."
],
"type": "u32"
},
{
"name": "isClosed",
"docs": [
"Whether an update request round has ended."
],
"type": "bool"
},
{
"name": "roundOpenSlot",
"docs": [
"Maintains the `solana_program::clock::Slot` that the round was opened at."
],
"type": "u64"
},
{
"name": "roundOpenTimestamp",
"docs": [
"Maintains the `solana_program::clock::UnixTimestamp;` the round was opened at."
],
"type": "i64"
},
{
"name": "result",
"docs": [
"Maintains the current median of all successful round responses."
],
"type": {
"defined": "SwitchboardDecimal"
}
},
{
"name": "stdDeviation",
"docs": [
"Standard deviation of the accepted results in the round."
],
"type": {
"defined": "SwitchboardDecimal"
}
},
{
"name": "minResponse",
"docs": [
"Maintains the minimum node response this round."
],
"type": {
"defined": "SwitchboardDecimal"
}
},
{
"name": "maxResponse",
"docs": [
"Maintains the maximum node response this round."
],
"type": {
"defined": "SwitchboardDecimal"
}
},
{
"name": "oraclePubkeysData",
"docs": [
"Pubkeys of the oracles fulfilling this round."
],
"type": {
"array": [
"publicKey",
16
]
}
},
{
"name": "mediansData",
"docs": [
"Represents all successful node responses this round. `NaN` if empty."
],
"type": {
"array": [
{
"defined": "SwitchboardDecimal"
},
16
]
}
},
{
"name": "currentPayout",
"docs": [
"Current rewards/slashes oracles have received this round."
],
"type": {
"array": [
"i64",
16
]
}
},
{
"name": "mediansFulfilled",
"docs": [
"Keep track of which responses are fulfilled here."
],
"type": {
"array": [
"bool",
16
]
}
},
{
"name": "errorsFulfilled",
"docs": [
"Keeps track of which errors are fulfilled here."
],
"type": {
"array": [
"bool",
16
]
}
}
]
}
},
{
"name": "AggregatorHistoryRow",
"type": {
"kind": "struct",
"fields": [
{
"name": "timestamp",
"docs": [
"The timestamp of the sample."
],
"type": "i64"
},
{
"name": "value",
"docs": [
"The value of the sample."
],
"type": {
"defined": "SwitchboardDecimal"
}
}
]
}
},
{
"name": "SwitchboardDecimal",
"type": {
"kind": "struct",
"fields": [
{
"name": "mantissa",
"docs": [
"The part of a floating-point number that represents the significant digits of that number,",
"and that is multiplied by the base, 10, raised to the power of scale to give the actual value of the number."
],
"type": "i128"
},
{
"name": "scale",
"docs": [
"The number of decimal places to move to the left to yield the actual value."
],
"type": "u32"
}
]
}
},
{
"name": "CrankRow",
"type": {
"kind": "struct",
"fields": [
{
"name": "pubkey",
"docs": [
"The PublicKey of the AggregatorAccountData."
],
"type": "publicKey"
},
{
"name": "nextTimestamp",
"docs": [
"The aggregator's next available update time."
],
"type": "i64"
}
]
}
},
{
"name": "OracleMetrics",
"type": {
"kind": "struct",
"fields": [
{
"name": "consecutiveSuccess",
"docs": [
"Number of consecutive successful update request."
],
"type": "u64"
},
{
"name": "consecutiveError",
"docs": [
"Number of consecutive update request that resulted in an error."
],
"type": "u64"
},
{
"name": "consecutiveDisagreement",
"docs": [
"Number of consecutive update request that resulted in a disagreement with the accepted median result."
],
"type": "u64"
},
{
"name": "consecutiveLateResponse",
"docs": [
"Number of consecutive update request that were posted on-chain late and not included in an accepted result."
],
"type": "u64"
},
{
"name": "consecutiveFailure",
"docs": [
"Number of consecutive update request that resulted in a failure."
],
"type": "u64"
},
{
"name": "totalSuccess",
"docs": [
"Total number of successful update request."
],
"type": "u128"
},
{
"name": "totalError",
"docs": [
"Total number of update request that resulted in an error."
],
"type": "u128"
},
{
"name": "totalDisagreement",
"docs": [
"Total number of update request that resulted in a disagreement with the accepted median result."
],
"type": "u128"
},
{
"name": "totalLateResponse",
"docs": [
"Total number of update request that were posted on-chain late and not included in an accepted result."
],
"type": "u128"
}
]
}
},
{
"name": "VrfBuilder",
"type": {
"kind": "struct",
"fields": [
{
"name": "producer",
"docs": [
"The OracleAccountData that is producing the randomness."
],
"type": "publicKey"
},
{
"name": "status",
"docs": [
"The current status of the VRF verification."
],
"type": {
"defined": "VrfStatus"
}
},
{
"name": "reprProof",
"docs": [
"The VRF proof sourced from the producer."
],
"type": {
"array": [
"u8",
80
]
}
},
{
"name": "proof",
"type": {
"defined": "EcvrfProofZC"
}
},
{
"name": "yPoint",
"type": "publicKey"
},
{
"name": "stage",
"type": "u32"
},
{
"name": "stage1Out",
"type": {
"defined": "EcvrfIntermediate"
}
},
{
"name": "r1",
"type": {
"defined": "EdwardsPointZC"
}
},
{
"name": "r2",
"type": {
"defined": "EdwardsPointZC"
}
},
{
"name": "stage3Out",
"type": {
"defined": "EcvrfIntermediate"
}
},
{
"name": "hPoint",
"type": {
"defined": "EdwardsPointZC"
}
},
{
"name": "sReduced",
"type": {
"defined": "Scalar"
}
},
{
"name": "yPointBuilder",
"type": {
"array": [
{
"defined": "FieldElementZC"
},
3
]
}
},
{
"name": "yRistrettoPoint",
"type": {
"defined": "EdwardsPointZC"
}
},
{
"name": "mulRound",
"type": "u8"
},
{
"name": "hashPointsRound",
"type": "u8"
},
{
"name": "mulTmp1",
"type": {
"defined": "CompletedPointZC"
}
},
{
"name": "uPoint1",
"type": {
"defined": "EdwardsPointZC"
}
},
{
"name": "uPoint2",
"type": {
"defined": "EdwardsPointZC"
}
},
{
"name": "vPoint1",
"type": {
"defined": "EdwardsPointZC"
}
},
{
"name": "vPoint2",
"type": {
"defined": "EdwardsPointZC"
}
},
{
"name": "uPoint",
"type": {
"defined": "EdwardsPointZC"
}
},
{
"name": "vPoint",
"type": {
"defined": "EdwardsPointZC"
}
},
{
"name": "u1",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "u2",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "invertee",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "y",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "z",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "p1Bytes",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "p2Bytes",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "p3Bytes",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "p4Bytes",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "cPrimeHashbuf",
"type": {
"array": [
"u8",
16
]
}
},
{
"name": "m1",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "m2",
"type": {
"defined": "FieldElementZC"
}
},
{
"name": "txRemaining",
"docs": [
"The number of transactions remaining to verify the VRF proof."
],
"type": "u32"
},
{
"name": "verified",
"docs": [
"Whether the VRF proof has been verified on-chain."
],
"type": "bool"
},
{
"name": "result",
"docs": [
"The VRF proof verification result. Will be zeroized if still awaiting fulfillment."
],
"type": {
"array": [
"u8",
32
]
}
}
]
}
},
{
"name": "AccountMetaZC",
"type": {
"kind": "struct",
"fields": [
{
"name": "pubkey",
"type": "publicKey"
},
{
"name": "isSigner",
"type": "bool"
},
{
"name": "isWritable",
"type": "bool"
}
]
}
},
{
"name": "AccountMetaBorsh",
"type": {
"kind": "struct",
"fields": [
{
"name": "pubkey",
"type": "publicKey"
},
{
"name": "isSigner",
"type": "bool"
},
{
"name": "isWritable",
"type": "bool"
}
]
}
},
{
"name": "CallbackZC",
"type": {
"kind": "struct",
"fields": [
{
"name": "programId",
"docs": [
"The program ID of the callback program being invoked."
],
"type": "publicKey"
},
{
"name": "accounts",
"docs": [
"The accounts being used in the callback instruction."
],
"type": {
"array": [
{
"defined": "AccountMetaZC"
},
32
]
}
},
{
"name": "accountsLen",
"docs": [
"The number of accounts used in the callback"
],
"type": "u32"
},
{
"name": "ixData",
"docs": [
"The serialized instruction data."
],
"type": {
"array": [
"u8",
1024
]
}
},
{
"name": "ixDataLen",
"docs": [
"The number of serialized bytes in the instruction data."
],
"type": "u32"
}
]
}
},
{
"name": "VrfRound",
"type": {
"kind": "struct",
"fields": [
{
"name": "alpha",
"docs": [
"The alpha bytes used to calculate the VRF proof."
],
"type": {
"array": [
"u8",
256
]
}
},
{
"name": "alphaLen",
"docs": [
"The number of bytes in the alpha buffer."
],
"type": "u32"
},
{
"name": "requestSlot",
"docs": [
"The Slot when the VRF round was opened."
],
"type": "u64"
},
{
"name": "requestTimestamp",
"docs": [
"The unix timestamp when the VRF round was opened."
],
"type": "i64"
},
{
"name": "result",
"docs": [
"The VRF round result. Will be zeroized if still awaiting fulfillment."
],
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "numVerified",
"docs": [
"The number of builders who verified the VRF proof."
],
"type": "u32"
},
{
"name": "ebuf",
"docs": [
"Reserved for future info."
],
"type": {
"array": [
"u8",
256
]
}
}
]
}
},
{
"name": "VrfPoolRow",
"type": {
"kind": "struct",
"fields": [
{
"name": "timestamp",
"type": "i64"
},
{
"name": "pubkey",
"type": "publicKey"
}
]
}
},
{
"name": "BufferRelayerRound",
"type": {
"kind": "struct",
"fields": [
{
"name": "numSuccess",
"docs": [
"Number of successful responses."
],
"type": "u32"
},
{
"name": "numError",
"docs": [
"Number of error responses."
],
"type": "u32"
},
{
"name": "roundOpenSlot",
"docs": [
"Slot when the buffer relayer round was opened."
],
"type": "u64"
},
{
"name": "roundOpenTimestamp",
"docs": [
"Timestamp when the buffer relayer round was opened."
],
"type": "i64"
},
{
"name": "oraclePubkey",
"docs": [
"The public key of the oracle fulfilling the buffer relayer update request."
],
"type": "publicKey"
}
]
}
},
{
"name": "Lanes",
"docs": [
"The `Lanes` enum represents a subset of the lanes `A,B,C,D` of a",
"`FieldElement2625x4`.",
"",
"It's used to specify blend operations without",
"having to know details about the data layout of the",
"`FieldElement2625x4`."
],
"type": {
"kind": "enum",
"variants": [
{
"name": "C"
},
{
"name": "D"
},
{
"name": "AB"
},
{
"name": "AC"
},
{
"name": "CD"
},
{
"name": "AD"
},
{
"name": "BC"
},
{
"name": "ABCD"
}
]
}
},
{
"name": "Shuffle",
"docs": [
"The `Shuffle` enum represents a shuffle of a `FieldElement2625x4`.",
"",
"The enum variants are named by what they do to a vector \\\\(",
"(A,B,C,D) \\\\); for instance, `Shuffle::BADC` turns \\\\( (A, B, C,",
"D) \\\\) into \\\\( (B, A, D, C) \\\\)."
],
"type": {
"kind": "enum",
"variants": [
{
"name": "AAAA"
},
{
"name": "BBBB"
},
{
"name": "CACA"
},
{
"name": "DBBD"
},
{
"name": "ADDA"
},
{
"name": "CBCB"
},
{
"name": "ABAB"
},
{
"name": "BADC"
},
{
"name": "BACD"
},
{
"name": "ABDC"
}
]
}
},
{
"name": "Shuffle",
"type": {
"kind": "enum",
"variants": [
{
"name": "AAAA"
},
{
"name": "BBBB"
},
{
"name": "BADC"
},
{
"name": "BACD"
},
{
"name": "ADDA"
},
{
"name": "CBCB"
},
{
"name": "ABDC"
},
{
"name": "ABAB"
},
{
"name": "DBBD"
},
{
"name": "CACA"
}
]
}
},
{
"name": "Lanes",
"type": {
"kind": "enum",
"variants": [
{
"name": "D"
},
{
"name": "C"
},
{
"name": "AB"
},
{
"name": "AC"
},
{
"name": "AD"
},
{
"name": "BCD"
}
]
}
},
{
"name": "Error",
"type": {
"kind": "enum",
"variants": [
{
"name": "InvalidPublicKey"
},
{
"name": "SerializationError"
},
{
"name": "DeserializationError"
},
{
"name": "InvalidDataError"
}
]
}
},
{
"name": "VerificationStatus",
"type": {
"kind": "enum",
"variants": [
{
"name": "None"
},
{
"name": "VerificationPending"
},
{
"name": "VerificationFailure"
},
{
"name": "VerificationSuccess"
},
{
"name": "VerificationOverride"
}
]
}
},
{
"name": "AggregatorResolutionMode",
"type": {
"kind": "enum",
"variants": [
{
"name": "ModeRoundResolution"
},
{
"name": "ModeSlidingResolution"
}
]
}
},
{
"name": "SwitchboardPermission",
"type": {
"kind": "enum",
"variants": [
{
"name": "PermitOracleHeartbeat"
},
{
"name": "PermitOracleQueueUsage"
},
{
"name": "PermitVrfRequests"
}
]
}
},
{
"name": "OracleResponseType",
"type": {
"kind": "enum",
"variants": [
{
"name": "TypeSuccess"
},
{
"name": "TypeError"
},
{
"name": "TypeDisagreement"
},
{
"name": "TypeNoResponse"
}
]
}
},
{
"name": "VrfStatus",
"type": {
"kind": "enum",
"variants": [
{
"name": "StatusNone"
},
{
"name": "StatusRequesting"
},
{
"name": "StatusVerifying"
},
{
"name": "StatusVerified"
},
{
"name": "StatusCallbackSuccess"
},
{
"name": "StatusVerifyFailure"
}
]
}
}
],
"events": [
{
"name": "VrfRequestRandomnessEvent",
"fields": [
{
"name": "vrfPubkey",
"type": "publicKey",
"index": true
},
{
"name": "oraclePubkeys",
"type": {
"vec": "publicKey"
},
"index": false
},
{
"name": "loadAmount",
"type": "u64",
"index": false
},
{
"name": "existingAmount",
"type": "u64",
"index": false
},
{
"name": "alpha",
"type": "bytes",
"index": false
},
{
"name": "counter",
"type": "u128",
"index": false
}
]
},
{
"name": "VrfRequestEvent",
"fields": [
{
"name": "vrfPubkey",
"type": "publicKey",
"index": true
},
{
"name": "oraclePubkeys",
"type": {
"vec": "publicKey"
},
"index": false
}
]
},
{
"name": "VrfProveEvent",
"fields": [
{
"name": "vrfPubkey",
"type": "publicKey",
"index": true
},
{
"name": "oraclePubkey",
"type": "publicKey",
"index": true
},
{
"name": "authorityPubkey",
"type": "publicKey",
"index": false
}
]
},
{
"name": "VrfVerifyEvent",
"fields": [
{
"name": "vrfPubkey",
"type": "publicKey",
"index": true
},
{
"name": "oraclePubkey",
"type": "publicKey",
"index": true
},
{
"name": "authorityPubkey",
"type": "publicKey",
"index": false
},
{
"name": "amount",
"type": "u64",
"index": false
}
]
},
{
"name": "VrfCallbackPerformedEvent",
"fields": [
{
"name": "vrfPubkey",
"type": "publicKey",
"index": true
},
{
"name": "oraclePubkey",
"type": "publicKey",
"index": true
},
{
"name": "amount",
"type": "u64",
"index": false
}
]
},
{
"name": "AggregatorOpenRoundEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "oraclePubkeys",
"type": {
"vec": "publicKey"
},
"index": false
},
{
"name": "jobPubkeys",
"type": {
"vec": "publicKey"
},
"index": false
},
{
"name": "remainingFunds",
"type": "u64",
"index": false
},
{
"name": "queueAuthority",
"type": "publicKey",
"index": false
}
]
},
{
"name": "AggregatorSaveResultEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "value",
"type": {
"defined": "BorshDecimal"
},
"index": false
},
{
"name": "slot",
"type": "u64",
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
},
{
"name": "oraclePubkey",
"type": "publicKey",
"index": false
},
{
"name": "jobValues",
"type": {
"vec": {
"option": {
"defined": "BorshDecimal"
}
}
},
"index": false
}
]
},
{
"name": "AggregatorTeeSaveResultEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "value",
"type": {
"defined": "BorshDecimal"
},
"index": false
},
{
"name": "slot",
"type": "u64",
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
},
{
"name": "oraclePubkey",
"type": "publicKey",
"index": false
}
]
},
{
"name": "AggregatorValueUpdateEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "value",
"type": {
"defined": "BorshDecimal"
},
"index": false
},
{
"name": "slot",
"type": "u64",
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
},
{
"name": "oraclePubkeys",
"type": {
"vec": "publicKey"
},
"index": false
},
{
"name": "oracleValues",
"type": {
"vec": {
"defined": "BorshDecimal"
}
},
"index": false
}
]
},
{
"name": "OracleRewardEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "leasePubkey",
"type": "publicKey",
"index": false
},
{
"name": "oraclePubkey",
"type": "publicKey",
"index": false
},
{
"name": "walletPubkey",
"type": "publicKey",
"index": false
},
{
"name": "amount",
"type": "u64",
"index": false
},
{
"name": "roundSlot",
"type": "u64",
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
}
]
},
{
"name": "OracleWithdrawEvent",
"fields": [
{
"name": "oraclePubkey",
"type": "publicKey",
"index": false
},
{
"name": "walletPubkey",
"type": "publicKey",
"index": false
},
{
"name": "destinationWallet",
"type": "publicKey",
"index": false
},
{
"name": "previousAmount",
"type": "u64",
"index": false
},
{
"name": "newAmount",
"type": "u64",
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
}
]
},
{
"name": "LeaseWithdrawEvent",
"fields": [
{
"name": "leasePubkey",
"type": "publicKey",
"index": false
},
{
"name": "walletPubkey",
"type": "publicKey",
"index": false
},
{
"name": "previousAmount",
"type": "u64",
"index": false
},
{
"name": "newAmount",
"type": "u64",
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
}
]
},
{
"name": "OracleSlashEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "leasePubkey",
"type": "publicKey",
"index": false
},
{
"name": "oraclePubkey",
"type": "publicKey",
"index": false
},
{
"name": "walletPubkey",
"type": "publicKey",
"index": false
},
{
"name": "amount",
"type": "u64",
"index": false
},
{
"name": "roundSlot",
"type": "u64",
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
}
]
},
{
"name": "LeaseFundEvent",
"fields": [
{
"name": "leasePubkey",
"type": "publicKey",
"index": false
},
{
"name": "funder",
"type": "publicKey",
"index": false
},
{
"name": "amount",
"type": "u64",
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
}
]
},
{
"name": "ProbationBrokenEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "queuePubkey",
"type": "publicKey",
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
}
]
},
{
"name": "FeedPermissionRevokedEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
}
]
},
{
"name": "GarbageCollectFailureEvent",
"fields": [
{
"name": "queuePubkey",
"type": "publicKey",
"index": false
}
]
},
{
"name": "OracleBootedEvent",
"fields": [
{
"name": "queuePubkey",
"type": "publicKey",
"index": false
},
{
"name": "oraclePubkey",
"type": "publicKey",
"index": false
}
]
},
{
"name": "AggregatorCrankEvictionEvent",
"fields": [
{
"name": "crankPubkey",
"type": "publicKey",
"index": false
},
{
"name": "aggregatorPubkey",
"type": "publicKey",
"index": true
},
{
"name": "reason",
"type": {
"option": "u32"
},
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
}
]
},
{
"name": "CrankLeaseInsufficientFundsEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "leasePubkey",
"type": "publicKey",
"index": false
}
]
},
{
"name": "CrankPopExpectedFailureEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "leasePubkey",
"type": "publicKey",
"index": false
}
]
},
{
"name": "BufferRelayerOpenRoundEvent",
"fields": [
{
"name": "relayerPubkey",
"type": "publicKey",
"index": false
},
{
"name": "jobPubkey",
"type": "publicKey",
"index": false
},
{
"name": "oraclePubkeys",
"type": {
"vec": "publicKey"
},
"index": false
},
{
"name": "remainingFunds",
"type": "u64",
"index": false
},
{
"name": "queue",
"type": "publicKey",
"index": false
}
]
},
{
"name": "PriorityFeeReimburseEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "slot",
"type": "u64",
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
},
{
"name": "fee",
"type": "u64",
"index": false
}
]
},
{
"name": "AggregatorAddJobEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "jobPubkey",
"type": "publicKey",
"index": false
}
]
},
{
"name": "AggregatorRemoveJobEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "jobPubkey",
"type": "publicKey",
"index": false
}
]
},
{
"name": "AggregatorLockEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
}
]
},
{
"name": "AggregatorInitEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
}
]
},
{
"name": "AggregatorSetAuthorityEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "oldAuthority",
"type": "publicKey",
"index": false
},
{
"name": "newAuthority",
"type": "publicKey",
"index": false
}
]
},
{
"name": "AggregatorSetConfigsEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
}
]
},
{
"name": "PermissionSetEvent",
"fields": [
{
"name": "permissionKey",
"type": "publicKey",
"index": false
},
{
"name": "permission",
"type": {
"defined": "SwitchboardPermission"
},
"index": false
},
{
"name": "enable",
"type": "bool",
"index": false
}
]
},
{
"name": "VrfPoolUpdateEvent",
"fields": [
{
"name": "queuePubkey",
"type": "publicKey",
"index": false
},
{
"name": "vrfPoolPubkey",
"type": "publicKey",
"index": false
},
{
"name": "vrfPubkey",
"type": "publicKey",
"index": false
},
{
"name": "newSize",
"type": "u32",
"index": false
},
{
"name": "minInterval",
"type": "u32",
"index": false
}
]
},
{
"name": "VrfPoolRequestEvent",
"fields": [
{
"name": "queuePubkey",
"type": "publicKey",
"index": false
},
{
"name": "vrfPoolPubkey",
"type": "publicKey",
"index": false
},
{
"name": "vrfPubkey",
"type": "publicKey",
"index": false
},
{
"name": "oraclePubkey",
"type": "publicKey",
"index": false
},
{
"name": "slot",
"type": "u64",
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
}
]
},
{
"name": "QuoteVerifyRequestEvent",
"fields": [
{
"name": "quotePubkey",
"type": "publicKey",
"index": false
}
]
},
{
"name": "AggregatorFunctionUpsertEvent",
"fields": [
{
"name": "feedPubkey",
"type": "publicKey",
"index": false
},
{
"name": "value",
"type": {
"defined": "BorshDecimal"
},
"index": false
},
{
"name": "timestamp",
"type": "i64",
"index": false
}
]
}
],
"errors": [
{
"code": 6000,
"name": "ArrayOperationError",
"msg": "Illegal operation on a Switchboard array."
},
{
"code": 6001,
"name": "QueueOperationError",
"msg": "Illegal operation on a Switchboard queue."
},
{
"code": 6002,
"name": "IncorrectProgramOwnerError",
"msg": "An account required to be owned by the program has a different owner."
},
{
"code": 6003,
"name": "InvalidAggregatorRound",
"msg": "Aggregator is not currently populated with a valid round."
},
{
"code": 6004,
"name": "TooManyAggregatorJobs",
"msg": "Aggregator cannot fit any more jobs."
},
{
"code": 6005,
"name": "AggregatorCurrentRoundClosed",
"msg": "Aggregator's current round is closed. No results are being accepted."
},
{
"code": 6006,
"name": "AggregatorInvalidSaveResult",
"msg": "Aggregator received an invalid save result instruction."
},
{
"code": 6007,
"name": "InvalidStrDecimalConversion",
"msg": "Failed to convert string to decimal format."
},
{
"code": 6008,
"name": "AccountLoaderMissingSignature",
"msg": "AccountLoader account is missing a required signature."
},
{
"code": 6009,
"name": "MissingRequiredSignature",
"msg": "Account is missing a required signature."
},
{
"code": 6010,
"name": "ArrayOverflowError",
"msg": "The attempted action will overflow a zero-copy account array."
},
{
"code": 6011,
"name": "ArrayUnderflowError",
"msg": "The attempted action will underflow a zero-copy account array."
},
{
"code": 6012,
"name": "PubkeyNotFoundError",
"msg": "The queried public key was not found."
},
{
"code": 6013,
"name": "AggregatorIllegalRoundOpenCall",
"msg": "Aggregator round open called too early."
},
{
"code": 6014,
"name": "AggregatorIllegalRoundCloseCall",
"msg": "Aggregator round close called too early."
},
{
"code": 6015,
"name": "AggregatorClosedError",
"msg": "Aggregator is closed. Illegal action."
},
{
"code": 6016,
"name": "IllegalOracleIdxError",
"msg": "Illegal oracle index."
},
{
"code": 6017,
"name": "OracleAlreadyRespondedError",
"msg": "The provided oracle has already responded this round."
},
{
"code": 6018,
"name": "ProtoDeserializeError",
"msg": "Failed to deserialize protocol buffer."
},
{
"code": 6019,
"name": "UnauthorizedStateUpdateError",
"msg": "Unauthorized program state modification attempted."
},
{
"code": 6020,
"name": "MissingOracleAccountsError",
"msg": "Not enough oracle accounts provided to closeRounds."
},
{
"code": 6021,
"name": "OracleMismatchError",
"msg": "An unexpected oracle account was provided for the transaction."
},
{
"code": 6022,
"name": "CrankMaxCapacityError",
"msg": "Attempted to push to a Crank that's at capacity"
},
{
"code": 6023,
"name": "AggregatorLeaseInsufficientFunds",
"msg": "Aggregator update call attempted but attached lease has insufficient funds."
},
{
"code": 6024,
"name": "IncorrectTokenAccountMint",
"msg": "The provided token account does not point to the Switchboard token mint."
},
{
"code": 6025,
"name": "InvalidEscrowAccount",
"msg": "An invalid escrow account was provided."
},
{
"code": 6026,
"name": "CrankEmptyError",
"msg": "Crank empty. Pop failed."
},
{
"code": 6027,
"name": "PdaDeriveError",
"msg": "Failed to derive a PDA from the provided seed."
},
{
"code": 6028,
"name": "AggregatorAccountNotFound",
"msg": "Aggregator account missing from provided account list."
},
{
"code": 6029,
"name": "PermissionAccountNotFound",
"msg": "Permission account missing from provided account list."
},
{
"code": 6030,
"name": "LeaseAccountDeriveFailure",
"msg": "Failed to derive a lease account."
},
{
"code": 6031,
"name": "PermissionAccountDeriveFailure",
"msg": "Failed to derive a permission account."
},
{
"code": 6032,
"name": "EscrowAccountNotFound",
"msg": "Escrow account missing from provided account list."
},
{
"code": 6033,
"name": "LeaseAccountNotFound",
"msg": "Lease account missing from provided account list."
},
{
"code": 6034,
"name": "DecimalConversionError",
"msg": "Decimal conversion method failed."
},
{
"code": 6035,
"name": "PermissionDenied",
"msg": "Permission account is missing required flags for the given action."
},
{
"code": 6036,
"name": "QueueAtCapacity",
"msg": "Oracle queue is at lease capacity."
},
{
"code": 6037,
"name": "ExcessiveCrankRowsError",
"msg": "Data feed is already pushed on a crank."
},
{
"code": 6038,
"name": "AggregatorLockedError",
"msg": "Aggregator is locked, no setting modifications or job additions allowed."
},
{
"code": 6039,
"name": "AggregatorInvalidBatchSizeError",
"msg": "Aggregator invalid batch size."
},
{
"code": 6040,
"name": "AggregatorJobChecksumMismatch",
"msg": "Oracle provided an incorrect aggregator job checksum."
},
{
"code": 6041,
"name": "IntegerOverflowError",
"msg": "An integer overflow occurred."
},
{
"code": 6042,
"name": "InvalidUpdatePeriodError",
"msg": "Minimum update period is 5 seconds."
},
{
"code": 6043,
"name": "NoResultsError",
"msg": "Aggregator round evaluation attempted with no results."
},
{
"code": 6044,
"name": "InvalidExpirationError",
"msg": "An expiration constraint was broken."
},
{
"code": 6045,
"name": "InsufficientStakeError",
"msg": "An account provided insufficient stake for action."
},
{
"code": 6046,
"name": "LeaseInactiveError",
"msg": "The provided lease account is not active."
},
{
"code": 6047,
"name": "NoAggregatorJobsFound",
"msg": "No jobs are currently included in the aggregator."
},
{
"code": 6048,
"name": "IntegerUnderflowError",
"msg": "An integer underflow occurred."
},
{
"code": 6049,
"name": "OracleQueueMismatch",
"msg": "An invalid oracle queue account was provided."
},
{
"code": 6050,
"name": "OracleWalletMismatchError",
"msg": "An unexpected oracle wallet account was provided for the transaction."
},
{
"code": 6051,
"name": "InvalidBufferAccountError",
"msg": "An invalid buffer account was provided."
},
{
"code": 6052,
"name": "InsufficientOracleQueueError",
"msg": "Insufficient oracle queue size."
},
{
"code": 6053,
"name": "InvalidAuthorityError",
"msg": "Invalid authority account provided."
},
{
"code": 6054,
"name": "InvalidTokenAccountMintError",
"msg": "A provided token wallet is associated with an incorrect mint."
},
{
"code": 6055,
"name": "ExcessiveLeaseWithdrawlError",
"msg": "You must leave enough funds to perform at least 1 update in the lease."
},
{
"code": 6056,
"name": "InvalideHistoryAccountError",
"msg": "Invalid history account provided."
},
{
"code": 6057,
"name": "InvalidLeaseAccountEscrowError",
"msg": "Invalid lease account escrow."
},
{
"code": 6058,
"name": "InvalidCrankAccountError",
"msg": "Invalid crank provided."
},
{
"code": 6059,
"name": "CrankNoElementsReadyError",
"msg": "No elements ready to be popped."
},
{
"code": 6060,
"name": "IndexOutOfBoundsError",
"msg": "Index out of bounds"
},
{
"code": 6061,
"name": "VrfInvalidRequestError",
"msg": "Invalid vrf request params"
},
{
"code": 6062,
"name": "VrfInvalidProofSubmissionError",
"msg": "Vrf proof failed to verify"
},
{
"code": 6063,
"name": "VrfVerifyError",
"msg": "Error in verifying vrf proof."
},
{
"code": 6064,
"name": "VrfCallbackError",
"msg": "Vrf callback function failed."
},
{
"code": 6065,
"name": "VrfCallbackParamsError",
"msg": "Invalid vrf callback params provided."
},
{
"code": 6066,
"name": "VrfCallbackAlreadyCalledError",
"msg": "Vrf callback has already been triggered."
},
{
"code": 6067,
"name": "VrfInvalidPubkeyError",
"msg": "The provided pubkey is invalid to use in ecvrf proofs"
},
{
"code": 6068,
"name": "VrfTooManyVerifyCallsError",
"msg": "Number of required verify calls exceeded"
},
{
"code": 6069,
"name": "VrfRequestAlreadyLaunchedError",
"msg": "Vrf request is already pending"
},
{
"code": 6070,
"name": "VrfInsufficientVerificationError",
"msg": "Insufficient amount of proofs collected for VRF callback"
},
{
"code": 6071,
"name": "InvalidVrfProducerError",
"msg": "An incorrect oracle attempted to submit a proof"
},
{
"code": 6072,
"name": "InvalidGovernancePidError",
"msg": "Invalid SPLGovernance Account Supplied"
},
{
"code": 6073,
"name": "InvalidGovernanceAccountError",
"msg": "An Invalid Governance Account was supplied"
},
{
"code": 6074,
"name": "MissingOptionalAccount",
"msg": "Expected an optional account"
},
{
"code": 6075,
"name": "InvalidSpawnRecordOwner",
"msg": "Invalid Owner for Spawn Record"
},
{
"code": 6076,
"name": "NoopError",
"msg": "Noop error"
},
{
"code": 6077,
"name": "MissingRequiredAccountsError",
"msg": "A required instruction account was not included"
},
{
"code": 6078,
"name": "InvalidMintError",
"msg": "Invalid mint account passed for instruction"
},
{
"code": 6079,
"name": "InvalidTokenAccountKeyError",
"msg": "An invalid token account was passed into the instruction"
},
{
"code": 6080,
"name": "InvalidJobAccountError",
"msg": ""
},
{
"code": 6081,
"name": "VoterStakeRegistryError",
"msg": ""
},
{
"code": 6082,
"name": "AccountDiscriminatorMismatch",
"msg": "Account discriminator did not match."
},
{
"code": 6083,
"name": "FuckingImpossibleError",
"msg": "This error is fucking impossible."
},
{
"code": 6084,
"name": "InvalidVrfRound",
"msg": "Responding to the wrong VRF round"
},
{
"code": 6085,
"name": "JobSizeExceeded",
"msg": "Job size has exceeded the max of 6400 bytes"
},
{
"code": 6086,
"name": "JobChunksExceeded",
"msg": "Job loading can only support a maximum of 8 chunks"
},
{
"code": 6087,
"name": "JobDataLocked",
"msg": "Job has finished initializing and is immutable"
},
{
"code": 6088,
"name": "JobNotInitialized",
"msg": "Job account has not finished initializing"
},
{
"code": 6089,
"name": "BufferRelayerIllegalRoundOpenCall",
"msg": "BufferRelayer round open called too early."
},
{
"code": 6090,
"name": "InvalidSliderAccount",
"msg": "Invalid slider account."
},
{
"code": 6091,
"name": "VrfLiteHasExistingPool",
"msg": "VRF lite account belongs to an existing pool."
},
{
"code": 6092,
"name": "VrfPoolFull",
"msg": "VRF pool is at max capacity."
},
{
"code": 6093,
"name": "VrfPoolEmpty",
"msg": "VRF pool is empty."
},
{
"code": 6094,
"name": "VrfAccountNotFound",
"msg": "Failed to find VRF account in remaining accounts array."
},
{
"code": 6095,
"name": "AccountCloseNotReady",
"msg": "Account is not ready to be closed."
},
{
"code": 6096,
"name": "VrfPoolRequestTooSoon",
"msg": "VRF requested too soon."
},
{
"code": 6097,
"name": "VrfPoolMiss",
"msg": "VRF pool miss."
},
{
"code": 6098,
"name": "VrfLiteOwnedByPool",
"msg": "VRF lite belongs to a pool."
},
{
"code": 6099,
"name": "InsufficientTokenBalance",
"msg": "Escrow has insufficient funds to perform this action."
},
{
"code": 6100,
"name": "InvalidQuoteError",
"msg": "Invalid SAS quote account"
},
{
"code": 6101,
"name": "InvalidHistoryAccountError",
"msg": ""
},
{
"code": 6102,
"name": "GenericError",
"msg": ""
},
{
"code": 6103,
"name": "InvalidAuthorityState",
"msg": ""
}
]
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/idl/openbook.json
|
{
"version": "0.1.0",
"name": "openbook_v2",
"instructions": [
{
"name": "createMarket",
"docs": [
"Create a [`Market`](crate::state::Market) for a given token pair."
],
"accounts": [
{
"name": "market",
"isMut": true,
"isSigner": true
},
{
"name": "marketAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false,
"docs": [
"Accounts are initialized by client,",
"anchor discriminator is set first when ix exits,"
]
},
{
"name": "asks",
"isMut": true,
"isSigner": false
},
{
"name": "eventHeap",
"isMut": true,
"isSigner": false
},
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "marketBaseVault",
"isMut": true,
"isSigner": false
},
{
"name": "marketQuoteVault",
"isMut": true,
"isSigner": false
},
{
"name": "baseMint",
"isMut": false,
"isSigner": false
},
{
"name": "quoteMint",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "associatedTokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "oracleA",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "oracleB",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "collectFeeAdmin",
"isMut": false,
"isSigner": false
},
{
"name": "openOrdersAdmin",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "consumeEventsAdmin",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "closeMarketAdmin",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "eventAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "program",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "name",
"type": "string"
},
{
"name": "oracleConfig",
"type": {
"defined": "OracleConfigParams"
}
},
{
"name": "quoteLotSize",
"type": "i64"
},
{
"name": "baseLotSize",
"type": "i64"
},
{
"name": "makerFee",
"type": "i64"
},
{
"name": "takerFee",
"type": "i64"
},
{
"name": "timeExpiry",
"type": "i64"
}
]
},
{
"name": "closeMarket",
"docs": [
"Close a [`Market`](crate::state::Market) (only",
"[`close_market_admin`](crate::state::Market::close_market_admin))."
],
"accounts": [
{
"name": "closeMarketAdmin",
"isMut": false,
"isSigner": true
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false
},
{
"name": "asks",
"isMut": true,
"isSigner": false
},
{
"name": "eventHeap",
"isMut": true,
"isSigner": false
},
{
"name": "solDestination",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "createOpenOrdersIndexer",
"docs": [
"Create an [`OpenOrdersIndexer`](crate::state::OpenOrdersIndexer) account."
],
"accounts": [
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "owner",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersIndexer",
"isMut": true,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "closeOpenOrdersIndexer",
"docs": [
"Close an [`OpenOrdersIndexer`](crate::state::OpenOrdersIndexer) account."
],
"accounts": [
{
"name": "owner",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersIndexer",
"isMut": true,
"isSigner": false
},
{
"name": "solDestination",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "createOpenOrdersAccount",
"docs": [
"Create an [`OpenOrdersAccount`](crate::state::OpenOrdersAccount)."
],
"accounts": [
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "owner",
"isMut": false,
"isSigner": true
},
{
"name": "delegateAccount",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "openOrdersIndexer",
"isMut": true,
"isSigner": false
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "name",
"type": "string"
}
]
},
{
"name": "closeOpenOrdersAccount",
"docs": [
"Close an [`OpenOrdersAccount`](crate::state::OpenOrdersAccount)."
],
"accounts": [
{
"name": "owner",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersIndexer",
"isMut": true,
"isSigner": false
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "solDestination",
"isMut": true,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "placeOrder",
"docs": [
"Place an order.",
"",
"Different types of orders have different effects on the order book,",
"as described in [`PlaceOrderType`](crate::state::PlaceOrderType).",
"",
"`price_lots` refers to the price in lots: the number of quote lots",
"per base lot. It is ignored for `PlaceOrderType::Market` orders.",
"",
"`expiry_timestamp` is a unix timestamp for when this order should",
"expire. If 0 is passed in, the order will never expire. If the time",
"is in the past, the instruction is skipped. Timestamps in the future",
"are reduced to now + 65,535s.",
"",
"`limit` determines the maximum number of orders from the book to fill,",
"and can be used to limit CU spent. When the limit is reached, processing",
"stops and the instruction succeeds."
],
"accounts": [
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "openOrdersAdmin",
"isMut": false,
"isSigner": true,
"isOptional": true
},
{
"name": "userTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false
},
{
"name": "asks",
"isMut": true,
"isSigner": false
},
{
"name": "eventHeap",
"isMut": true,
"isSigner": false
},
{
"name": "marketVault",
"isMut": true,
"isSigner": false
},
{
"name": "oracleA",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "oracleB",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "args",
"type": {
"defined": "PlaceOrderArgs"
}
}
],
"returns": {
"option": "u128"
}
},
{
"name": "editOrder",
"docs": [
"Edit an order."
],
"accounts": [
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "openOrdersAdmin",
"isMut": false,
"isSigner": true,
"isOptional": true
},
{
"name": "userTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false
},
{
"name": "asks",
"isMut": true,
"isSigner": false
},
{
"name": "eventHeap",
"isMut": true,
"isSigner": false
},
{
"name": "marketVault",
"isMut": true,
"isSigner": false
},
{
"name": "oracleA",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "oracleB",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "clientOrderId",
"type": "u64"
},
{
"name": "expectedCancelSize",
"type": "i64"
},
{
"name": "placeOrder",
"type": {
"defined": "PlaceOrderArgs"
}
}
],
"returns": {
"option": "u128"
}
},
{
"name": "editOrderPegged",
"docs": [
"Edit an order pegged."
],
"accounts": [
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "openOrdersAdmin",
"isMut": false,
"isSigner": true,
"isOptional": true
},
{
"name": "userTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false
},
{
"name": "asks",
"isMut": true,
"isSigner": false
},
{
"name": "eventHeap",
"isMut": true,
"isSigner": false
},
{
"name": "marketVault",
"isMut": true,
"isSigner": false
},
{
"name": "oracleA",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "oracleB",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "clientOrderId",
"type": "u64"
},
{
"name": "expectedCancelSize",
"type": "i64"
},
{
"name": "placeOrder",
"type": {
"defined": "PlaceOrderPeggedArgs"
}
}
],
"returns": {
"option": "u128"
}
},
{
"name": "placeOrders",
"docs": [
"Place multiple orders"
],
"accounts": [
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "openOrdersAdmin",
"isMut": false,
"isSigner": true,
"isOptional": true
},
{
"name": "userQuoteAccount",
"isMut": true,
"isSigner": false
},
{
"name": "userBaseAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false
},
{
"name": "asks",
"isMut": true,
"isSigner": false
},
{
"name": "eventHeap",
"isMut": true,
"isSigner": false
},
{
"name": "marketQuoteVault",
"isMut": true,
"isSigner": false
},
{
"name": "marketBaseVault",
"isMut": true,
"isSigner": false
},
{
"name": "oracleA",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "oracleB",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "ordersType",
"type": {
"defined": "PlaceOrderType"
}
},
{
"name": "bids",
"type": {
"vec": {
"defined": "PlaceMultipleOrdersArgs"
}
}
},
{
"name": "asks",
"type": {
"vec": {
"defined": "PlaceMultipleOrdersArgs"
}
}
},
{
"name": "limit",
"type": "u8"
}
],
"returns": {
"vec": {
"option": "u128"
}
}
},
{
"name": "cancelAllAndPlaceOrders",
"docs": [
"Cancel orders and place multiple orders."
],
"accounts": [
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "openOrdersAdmin",
"isMut": false,
"isSigner": true,
"isOptional": true
},
{
"name": "userQuoteAccount",
"isMut": true,
"isSigner": false
},
{
"name": "userBaseAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false
},
{
"name": "asks",
"isMut": true,
"isSigner": false
},
{
"name": "eventHeap",
"isMut": true,
"isSigner": false
},
{
"name": "marketQuoteVault",
"isMut": true,
"isSigner": false
},
{
"name": "marketBaseVault",
"isMut": true,
"isSigner": false
},
{
"name": "oracleA",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "oracleB",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "ordersType",
"type": {
"defined": "PlaceOrderType"
}
},
{
"name": "bids",
"type": {
"vec": {
"defined": "PlaceMultipleOrdersArgs"
}
}
},
{
"name": "asks",
"type": {
"vec": {
"defined": "PlaceMultipleOrdersArgs"
}
}
},
{
"name": "limit",
"type": "u8"
}
],
"returns": {
"vec": {
"option": "u128"
}
}
},
{
"name": "placeOrderPegged",
"docs": [
"Place an oracle-peg order."
],
"accounts": [
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "openOrdersAdmin",
"isMut": false,
"isSigner": true,
"isOptional": true
},
{
"name": "userTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false
},
{
"name": "asks",
"isMut": true,
"isSigner": false
},
{
"name": "eventHeap",
"isMut": true,
"isSigner": false
},
{
"name": "marketVault",
"isMut": true,
"isSigner": false
},
{
"name": "oracleA",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "oracleB",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "args",
"type": {
"defined": "PlaceOrderPeggedArgs"
}
}
],
"returns": {
"option": "u128"
}
},
{
"name": "placeTakeOrder",
"docs": [
"Place an order that shall take existing liquidity off of the book, not",
"add a new order off the book.",
"",
"This type of order allows for instant token settlement for the taker."
],
"accounts": [
{
"name": "signer",
"isMut": true,
"isSigner": true
},
{
"name": "penaltyPayer",
"isMut": true,
"isSigner": true
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "marketAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false
},
{
"name": "asks",
"isMut": true,
"isSigner": false
},
{
"name": "marketBaseVault",
"isMut": true,
"isSigner": false
},
{
"name": "marketQuoteVault",
"isMut": true,
"isSigner": false
},
{
"name": "eventHeap",
"isMut": true,
"isSigner": false
},
{
"name": "userBaseAccount",
"isMut": true,
"isSigner": false
},
{
"name": "userQuoteAccount",
"isMut": true,
"isSigner": false
},
{
"name": "oracleA",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "oracleB",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "openOrdersAdmin",
"isMut": false,
"isSigner": true,
"isOptional": true
}
],
"args": [
{
"name": "args",
"type": {
"defined": "PlaceTakeOrderArgs"
}
}
]
},
{
"name": "consumeEvents",
"docs": [
"Process up to `limit` [events](crate::state::AnyEvent).",
"",
"When a user places a 'take' order, they do not know beforehand which",
"market maker will have placed the 'make' order that they get executed",
"against. This prevents them from passing in a market maker's",
"[`OpenOrdersAccount`](crate::state::OpenOrdersAccount), which is needed",
"to credit/debit the relevant tokens to/from the maker. As such, Openbook",
"uses a 'crank' system, where `place_order` only emits events, and",
"`consume_events` handles token settlement.",
"",
"Currently, there are two types of events: [`FillEvent`](crate::state::FillEvent)s",
"and [`OutEvent`](crate::state::OutEvent)s.",
"",
"A `FillEvent` is emitted when an order is filled, and it is handled by",
"debiting whatever the taker is selling from the taker and crediting",
"it to the maker, and debiting whatever the taker is buying from the",
"maker and crediting it to the taker. Note that *no tokens are moved*,",
"these are just debits and credits to each party's [`Position`](crate::state::Position).",
"",
"An `OutEvent` is emitted when a limit order needs to be removed from",
"the book during a `place_order` invocation, and it is handled by",
"crediting whatever the maker would have sold (quote token in a bid,",
"base token in an ask) back to the maker."
],
"accounts": [
{
"name": "consumeEventsAdmin",
"isMut": false,
"isSigner": true,
"isOptional": true
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "eventHeap",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "limit",
"type": "u64"
}
]
},
{
"name": "consumeGivenEvents",
"docs": [
"Process the [events](crate::state::AnyEvent) at the given positions."
],
"accounts": [
{
"name": "consumeEventsAdmin",
"isMut": false,
"isSigner": true,
"isOptional": true
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "eventHeap",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "slots",
"type": {
"vec": "u64"
}
}
]
},
{
"name": "cancelOrder",
"docs": [
"Cancel an order by its `order_id`.",
"",
"Note that this doesn't emit an [`OutEvent`](crate::state::OutEvent) because a",
"maker knows that they will be passing in their own [`OpenOrdersAccount`](crate::state::OpenOrdersAccount)."
],
"accounts": [
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": false,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false
},
{
"name": "asks",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "orderId",
"type": "u128"
}
]
},
{
"name": "cancelOrderByClientOrderId",
"docs": [
"Cancel an order by its `client_order_id`.",
"",
"Note that this doesn't emit an [`OutEvent`](crate::state::OutEvent) because a",
"maker knows that they will be passing in their own [`OpenOrdersAccount`](crate::state::OpenOrdersAccount)."
],
"accounts": [
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": false,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false
},
{
"name": "asks",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "clientOrderId",
"type": "u64"
}
],
"returns": "i64"
},
{
"name": "cancelAllOrders",
"docs": [
"Cancel up to `limit` orders, optionally filtering by side"
],
"accounts": [
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": false,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false
},
{
"name": "asks",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "sideOption",
"type": {
"option": {
"defined": "Side"
}
}
},
{
"name": "limit",
"type": "u8"
}
]
},
{
"name": "deposit",
"docs": [
"Deposit a certain amount of `base` and `quote` lamports into one's",
"[`Position`](crate::state::Position).",
"",
"Makers might wish to `deposit`, rather than have actual tokens moved for",
"each trade, in order to reduce CUs."
],
"accounts": [
{
"name": "owner",
"isMut": false,
"isSigner": true
},
{
"name": "userBaseAccount",
"isMut": true,
"isSigner": false
},
{
"name": "userQuoteAccount",
"isMut": true,
"isSigner": false
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "marketBaseVault",
"isMut": true,
"isSigner": false
},
{
"name": "marketQuoteVault",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "baseAmount",
"type": "u64"
},
{
"name": "quoteAmount",
"type": "u64"
}
]
},
{
"name": "refill",
"docs": [
"Refill a certain amount of `base` and `quote` lamports. The amount being passed is the",
"total lamports that the [`Position`](crate::state::Position) will have.",
"",
"Makers might wish to `refill`, rather than have actual tokens moved for",
"each trade, in order to reduce CUs."
],
"accounts": [
{
"name": "owner",
"isMut": false,
"isSigner": true
},
{
"name": "userBaseAccount",
"isMut": true,
"isSigner": false
},
{
"name": "userQuoteAccount",
"isMut": true,
"isSigner": false
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "marketBaseVault",
"isMut": true,
"isSigner": false
},
{
"name": "marketQuoteVault",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "baseAmount",
"type": "u64"
},
{
"name": "quoteAmount",
"type": "u64"
}
]
},
{
"name": "settleFunds",
"docs": [
"Withdraw any available tokens."
],
"accounts": [
{
"name": "owner",
"isMut": true,
"isSigner": true
},
{
"name": "penaltyPayer",
"isMut": true,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "marketAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "marketBaseVault",
"isMut": true,
"isSigner": false
},
{
"name": "marketQuoteVault",
"isMut": true,
"isSigner": false
},
{
"name": "userBaseAccount",
"isMut": true,
"isSigner": false
},
{
"name": "userQuoteAccount",
"isMut": true,
"isSigner": false
},
{
"name": "referrerAccount",
"isMut": true,
"isSigner": false,
"isOptional": true
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "settleFundsExpired",
"docs": [
"Withdraw any available tokens when the market is expired (only",
"[`close_market_admin`](crate::state::Market::close_market_admin))."
],
"accounts": [
{
"name": "closeMarketAdmin",
"isMut": false,
"isSigner": true
},
{
"name": "owner",
"isMut": true,
"isSigner": true
},
{
"name": "penaltyPayer",
"isMut": true,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "marketAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "marketBaseVault",
"isMut": true,
"isSigner": false
},
{
"name": "marketQuoteVault",
"isMut": true,
"isSigner": false
},
{
"name": "userBaseAccount",
"isMut": true,
"isSigner": false
},
{
"name": "userQuoteAccount",
"isMut": true,
"isSigner": false
},
{
"name": "referrerAccount",
"isMut": true,
"isSigner": false,
"isOptional": true
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "sweepFees",
"docs": [
"Sweep fees, as a [`Market`](crate::state::Market)'s admin."
],
"accounts": [
{
"name": "collectFeeAdmin",
"isMut": false,
"isSigner": true
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "marketAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "marketQuoteVault",
"isMut": true,
"isSigner": false
},
{
"name": "tokenReceiverAccount",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "setDelegate",
"docs": [
"Update the [`delegate`](crate::state::OpenOrdersAccount::delegate) of an open orders account."
],
"accounts": [
{
"name": "owner",
"isMut": true,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "delegateAccount",
"isMut": false,
"isSigner": false,
"isOptional": true
}
],
"args": []
},
{
"name": "setMarketExpired",
"docs": [
"Set market to expired before pruning orders and closing the market (only",
"[`close_market_admin`](crate::state::Market::close_market_admin))."
],
"accounts": [
{
"name": "closeMarketAdmin",
"isMut": false,
"isSigner": true
},
{
"name": "market",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "pruneOrders",
"docs": [
"Remove orders from the book when the market is expired (only",
"[`close_market_admin`](crate::state::Market::close_market_admin))."
],
"accounts": [
{
"name": "closeMarketAdmin",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": false,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false
},
{
"name": "asks",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "limit",
"type": "u8"
}
]
},
{
"name": "stubOracleCreate",
"accounts": [
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "owner",
"isMut": false,
"isSigner": true
},
{
"name": "oracle",
"isMut": true,
"isSigner": false
},
{
"name": "mint",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "price",
"type": "f64"
}
]
},
{
"name": "stubOracleClose",
"accounts": [
{
"name": "owner",
"isMut": false,
"isSigner": true
},
{
"name": "oracle",
"isMut": true,
"isSigner": false
},
{
"name": "solDestination",
"isMut": true,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "stubOracleSet",
"accounts": [
{
"name": "owner",
"isMut": false,
"isSigner": true
},
{
"name": "oracle",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "price",
"type": "f64"
}
]
}
],
"accounts": [
{
"name": "Market",
"type": {
"kind": "struct",
"fields": [
{
"name": "bump",
"docs": [
"PDA bump"
],
"type": "u8"
},
{
"name": "baseDecimals",
"docs": [
"Number of decimals used for the base token.",
"",
"Used to convert the oracle's price into a native/native price."
],
"type": "u8"
},
{
"name": "quoteDecimals",
"type": "u8"
},
{
"name": "padding1",
"type": {
"array": [
"u8",
5
]
}
},
{
"name": "marketAuthority",
"type": "publicKey"
},
{
"name": "timeExpiry",
"docs": [
"No expiry = 0. Market will expire and no trading allowed after time_expiry"
],
"type": "i64"
},
{
"name": "collectFeeAdmin",
"docs": [
"Admin who can collect fees from the market"
],
"type": "publicKey"
},
{
"name": "openOrdersAdmin",
"docs": [
"Admin who must sign off on all order creations"
],
"type": {
"defined": "NonZeroPubkeyOption"
}
},
{
"name": "consumeEventsAdmin",
"docs": [
"Admin who must sign off on all event consumptions"
],
"type": {
"defined": "NonZeroPubkeyOption"
}
},
{
"name": "closeMarketAdmin",
"docs": [
"Admin who can set market expired, prune orders and close the market"
],
"type": {
"defined": "NonZeroPubkeyOption"
}
},
{
"name": "name",
"docs": [
"Name. Trailing zero bytes are ignored."
],
"type": {
"array": [
"u8",
16
]
}
},
{
"name": "bids",
"docs": [
"Address of the BookSide account for bids"
],
"type": "publicKey"
},
{
"name": "asks",
"docs": [
"Address of the BookSide account for asks"
],
"type": "publicKey"
},
{
"name": "eventHeap",
"docs": [
"Address of the EventHeap account"
],
"type": "publicKey"
},
{
"name": "oracleA",
"docs": [
"Oracles account address"
],
"type": {
"defined": "NonZeroPubkeyOption"
}
},
{
"name": "oracleB",
"type": {
"defined": "NonZeroPubkeyOption"
}
},
{
"name": "oracleConfig",
"docs": [
"Oracle configuration"
],
"type": {
"defined": "OracleConfig"
}
},
{
"name": "quoteLotSize",
"docs": [
"Number of quote native in a quote lot. Must be a power of 10.",
"",
"Primarily useful for increasing the tick size on the market: A lot price",
"of 1 becomes a native price of quote_lot_size/base_lot_size becomes a",
"ui price of quote_lot_size*base_decimals/base_lot_size/quote_decimals."
],
"type": "i64"
},
{
"name": "baseLotSize",
"docs": [
"Number of base native in a base lot. Must be a power of 10.",
"",
"Example: If base decimals for the underlying asset is 6, base lot size",
"is 100 and and base position lots is 10_000 then base position native is",
"1_000_000 and base position ui is 1."
],
"type": "i64"
},
{
"name": "seqNum",
"docs": [
"Total number of orders seen"
],
"type": "u64"
},
{
"name": "registrationTime",
"docs": [
"Timestamp in seconds that the market was registered at."
],
"type": "i64"
},
{
"name": "makerFee",
"docs": [
"Fees",
"",
"Fee (in 10^-6) when matching maker orders.",
"maker_fee < 0 it means some of the taker_fees goes to the maker",
"maker_fee > 0, it means no taker_fee to the maker, and maker fee goes to the referral"
],
"type": "i64"
},
{
"name": "takerFee",
"docs": [
"Fee (in 10^-6) for taker orders, always >= 0."
],
"type": "i64"
},
{
"name": "feesAccrued",
"docs": [
"Total fees accrued in native quote"
],
"type": "u128"
},
{
"name": "feesToReferrers",
"docs": [
"Total fees settled in native quote"
],
"type": "u128"
},
{
"name": "referrerRebatesAccrued",
"docs": [
"Referrer rebates to be distributed"
],
"type": "u64"
},
{
"name": "feesAvailable",
"docs": [
"Fees generated and available to withdraw via sweep_fees"
],
"type": "u64"
},
{
"name": "makerVolume",
"docs": [
"Cumulative maker volume (same as taker volume) in quote native units"
],
"type": "u128"
},
{
"name": "takerVolumeWoOo",
"docs": [
"Cumulative taker volume in quote native units due to place take orders"
],
"type": "u128"
},
{
"name": "baseMint",
"type": "publicKey"
},
{
"name": "quoteMint",
"type": "publicKey"
},
{
"name": "marketBaseVault",
"type": "publicKey"
},
{
"name": "baseDepositTotal",
"type": "u64"
},
{
"name": "marketQuoteVault",
"type": "publicKey"
},
{
"name": "quoteDepositTotal",
"type": "u64"
},
{
"name": "reserved",
"type": {
"array": [
"u8",
128
]
}
}
]
}
},
{
"name": "OpenOrdersAccount",
"type": {
"kind": "struct",
"fields": [
{
"name": "owner",
"type": "publicKey"
},
{
"name": "market",
"type": "publicKey"
},
{
"name": "name",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "delegate",
"type": {
"defined": "NonZeroPubkeyOption"
}
},
{
"name": "accountNum",
"type": "u32"
},
{
"name": "bump",
"type": "u8"
},
{
"name": "version",
"type": "u8"
},
{
"name": "padding",
"type": {
"array": [
"u8",
2
]
}
},
{
"name": "position",
"type": {
"defined": "Position"
}
},
{
"name": "openOrders",
"type": {
"array": [
{
"defined": "OpenOrder"
},
24
]
}
}
]
}
},
{
"name": "OpenOrdersIndexer",
"type": {
"kind": "struct",
"fields": [
{
"name": "bump",
"type": "u8"
},
{
"name": "createdCounter",
"type": "u32"
},
{
"name": "addresses",
"type": {
"vec": "publicKey"
}
}
]
}
},
{
"name": "StubOracle",
"type": {
"kind": "struct",
"fields": [
{
"name": "owner",
"type": "publicKey"
},
{
"name": "mint",
"type": "publicKey"
},
{
"name": "price",
"type": "f64"
},
{
"name": "lastUpdateTs",
"type": "i64"
},
{
"name": "lastUpdateSlot",
"type": "u64"
},
{
"name": "deviation",
"type": "f64"
},
{
"name": "reserved",
"type": {
"array": [
"u8",
104
]
}
}
]
}
},
{
"name": "BookSide",
"type": {
"kind": "struct",
"fields": [
{
"name": "roots",
"type": {
"array": [
{
"defined": "OrderTreeRoot"
},
2
]
}
},
{
"name": "reservedRoots",
"type": {
"array": [
{
"defined": "OrderTreeRoot"
},
4
]
}
},
{
"name": "reserved",
"type": {
"array": [
"u8",
256
]
}
},
{
"name": "nodes",
"type": {
"defined": "OrderTreeNodes"
}
}
]
}
},
{
"name": "EventHeap",
"docs": [
"Container for the different EventTypes.",
"",
"Events are stored in a fixed-array of nodes. Free nodes are connected by a single-linked list",
"starting at free_head while used nodes form a circular doubly-linked list starting at",
"used_head."
],
"type": {
"kind": "struct",
"fields": [
{
"name": "header",
"type": {
"defined": "EventHeapHeader"
}
},
{
"name": "nodes",
"type": {
"array": [
{
"defined": "EventNode"
},
600
]
}
},
{
"name": "reserved",
"type": {
"array": [
"u8",
64
]
}
}
]
}
}
],
"types": [
{
"name": "NonZeroPubkeyOption",
"docs": [
"Like `Option`, but implemented for `Pubkey` to be used with `zero_copy`"
],
"type": {
"kind": "struct",
"fields": [
{
"name": "key",
"type": "publicKey"
}
]
}
},
{
"name": "Position",
"type": {
"kind": "struct",
"fields": [
{
"name": "bidsBaseLots",
"docs": [
"Base lots in open bids"
],
"type": "i64"
},
{
"name": "asksBaseLots",
"docs": [
"Base lots in open asks"
],
"type": "i64"
},
{
"name": "baseFreeNative",
"type": "u64"
},
{
"name": "quoteFreeNative",
"type": "u64"
},
{
"name": "lockedMakerFees",
"type": "u64"
},
{
"name": "referrerRebatesAvailable",
"type": "u64"
},
{
"name": "penaltyHeapCount",
"docs": [
"Count of ixs when events are added to the heap",
"To avoid this, send remaining accounts in order to process the events"
],
"type": "u64"
},
{
"name": "makerVolume",
"docs": [
"Cumulative maker volume in quote native units (display only)"
],
"type": "u128"
},
{
"name": "takerVolume",
"docs": [
"Cumulative taker volume in quote native units (display only)"
],
"type": "u128"
},
{
"name": "bidsQuoteLots",
"docs": [
"Quote lots in open bids"
],
"type": "i64"
},
{
"name": "reserved",
"type": {
"array": [
"u8",
64
]
}
}
]
}
},
{
"name": "OpenOrder",
"type": {
"kind": "struct",
"fields": [
{
"name": "id",
"type": "u128"
},
{
"name": "clientId",
"type": "u64"
},
{
"name": "lockedPrice",
"docs": [
"Price at which user's assets were locked"
],
"type": "i64"
},
{
"name": "isFree",
"type": "u8"
},
{
"name": "sideAndTree",
"type": "u8"
},
{
"name": "padding",
"type": {
"array": [
"u8",
6
]
}
}
]
}
},
{
"name": "OracleConfig",
"type": {
"kind": "struct",
"fields": [
{
"name": "confFilter",
"type": "f64"
},
{
"name": "maxStalenessSlots",
"type": "i64"
},
{
"name": "reserved",
"type": {
"array": [
"u8",
72
]
}
}
]
}
},
{
"name": "OracleConfigParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "confFilter",
"type": "f32"
},
{
"name": "maxStalenessSlots",
"type": {
"option": "u32"
}
}
]
}
},
{
"name": "EventHeapHeader",
"type": {
"kind": "struct",
"fields": [
{
"name": "freeHead",
"type": "u16"
},
{
"name": "usedHead",
"type": "u16"
},
{
"name": "count",
"type": "u16"
},
{
"name": "padd",
"type": "u16"
},
{
"name": "seqNum",
"type": "u64"
}
]
}
},
{
"name": "EventNode",
"type": {
"kind": "struct",
"fields": [
{
"name": "next",
"type": "u16"
},
{
"name": "prev",
"type": "u16"
},
{
"name": "pad",
"type": {
"array": [
"u8",
4
]
}
},
{
"name": "event",
"type": {
"defined": "AnyEvent"
}
}
]
}
},
{
"name": "AnyEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "eventType",
"type": "u8"
},
{
"name": "padding",
"type": {
"array": [
"u8",
143
]
}
}
]
}
},
{
"name": "FillEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "eventType",
"type": "u8"
},
{
"name": "takerSide",
"type": "u8"
},
{
"name": "makerOut",
"type": "u8"
},
{
"name": "makerSlot",
"type": "u8"
},
{
"name": "padding",
"type": {
"array": [
"u8",
4
]
}
},
{
"name": "timestamp",
"type": "u64"
},
{
"name": "seqNum",
"type": "u64"
},
{
"name": "maker",
"type": "publicKey"
},
{
"name": "makerTimestamp",
"type": "u64"
},
{
"name": "taker",
"type": "publicKey"
},
{
"name": "takerClientOrderId",
"type": "u64"
},
{
"name": "price",
"type": "i64"
},
{
"name": "pegLimit",
"type": "i64"
},
{
"name": "quantity",
"type": "i64"
},
{
"name": "makerClientOrderId",
"type": "u64"
},
{
"name": "reserved",
"type": {
"array": [
"u8",
8
]
}
}
]
}
},
{
"name": "OutEvent",
"type": {
"kind": "struct",
"fields": [
{
"name": "eventType",
"type": "u8"
},
{
"name": "side",
"type": "u8"
},
{
"name": "ownerSlot",
"type": "u8"
},
{
"name": "padding0",
"type": {
"array": [
"u8",
5
]
}
},
{
"name": "timestamp",
"type": "u64"
},
{
"name": "seqNum",
"type": "u64"
},
{
"name": "owner",
"type": "publicKey"
},
{
"name": "quantity",
"type": "i64"
},
{
"name": "padding1",
"type": {
"array": [
"u8",
80
]
}
}
]
}
},
{
"name": "InnerNode",
"docs": [
"InnerNodes and LeafNodes compose the binary tree of orders.",
"",
"Each InnerNode has exactly two children, which are either InnerNodes themselves,",
"or LeafNodes. The children share the top `prefix_len` bits of `key`. The left",
"child has a 0 in the next bit, and the right a 1."
],
"type": {
"kind": "struct",
"fields": [
{
"name": "tag",
"type": "u8"
},
{
"name": "padding",
"type": {
"array": [
"u8",
3
]
}
},
{
"name": "prefixLen",
"docs": [
"number of highest `key` bits that all children share",
"e.g. if it's 2, the two highest bits of `key` will be the same on all children"
],
"type": "u32"
},
{
"name": "key",
"docs": [
"only the top `prefix_len` bits of `key` are relevant"
],
"type": "u128"
},
{
"name": "children",
"docs": [
"indexes into `BookSide::nodes`"
],
"type": {
"array": [
"u32",
2
]
}
},
{
"name": "childEarliestExpiry",
"docs": [
"The earliest expiry timestamp for the left and right subtrees.",
"",
"Needed to be able to find and remove expired orders without having to",
"iterate through the whole bookside."
],
"type": {
"array": [
"u64",
2
]
}
},
{
"name": "reserved",
"type": {
"array": [
"u8",
40
]
}
}
]
}
},
{
"name": "LeafNode",
"docs": [
"LeafNodes represent an order in the binary tree"
],
"type": {
"kind": "struct",
"fields": [
{
"name": "tag",
"docs": [
"NodeTag"
],
"type": "u8"
},
{
"name": "ownerSlot",
"docs": [
"Index into the owning OpenOrdersAccount's OpenOrders"
],
"type": "u8"
},
{
"name": "timeInForce",
"docs": [
"Time in seconds after `timestamp` at which the order expires.",
"A value of 0 means no expiry."
],
"type": "u16"
},
{
"name": "padding",
"type": {
"array": [
"u8",
4
]
}
},
{
"name": "key",
"docs": [
"The binary tree key, see new_node_key()"
],
"type": "u128"
},
{
"name": "owner",
"docs": [
"Address of the owning OpenOrdersAccount"
],
"type": "publicKey"
},
{
"name": "quantity",
"docs": [
"Number of base lots to buy or sell, always >=1"
],
"type": "i64"
},
{
"name": "timestamp",
"docs": [
"The time the order was placed"
],
"type": "u64"
},
{
"name": "pegLimit",
"docs": [
"If the effective price of an oracle pegged order exceeds this limit,",
"it will be considered invalid and may be removed.",
"",
"Only applicable in the oracle_pegged OrderTree"
],
"type": "i64"
},
{
"name": "clientOrderId",
"docs": [
"User defined id for this order, used in FillEvents"
],
"type": "u64"
}
]
}
},
{
"name": "AnyNode",
"type": {
"kind": "struct",
"fields": [
{
"name": "tag",
"type": "u8"
},
{
"name": "data",
"type": {
"array": [
"u8",
87
]
}
}
]
}
},
{
"name": "OrderTreeRoot",
"type": {
"kind": "struct",
"fields": [
{
"name": "maybeNode",
"type": "u32"
},
{
"name": "leafCount",
"type": "u32"
}
]
}
},
{
"name": "OrderTreeNodes",
"docs": [
"A binary tree on AnyNode::key()",
"",
"The key encodes the price in the top 64 bits."
],
"type": {
"kind": "struct",
"fields": [
{
"name": "orderTreeType",
"type": "u8"
},
{
"name": "padding",
"type": {
"array": [
"u8",
3
]
}
},
{
"name": "bumpIndex",
"type": "u32"
},
{
"name": "freeListLen",
"type": "u32"
},
{
"name": "freeListHead",
"type": "u32"
},
{
"name": "reserved",
"type": {
"array": [
"u8",
512
]
}
},
{
"name": "nodes",
"type": {
"array": [
{
"defined": "AnyNode"
},
1024
]
}
}
]
}
},
{
"name": "I80F48",
"docs": [
"Nothing in Rust shall use these types. They only exist so that the Anchor IDL",
"knows about them and typescript can deserialize it."
],
"type": {
"kind": "struct",
"fields": [
{
"name": "val",
"type": "i128"
}
]
}
},
{
"name": "PlaceOrderArgs",
"type": {
"kind": "struct",
"fields": [
{
"name": "side",
"type": {
"defined": "Side"
}
},
{
"name": "priceLots",
"type": "i64"
},
{
"name": "maxBaseLots",
"type": "i64"
},
{
"name": "maxQuoteLotsIncludingFees",
"type": "i64"
},
{
"name": "clientOrderId",
"type": "u64"
},
{
"name": "orderType",
"type": {
"defined": "PlaceOrderType"
}
},
{
"name": "expiryTimestamp",
"type": "u64"
},
{
"name": "selfTradeBehavior",
"type": {
"defined": "SelfTradeBehavior"
}
},
{
"name": "limit",
"type": "u8"
}
]
}
},
{
"name": "PlaceMultipleOrdersArgs",
"type": {
"kind": "struct",
"fields": [
{
"name": "priceLots",
"type": "i64"
},
{
"name": "maxQuoteLotsIncludingFees",
"type": "i64"
},
{
"name": "expiryTimestamp",
"type": "u64"
}
]
}
},
{
"name": "PlaceOrderPeggedArgs",
"type": {
"kind": "struct",
"fields": [
{
"name": "side",
"type": {
"defined": "Side"
}
},
{
"name": "priceOffsetLots",
"type": "i64"
},
{
"name": "pegLimit",
"type": "i64"
},
{
"name": "maxBaseLots",
"type": "i64"
},
{
"name": "maxQuoteLotsIncludingFees",
"type": "i64"
},
{
"name": "clientOrderId",
"type": "u64"
},
{
"name": "orderType",
"type": {
"defined": "PlaceOrderType"
}
},
{
"name": "expiryTimestamp",
"type": "u64"
},
{
"name": "selfTradeBehavior",
"type": {
"defined": "SelfTradeBehavior"
}
},
{
"name": "limit",
"type": "u8"
}
]
}
},
{
"name": "PlaceTakeOrderArgs",
"type": {
"kind": "struct",
"fields": [
{
"name": "side",
"type": {
"defined": "Side"
}
},
{
"name": "priceLots",
"type": "i64"
},
{
"name": "maxBaseLots",
"type": "i64"
},
{
"name": "maxQuoteLotsIncludingFees",
"type": "i64"
},
{
"name": "orderType",
"type": {
"defined": "PlaceOrderType"
}
},
{
"name": "limit",
"type": "u8"
}
]
}
},
{
"name": "OracleType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Pyth"
},
{
"name": "Stub"
},
{
"name": "SwitchboardV1"
},
{
"name": "SwitchboardV2"
},
{
"name": "RaydiumCLMM"
}
]
}
},
{
"name": "OrderState",
"type": {
"kind": "enum",
"variants": [
{
"name": "Valid"
},
{
"name": "Invalid"
},
{
"name": "Skipped"
}
]
}
},
{
"name": "BookSideOrderTree",
"type": {
"kind": "enum",
"variants": [
{
"name": "Fixed"
},
{
"name": "OraclePegged"
}
]
}
},
{
"name": "EventType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Fill"
},
{
"name": "Out"
}
]
}
},
{
"name": "NodeTag",
"type": {
"kind": "enum",
"variants": [
{
"name": "Uninitialized"
},
{
"name": "InnerNode"
},
{
"name": "LeafNode"
},
{
"name": "FreeNode"
},
{
"name": "LastFreeNode"
}
]
}
},
{
"name": "PlaceOrderType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Limit"
},
{
"name": "ImmediateOrCancel"
},
{
"name": "PostOnly"
},
{
"name": "Market"
},
{
"name": "PostOnlySlide"
},
{
"name": "FillOrKill"
}
]
}
},
{
"name": "PostOrderType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Limit"
},
{
"name": "PostOnly"
},
{
"name": "PostOnlySlide"
}
]
}
},
{
"name": "SelfTradeBehavior",
"docs": [
"Self trade behavior controls how taker orders interact with resting limit orders of the same account.",
"This setting has no influence on placing a resting or oracle pegged limit order that does not match",
"immediately, instead it's the responsibility of the user to correctly configure his taker orders."
],
"type": {
"kind": "enum",
"variants": [
{
"name": "DecrementTake"
},
{
"name": "CancelProvide"
},
{
"name": "AbortTransaction"
}
]
}
},
{
"name": "Side",
"type": {
"kind": "enum",
"variants": [
{
"name": "Bid"
},
{
"name": "Ask"
}
]
}
},
{
"name": "SideAndOrderTree",
"docs": [
"SideAndOrderTree is a storage optimization, so we don't need two bytes for the data"
],
"type": {
"kind": "enum",
"variants": [
{
"name": "BidFixed"
},
{
"name": "AskFixed"
},
{
"name": "BidOraclePegged"
},
{
"name": "AskOraclePegged"
}
]
}
},
{
"name": "OrderParams",
"type": {
"kind": "enum",
"variants": [
{
"name": "Market"
},
{
"name": "ImmediateOrCancel",
"fields": [
{
"name": "price_lots",
"type": "i64"
}
]
},
{
"name": "Fixed",
"fields": [
{
"name": "price_lots",
"type": "i64"
},
{
"name": "order_type",
"type": {
"defined": "PostOrderType"
}
}
]
},
{
"name": "OraclePegged",
"fields": [
{
"name": "price_offset_lots",
"type": "i64"
},
{
"name": "order_type",
"type": {
"defined": "PostOrderType"
}
},
{
"name": "peg_limit",
"type": "i64"
}
]
},
{
"name": "FillOrKill",
"fields": [
{
"name": "price_lots",
"type": "i64"
}
]
}
]
}
},
{
"name": "OrderTreeType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Bids"
},
{
"name": "Asks"
}
]
}
}
],
"events": [
{
"name": "DepositLog",
"fields": [
{
"name": "openOrdersAccount",
"type": "publicKey",
"index": false
},
{
"name": "signer",
"type": "publicKey",
"index": false
},
{
"name": "baseAmount",
"type": "u64",
"index": false
},
{
"name": "quoteAmount",
"type": "u64",
"index": false
}
]
},
{
"name": "FillLog",
"fields": [
{
"name": "market",
"type": "publicKey",
"index": false
},
{
"name": "takerSide",
"type": "u8",
"index": false
},
{
"name": "makerSlot",
"type": "u8",
"index": false
},
{
"name": "makerOut",
"type": "bool",
"index": false
},
{
"name": "timestamp",
"type": "u64",
"index": false
},
{
"name": "seqNum",
"type": "u64",
"index": false
},
{
"name": "maker",
"type": "publicKey",
"index": false
},
{
"name": "makerClientOrderId",
"type": "u64",
"index": false
},
{
"name": "makerFee",
"type": "u64",
"index": false
},
{
"name": "makerTimestamp",
"type": "u64",
"index": false
},
{
"name": "taker",
"type": "publicKey",
"index": false
},
{
"name": "takerClientOrderId",
"type": "u64",
"index": false
},
{
"name": "takerFeeCeil",
"type": "u64",
"index": false
},
{
"name": "price",
"type": "i64",
"index": false
},
{
"name": "quantity",
"type": "i64",
"index": false
}
]
},
{
"name": "MarketMetaDataLog",
"fields": [
{
"name": "market",
"type": "publicKey",
"index": false
},
{
"name": "name",
"type": "string",
"index": false
},
{
"name": "baseMint",
"type": "publicKey",
"index": false
},
{
"name": "quoteMint",
"type": "publicKey",
"index": false
},
{
"name": "baseDecimals",
"type": "u8",
"index": false
},
{
"name": "quoteDecimals",
"type": "u8",
"index": false
},
{
"name": "baseLotSize",
"type": "i64",
"index": false
},
{
"name": "quoteLotSize",
"type": "i64",
"index": false
}
]
},
{
"name": "TotalOrderFillEvent",
"fields": [
{
"name": "side",
"type": "u8",
"index": false
},
{
"name": "taker",
"type": "publicKey",
"index": false
},
{
"name": "totalQuantityPaid",
"type": "u64",
"index": false
},
{
"name": "totalQuantityReceived",
"type": "u64",
"index": false
},
{
"name": "fees",
"type": "u64",
"index": false
}
]
},
{
"name": "SetDelegateLog",
"fields": [
{
"name": "openOrdersAccount",
"type": "publicKey",
"index": false
},
{
"name": "delegate",
"type": {
"option": "publicKey"
},
"index": false
}
]
},
{
"name": "SettleFundsLog",
"fields": [
{
"name": "openOrdersAccount",
"type": "publicKey",
"index": false
},
{
"name": "baseNative",
"type": "u64",
"index": false
},
{
"name": "quoteNative",
"type": "u64",
"index": false
},
{
"name": "referrerRebate",
"type": "u64",
"index": false
},
{
"name": "referrer",
"type": {
"option": "publicKey"
},
"index": false
}
]
},
{
"name": "SweepFeesLog",
"fields": [
{
"name": "market",
"type": "publicKey",
"index": false
},
{
"name": "amount",
"type": "u64",
"index": false
},
{
"name": "receiver",
"type": "publicKey",
"index": false
}
]
},
{
"name": "OpenOrdersPositionLog",
"fields": [
{
"name": "owner",
"type": "publicKey",
"index": false
},
{
"name": "openOrdersAccountNum",
"type": "u32",
"index": false
},
{
"name": "market",
"type": "publicKey",
"index": false
},
{
"name": "bidsBaseLots",
"type": "i64",
"index": false
},
{
"name": "bidsQuoteLots",
"type": "i64",
"index": false
},
{
"name": "asksBaseLots",
"type": "i64",
"index": false
},
{
"name": "baseFreeNative",
"type": "u64",
"index": false
},
{
"name": "quoteFreeNative",
"type": "u64",
"index": false
},
{
"name": "lockedMakerFees",
"type": "u64",
"index": false
},
{
"name": "referrerRebatesAvailable",
"type": "u64",
"index": false
},
{
"name": "makerVolume",
"type": "u128",
"index": false
},
{
"name": "takerVolume",
"type": "u128",
"index": false
}
]
}
],
"errors": [
{
"code": 6000,
"name": "SomeError",
"msg": ""
},
{
"code": 6001,
"name": "InvalidInputNameLength",
"msg": "Name lenght above limit"
},
{
"code": 6002,
"name": "InvalidInputMarketExpired",
"msg": "Market cannot be created as expired"
},
{
"code": 6003,
"name": "InvalidInputMarketFees",
"msg": "Taker fees should be positive and if maker fees are negative, greater or equal to their abs value"
},
{
"code": 6004,
"name": "InvalidInputLots",
"msg": "Lots cannot be negative"
},
{
"code": 6005,
"name": "InvalidInputLotsSize",
"msg": "Lots size above market limits"
},
{
"code": 6006,
"name": "InvalidInputOrdersAmounts",
"msg": "Input amounts above limits"
},
{
"code": 6007,
"name": "InvalidInputCancelSize",
"msg": "Price lots should be greater than zero"
},
{
"code": 6008,
"name": "InvalidInputPriceLots",
"msg": "Expected cancel size should be greater than zero"
},
{
"code": 6009,
"name": "InvalidInputPegLimit",
"msg": "Peg limit should be greater than zero"
},
{
"code": 6010,
"name": "InvalidInputOrderType",
"msg": "The order type is invalid. A taker order must be Market or ImmediateOrCancel"
},
{
"code": 6011,
"name": "InvalidInputOrderId",
"msg": "Order id cannot be zero"
},
{
"code": 6012,
"name": "InvalidInputHeapSlots",
"msg": "Slot above heap limit"
},
{
"code": 6013,
"name": "InvalidOracleTypes",
"msg": "Cannot combine two oracles of different providers"
},
{
"code": 6014,
"name": "InvalidSecondOracle",
"msg": "Cannot configure secondary oracle without primary"
},
{
"code": 6015,
"name": "NoCloseMarketAdmin",
"msg": "This market does not have a `close_market_admin` and thus cannot be closed."
},
{
"code": 6016,
"name": "InvalidCloseMarketAdmin",
"msg": "The signer of this transaction is not this market's `close_market_admin`."
},
{
"code": 6017,
"name": "InvalidOpenOrdersAdmin",
"msg": "The `open_orders_admin` required by this market to sign all instructions that creates orders is missing or is not valid"
},
{
"code": 6018,
"name": "InvalidConsumeEventsAdmin",
"msg": "The `consume_events_admin` required by this market to sign all instructions that consume events is missing or is not valid"
},
{
"code": 6019,
"name": "InvalidMarketVault",
"msg": "Provided `market_vault` is invalid"
},
{
"code": 6020,
"name": "IndexerActiveOO",
"msg": "Cannot be closed due to the existence of open orders accounts"
},
{
"code": 6021,
"name": "OraclePegInvalidOracleState",
"msg": "Cannot place a peg order due to invalid oracle state"
},
{
"code": 6022,
"name": "UnknownOracleType",
"msg": "oracle type cannot be determined"
},
{
"code": 6023,
"name": "OracleConfidence",
"msg": "an oracle does not reach the confidence threshold"
},
{
"code": 6024,
"name": "OracleStale",
"msg": "an oracle is stale"
},
{
"code": 6025,
"name": "OrderIdNotFound",
"msg": "Order id not found on the orderbook"
},
{
"code": 6026,
"name": "EventHeapContainsElements",
"msg": "Event heap contains elements and market can't be closed"
},
{
"code": 6027,
"name": "InvalidOrderPostIOC",
"msg": "ImmediateOrCancel is not a PostOrderType"
},
{
"code": 6028,
"name": "InvalidOrderPostMarket",
"msg": "Market is not a PostOrderType"
},
{
"code": 6029,
"name": "WouldSelfTrade",
"msg": "would self trade"
},
{
"code": 6030,
"name": "MarketHasExpired",
"msg": "The Market has already expired."
},
{
"code": 6031,
"name": "InvalidPriceLots",
"msg": "Price lots should be greater than zero"
},
{
"code": 6032,
"name": "InvalidOraclePrice",
"msg": "Oracle price above market limits"
},
{
"code": 6033,
"name": "MarketHasNotExpired",
"msg": "The Market has not expired yet."
},
{
"code": 6034,
"name": "NoOwnerOrDelegate",
"msg": "No correct owner or delegate."
},
{
"code": 6035,
"name": "NoOwner",
"msg": "No correct owner"
},
{
"code": 6036,
"name": "OpenOrdersFull",
"msg": "No free order index in open orders account"
},
{
"code": 6037,
"name": "BookContainsElements",
"msg": "Book contains elements"
},
{
"code": 6038,
"name": "OpenOrdersOrderNotFound",
"msg": "Could not find order in user account"
},
{
"code": 6039,
"name": "InvalidPostAmount",
"msg": "Amount to post above book limits"
},
{
"code": 6040,
"name": "DisabledOraclePeg",
"msg": "Oracle peg orders are not enabled for this market"
},
{
"code": 6041,
"name": "NonEmptyMarket",
"msg": "Cannot close a non-empty market"
},
{
"code": 6042,
"name": "NonEmptyOpenOrdersPosition",
"msg": "Cannot close a non-empty open orders account"
},
{
"code": 6043,
"name": "WouldExecutePartially",
"msg": "Fill-Or-Kill order would generate a partial execution"
}
]
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/idl/pyth_solana_receiver.json
|
{
"version": "0.1.0",
"name": "pyth_solana_receiver",
"instructions": [
{
"name": "initialize",
"accounts": [
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "config",
"isMut": true,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "initialConfig",
"type": {
"defined": "Config"
}
}
]
},
{
"name": "requestGovernanceAuthorityTransfer",
"accounts": [
{
"name": "payer",
"isMut": false,
"isSigner": true
},
{
"name": "config",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "targetGovernanceAuthority",
"type": "publicKey"
}
]
},
{
"name": "acceptGovernanceAuthorityTransfer",
"accounts": [
{
"name": "payer",
"isMut": false,
"isSigner": true
},
{
"name": "config",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "setDataSources",
"accounts": [
{
"name": "payer",
"isMut": false,
"isSigner": true
},
{
"name": "config",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "validDataSources",
"type": {
"vec": {
"defined": "DataSource"
}
}
}
]
},
{
"name": "setFee",
"accounts": [
{
"name": "payer",
"isMut": false,
"isSigner": true
},
{
"name": "config",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "singleUpdateFeeInLamports",
"type": "u64"
}
]
},
{
"name": "setWormholeAddress",
"accounts": [
{
"name": "payer",
"isMut": false,
"isSigner": true
},
{
"name": "config",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "wormhole",
"type": "publicKey"
}
]
},
{
"name": "setMinimumSignatures",
"accounts": [
{
"name": "payer",
"isMut": false,
"isSigner": true
},
{
"name": "config",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "minimumSignatures",
"type": "u8"
}
]
},
{
"name": "postUpdateAtomic",
"docs": [
"Post a price update using a VAA and a MerklePriceUpdate.",
"This function allows you to post a price update in a single transaction.",
"Compared to post_update, it is less secure since you won't be able to verify all guardian signatures if you use this function because of transaction size limitations.",
"Typically, you can fit 5 guardian signatures in a transaction that uses this."
],
"accounts": [
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "guardianSet",
"isMut": false,
"isSigner": false,
"docs": [
"Instead we do the same steps in deserialize_guardian_set_checked."
]
},
{
"name": "config",
"isMut": false,
"isSigner": false
},
{
"name": "treasury",
"isMut": true,
"isSigner": false
},
{
"name": "priceUpdateAccount",
"isMut": true,
"isSigner": true,
"docs": [
"The contraint is such that either the price_update_account is uninitialized or the payer is the write_authority.",
"Pubkey::default() is the SystemProgram on Solana and it can't sign so it's impossible that price_update_account.write_authority == Pubkey::default() once the account is initialized"
]
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "writeAuthority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "PostUpdateAtomicParams"
}
}
]
},
{
"name": "postUpdate",
"docs": [
"Post a price update using an encoded_vaa account and a MerklePriceUpdate calldata.",
"This should be called after the client has already verified the Vaa via the Wormhole contract.",
"Check out target_chains/solana/cli/src/main.rs for an example of how to do this."
],
"accounts": [
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "encodedVaa",
"isMut": false,
"isSigner": false
},
{
"name": "config",
"isMut": false,
"isSigner": false
},
{
"name": "treasury",
"isMut": true,
"isSigner": false
},
{
"name": "priceUpdateAccount",
"isMut": true,
"isSigner": true,
"docs": [
"The contraint is such that either the price_update_account is uninitialized or the payer is the write_authority.",
"Pubkey::default() is the SystemProgram on Solana and it can't sign so it's impossible that price_update_account.write_authority == Pubkey::default() once the account is initialized"
]
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "writeAuthority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "PostUpdateParams"
}
}
]
},
{
"name": "reclaimRent",
"accounts": [
{
"name": "payer",
"isMut": true,
"isSigner": true
},
{
"name": "priceUpdateAccount",
"isMut": true,
"isSigner": false
}
],
"args": []
}
],
"accounts": [
{
"name": "Config",
"type": {
"kind": "struct",
"fields": [
{
"name": "governanceAuthority",
"type": "publicKey"
},
{
"name": "targetGovernanceAuthority",
"type": {
"option": "publicKey"
}
},
{
"name": "wormhole",
"type": "publicKey"
},
{
"name": "validDataSources",
"type": {
"vec": {
"defined": "DataSource"
}
}
},
{
"name": "singleUpdateFeeInLamports",
"type": "u64"
},
{
"name": "minimumSignatures",
"type": "u8"
}
]
}
},
{
"name": "priceUpdateV2",
"type": {
"kind": "struct",
"fields": [
{
"name": "writeAuthority",
"type": "publicKey"
},
{
"name": "verificationLevel",
"type": {
"defined": "VerificationLevel"
}
},
{
"name": "priceMessage",
"type": {
"defined": "PriceFeedMessage"
}
},
{
"name": "postedSlot",
"type": "u64"
}
]
}
}
],
"types": [
{
"name": "PriceFeedMessage",
"type": {
"kind": "struct",
"fields": [
{
"name": "feedId",
"type": {
"array": ["u8", 32]
}
},
{
"name": "price",
"type": "i64"
},
{
"name": "conf",
"type": "u64"
},
{
"name": "exponent",
"type": "i32"
},
{
"name": "publishTime",
"type": "i64"
},
{
"name": "prevPublishTime",
"type": "i64"
},
{
"name": "emaPrice",
"type": "i64"
},
{
"name": "emaConf",
"type": "u64"
}
]
}
},
{
"name": "MerklePriceUpdate",
"type": {
"kind": "struct",
"fields": [
{
"name": "message",
"type": "bytes"
},
{
"name": "proof",
"type": {
"vec": {
"array": ["u8", 20]
}
}
}
]
}
},
{
"name": "DataSource",
"type": {
"kind": "struct",
"fields": [
{
"name": "chain",
"type": "u16"
},
{
"name": "emitter",
"type": "publicKey"
}
]
}
},
{
"name": "PostMultiUpdatesAtomicParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "vaa",
"type": "bytes"
},
{
"name": "merklePriceUpdates",
"type": {
"vec": {
"defined": "MerklePriceUpdate"
}
}
}
]
}
},
{
"name": "PostUpdateAtomicParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "vaa",
"type": "bytes"
},
{
"name": "merklePriceUpdate",
"type": {
"defined": "MerklePriceUpdate"
}
}
]
}
},
{
"name": "PostUpdateParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "merklePriceUpdate",
"type": {
"defined": "MerklePriceUpdate"
}
}
]
}
},
{
"name": "VerificationLevel",
"docs": [
"* This enum represents how many guardian signatures were checked for a Pythnet price update\n * If full, guardian quorum has been attained\n * If partial, at least config.minimum signatures have been verified, but in the case config.minimum_signatures changes in the future we also include the number of signatures that were checked"
],
"type": {
"kind": "enum",
"variants": [
{
"name": "Partial",
"fields": [
{
"name": "numSignatures",
"type": "u8"
}
]
},
{
"name": "Full"
}
]
}
}
],
"errors": [
{
"code": 6000,
"name": "InvalidWormholeMessage",
"msg": "Received an invalid wormhole message"
},
{
"code": 6001,
"name": "DeserializeMessageFailed",
"msg": "An error occurred when deserializing the message"
},
{
"code": 6002,
"name": "InvalidPriceUpdate",
"msg": "Received an invalid price update"
},
{
"code": 6003,
"name": "UnsupportedMessageType",
"msg": "This type of message is not supported currently"
},
{
"code": 6004,
"name": "InvalidDataSource",
"msg": "The tuple emitter chain, emitter doesn't match one of the valid data sources."
},
{
"code": 6005,
"name": "InsufficientFunds",
"msg": "Funds are insufficient to pay the receiving fee"
},
{
"code": 6006,
"name": "WrongWriteAuthority",
"msg": "This signer can't write to price update account"
},
{
"code": 6007,
"name": "WrongVaaOwner",
"msg": "The posted VAA account has the wrong owner."
},
{
"code": 6008,
"name": "DeserializeVaaFailed",
"msg": "An error occurred when deserializing the VAA."
},
{
"code": 6009,
"name": "InsufficientGuardianSignatures",
"msg": "The number of guardian signatures is below the minimum"
},
{
"code": 6010,
"name": "InvalidVaaVersion",
"msg": "Invalid VAA version"
},
{
"code": 6011,
"name": "GuardianSetMismatch",
"msg": "Guardian set version in the VAA doesn't match the guardian set passed"
},
{
"code": 6012,
"name": "InvalidGuardianOrder",
"msg": "Guardian signature indices must be increasing"
},
{
"code": 6013,
"name": "InvalidGuardianIndex",
"msg": "Guardian index exceeds the number of guardians in the set"
},
{
"code": 6014,
"name": "InvalidSignature",
"msg": "A VAA signature is invalid"
},
{
"code": 6015,
"name": "InvalidGuardianKeyRecovery",
"msg": "The recovered guardian public key doesn't match the guardian set"
},
{
"code": 6016,
"name": "WrongGuardianSetOwner",
"msg": "The guardian set account is owned by the wrong program"
},
{
"code": 6017,
"name": "InvalidGuardianSetPda",
"msg": "The Guardian Set account doesn't match the PDA derivation"
},
{
"code": 6018,
"name": "GuardianSetExpired",
"msg": "The Guardian Set is expired"
},
{
"code": 6019,
"name": "GovernanceAuthorityMismatch",
"msg": "The signer is not authorized to perform this governance action"
},
{
"code": 6020,
"name": "TargetGovernanceAuthorityMismatch",
"msg": "The signer is not authorized to accept the governance authority"
},
{
"code": 6021,
"name": "NonexistentGovernanceAuthorityTransferRequest",
"msg": "The governance authority needs to request a transfer first"
}
]
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/idl/token_faucet.json
|
{
"version": "0.1.0",
"name": "token_faucet",
"instructions": [
{
"name": "initialize",
"accounts": [
{
"name": "faucetConfig",
"isMut": true,
"isSigner": false
},
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "mintAccount",
"isMut": true,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "mintToUser",
"accounts": [
{
"name": "faucetConfig",
"isMut": false,
"isSigner": false
},
{
"name": "mintAccount",
"isMut": true,
"isSigner": false
},
{
"name": "userTokenAccount",
"isMut": true,
"isSigner": false
},
{
"name": "mintAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "amount",
"type": "u64"
}
]
},
{
"name": "transferMintAuthority",
"accounts": [
{
"name": "faucetConfig",
"isMut": false,
"isSigner": false
},
{
"name": "admin",
"isMut": true,
"isSigner": true
},
{
"name": "mintAccount",
"isMut": true,
"isSigner": false
},
{
"name": "mintAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
}
],
"accounts": [
{
"name": "FaucetConfig",
"type": {
"kind": "struct",
"fields": [
{
"name": "admin",
"type": "publicKey"
},
{
"name": "mint",
"type": "publicKey"
},
{
"name": "mintAuthority",
"type": "publicKey"
},
{
"name": "mintAuthorityNonce",
"type": "u8"
}
]
}
}
],
"errors": [
{
"code": 6000,
"name": "InvalidMintAccountAuthority",
"msg": "Program not mint authority"
}
]
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/dlob/DLOB.ts
|
import { getOrderSignature, NodeList } from './NodeList';
import {
BASE_PRECISION,
BN,
BN_MAX,
convertToNumber,
decodeName,
DLOBNode,
DLOBNodeType,
DriftClient,
getLimitPrice,
getVariant,
isFallbackAvailableLiquiditySource,
isOneOfVariant,
isOrderExpired,
isRestingLimitOrder,
isTriggered,
isUserProtectedMaker,
isVariant,
MarketType,
MarketTypeStr,
mustBeTriggered,
OraclePriceData,
Order,
PerpMarketAccount,
PositionDirection,
PRICE_PRECISION,
QUOTE_PRECISION,
SlotSubscriber,
SpotMarketAccount,
StateAccount,
TriggerOrderNode,
UserMap,
ZERO,
} from '..';
import { PublicKey } from '@solana/web3.js';
import { ammPaused, exchangePaused, fillPaused } from '../math/exchangeStatus';
import {
createL2Levels,
getL2GeneratorFromDLOBNodes,
L2OrderBook,
L2OrderBookGenerator,
L3Level,
L3OrderBook,
mergeL2LevelGenerators,
} from './orderBookLevels';
export type DLOBOrder = { user: PublicKey; order: Order };
export type DLOBOrders = DLOBOrder[];
export type MarketNodeLists = {
restingLimit: {
ask: NodeList<'restingLimit'>;
bid: NodeList<'restingLimit'>;
};
floatingLimit: {
ask: NodeList<'floatingLimit'>;
bid: NodeList<'floatingLimit'>;
};
takingLimit: {
ask: NodeList<'takingLimit'>;
bid: NodeList<'takingLimit'>;
};
market: {
ask: NodeList<'market'>;
bid: NodeList<'market'>;
};
trigger: {
above: NodeList<'trigger'>;
below: NodeList<'trigger'>;
};
swift: {
ask: NodeList<'swift'>;
bid: NodeList<'swift'>;
};
};
type OrderBookCallback = () => void;
/**
* Receives a DLOBNode and is expected to return true if the node should
* be taken into account when generating, or false otherwise.
*
* Currently used in functions that rely on getBestNode
*/
export type DLOBFilterFcn = (node: DLOBNode) => boolean;
export type NodeToFill = {
node: DLOBNode;
makerNodes: DLOBNode[];
};
export type NodeToTrigger = {
node: TriggerOrderNode;
};
const SUPPORTED_ORDER_TYPES = [
'market',
'limit',
'triggerMarket',
'triggerLimit',
'oracle',
];
export class DLOB {
openOrders = new Map<MarketTypeStr, Set<string>>();
orderLists = new Map<MarketTypeStr, Map<number, MarketNodeLists>>();
maxSlotForRestingLimitOrders = 0;
initialized = false;
public constructor() {
this.init();
}
private init() {
this.openOrders.set('perp', new Set<string>());
this.openOrders.set('spot', new Set<string>());
this.orderLists.set('perp', new Map<number, MarketNodeLists>());
this.orderLists.set('spot', new Map<number, MarketNodeLists>());
}
public clear() {
for (const marketType of this.openOrders.keys()) {
this.openOrders.get(marketType).clear();
}
this.openOrders.clear();
for (const marketType of this.orderLists.keys()) {
for (const marketIndex of this.orderLists.get(marketType).keys()) {
const marketNodeLists = this.orderLists
.get(marketType)
.get(marketIndex);
for (const side of Object.keys(marketNodeLists)) {
for (const orderType of Object.keys(marketNodeLists[side])) {
marketNodeLists[side][orderType].clear();
}
}
}
}
this.orderLists.clear();
this.maxSlotForRestingLimitOrders = 0;
this.init();
}
/**
* initializes a new DLOB instance
*
* @returns a promise that resolves when the DLOB is initialized
*/
public async initFromUserMap(
userMap: UserMap,
slot: number
): Promise<boolean> {
if (this.initialized) {
return false;
}
// initialize the dlob with the user map
for (const user of userMap.values()) {
const userAccount = user.getUserAccount();
const userAccountPubkey = user.getUserAccountPublicKey();
const userAccountPubkeyString = userAccountPubkey.toString();
const protectedMaker = isUserProtectedMaker(userAccount);
for (const order of userAccount.orders) {
this.insertOrder(order, userAccountPubkeyString, slot, protectedMaker);
}
}
this.initialized = true;
return true;
}
public insertOrder(
order: Order,
userAccount: string,
slot: number,
isUserProtectedMaker: boolean,
onInsert?: OrderBookCallback
): void {
if (isVariant(order.status, 'init')) {
return;
}
if (!isOneOfVariant(order.orderType, SUPPORTED_ORDER_TYPES)) {
return;
}
const marketType = getVariant(order.marketType) as MarketTypeStr;
if (!this.orderLists.get(marketType).has(order.marketIndex)) {
this.addOrderList(marketType, order.marketIndex);
}
if (isVariant(order.status, 'open')) {
this.openOrders
.get(marketType)
.add(getOrderSignature(order.orderId, userAccount));
}
this.getListForOnChainOrder(order, slot)?.insert(
order,
marketType,
userAccount,
isUserProtectedMaker
);
if (onInsert) {
onInsert();
}
}
public insertSwiftOrder(
order: Order,
userAccount: string,
isUserProtectedMaker: boolean,
onInsert?: OrderBookCallback
): void {
const marketType = getVariant(order.marketType) as MarketTypeStr;
const marketIndex = order.marketIndex;
const bidOrAsk = isVariant(order.direction, 'long') ? 'bid' : 'ask';
if (!this.orderLists.get(marketType).has(order.marketIndex)) {
this.addOrderList(marketType, order.marketIndex);
}
this.openOrders
.get(marketType)
.add(getOrderSignature(order.orderId, userAccount));
this.orderLists
.get(marketType)
.get(marketIndex)
.swift[bidOrAsk].insert(
order,
marketType,
userAccount,
isUserProtectedMaker
);
if (onInsert) {
onInsert();
}
}
addOrderList(marketType: MarketTypeStr, marketIndex: number): void {
this.orderLists.get(marketType).set(marketIndex, {
restingLimit: {
ask: new NodeList('restingLimit', 'asc'),
bid: new NodeList('restingLimit', 'desc'),
},
floatingLimit: {
ask: new NodeList('floatingLimit', 'asc'),
bid: new NodeList('floatingLimit', 'desc'),
},
takingLimit: {
ask: new NodeList('takingLimit', 'asc'),
bid: new NodeList('takingLimit', 'asc'), // always sort ascending for market orders
},
market: {
ask: new NodeList('market', 'asc'),
bid: new NodeList('market', 'asc'), // always sort ascending for market orders
},
trigger: {
above: new NodeList('trigger', 'asc'),
below: new NodeList('trigger', 'desc'),
},
swift: {
ask: new NodeList('swift', 'asc'),
bid: new NodeList('swift', 'asc'),
},
});
}
public getListForOnChainOrder(
order: Order,
slot: number
): NodeList<any> | undefined {
const isInactiveTriggerOrder =
mustBeTriggered(order) && !isTriggered(order);
let type: DLOBNodeType;
if (isInactiveTriggerOrder) {
type = 'trigger';
} else if (
isOneOfVariant(order.orderType, ['market', 'triggerMarket', 'oracle'])
) {
type = 'market';
} else if (order.oraclePriceOffset !== 0) {
type = 'floatingLimit';
} else {
const isResting = isRestingLimitOrder(order, slot);
type = isResting ? 'restingLimit' : 'takingLimit';
}
let subType: string;
if (isInactiveTriggerOrder) {
subType = isVariant(order.triggerCondition, 'above') ? 'above' : 'below';
} else {
subType = isVariant(order.direction, 'long') ? 'bid' : 'ask';
}
const marketType = getVariant(order.marketType) as MarketTypeStr;
if (!this.orderLists.has(marketType)) {
return undefined;
}
return this.orderLists.get(marketType).get(order.marketIndex)[type][
subType
];
}
public updateRestingLimitOrders(slot: number): void {
if (slot <= this.maxSlotForRestingLimitOrders) {
return;
}
this.maxSlotForRestingLimitOrders = slot;
this.updateRestingLimitOrdersForMarketType(slot, 'perp');
this.updateRestingLimitOrdersForMarketType(slot, 'spot');
}
updateRestingLimitOrdersForMarketType(
slot: number,
marketTypeStr: MarketTypeStr
): void {
for (const [_, nodeLists] of this.orderLists.get(marketTypeStr)) {
const nodesToUpdate = [];
for (const node of nodeLists.takingLimit.ask.getGenerator()) {
if (!isRestingLimitOrder(node.order, slot)) {
continue;
}
nodesToUpdate.push({
side: 'ask',
node,
});
}
for (const node of nodeLists.takingLimit.bid.getGenerator()) {
if (!isRestingLimitOrder(node.order, slot)) {
continue;
}
nodesToUpdate.push({
side: 'bid',
node,
});
}
for (const nodeToUpdate of nodesToUpdate) {
const { side, node } = nodeToUpdate;
nodeLists.takingLimit[side].remove(node.order, node.userAccount);
nodeLists.restingLimit[side].insert(
node.order,
marketTypeStr,
node.userAccount
);
}
}
}
public getOrder(orderId: number, userAccount: PublicKey): Order | undefined {
const orderSignature = getOrderSignature(orderId, userAccount.toString());
for (const nodeList of this.getNodeLists()) {
const node = nodeList.get(orderSignature);
if (node) {
return node.order;
}
}
return undefined;
}
public findNodesToFill(
marketIndex: number,
fallbackBid: BN | undefined,
fallbackAsk: BN | undefined,
slot: number,
ts: number,
marketType: MarketType,
oraclePriceData: OraclePriceData,
stateAccount: StateAccount,
marketAccount: PerpMarketAccount | SpotMarketAccount
): NodeToFill[] {
if (fillPaused(stateAccount, marketAccount)) {
return [];
}
const isAmmPaused = ammPaused(stateAccount, marketAccount);
const minAuctionDuration = isVariant(marketType, 'perp')
? stateAccount.minPerpAuctionDuration
: 0;
const { makerRebateNumerator, makerRebateDenominator } =
this.getMakerRebate(marketType, stateAccount, marketAccount);
const takingOrderNodesToFill: Array<NodeToFill> =
this.findTakingNodesToFill(
marketIndex,
slot,
marketType,
oraclePriceData,
isAmmPaused,
minAuctionDuration,
fallbackAsk,
fallbackBid
);
const restingLimitOrderNodesToFill: Array<NodeToFill> =
this.findRestingLimitOrderNodesToFill(
marketIndex,
slot,
marketType,
oraclePriceData,
isAmmPaused,
minAuctionDuration,
makerRebateNumerator,
makerRebateDenominator,
fallbackAsk,
fallbackBid
);
// get expired market nodes
const expiredNodesToFill = this.findExpiredNodesToFill(
marketIndex,
ts,
marketType,
new BN(slot)
);
return this.mergeNodesToFill(
restingLimitOrderNodesToFill,
takingOrderNodesToFill
).concat(expiredNodesToFill);
}
getMakerRebate(
marketType: MarketType,
stateAccount: StateAccount,
marketAccount: PerpMarketAccount | SpotMarketAccount
): { makerRebateNumerator: number; makerRebateDenominator: number } {
let makerRebateNumerator: number;
let makerRebateDenominator: number;
if (isVariant(marketType, 'perp')) {
makerRebateNumerator =
stateAccount.perpFeeStructure.feeTiers[0].makerRebateNumerator;
makerRebateDenominator =
stateAccount.perpFeeStructure.feeTiers[0].makerRebateDenominator;
} else {
makerRebateNumerator =
stateAccount.spotFeeStructure.feeTiers[0].makerRebateNumerator;
makerRebateDenominator =
stateAccount.spotFeeStructure.feeTiers[0].makerRebateDenominator;
}
// @ts-ignore
const feeAdjustment = marketAccount.feeAdjustment || 0;
if (feeAdjustment !== 0) {
makerRebateNumerator += (makerRebateNumerator * feeAdjustment) / 100;
}
return { makerRebateNumerator, makerRebateDenominator };
}
mergeNodesToFill(
restingLimitOrderNodesToFill: NodeToFill[],
takingOrderNodesToFill: NodeToFill[]
): NodeToFill[] {
const mergedNodesToFill = new Map<string, NodeToFill>();
const mergeNodesToFillHelper = (nodesToFillArray: NodeToFill[]) => {
nodesToFillArray.forEach((nodeToFill) => {
const nodeSignature = getOrderSignature(
nodeToFill.node.order.orderId,
nodeToFill.node.userAccount
);
if (!mergedNodesToFill.has(nodeSignature)) {
mergedNodesToFill.set(nodeSignature, {
node: nodeToFill.node,
makerNodes: [],
});
}
if (nodeToFill.makerNodes) {
mergedNodesToFill
.get(nodeSignature)
.makerNodes.push(...nodeToFill.makerNodes);
}
});
};
mergeNodesToFillHelper(restingLimitOrderNodesToFill);
mergeNodesToFillHelper(takingOrderNodesToFill);
return Array.from(mergedNodesToFill.values());
}
public findRestingLimitOrderNodesToFill(
marketIndex: number,
slot: number,
marketType: MarketType,
oraclePriceData: OraclePriceData,
isAmmPaused: boolean,
minAuctionDuration: number,
makerRebateNumerator: number,
makerRebateDenominator: number,
fallbackAsk: BN | undefined,
fallbackBid: BN | undefined
): NodeToFill[] {
const nodesToFill = new Array<NodeToFill>();
const crossingNodes = this.findCrossingRestingLimitOrders(
marketIndex,
slot,
marketType,
oraclePriceData
);
for (const crossingNode of crossingNodes) {
nodesToFill.push(crossingNode);
}
if (fallbackBid && !isAmmPaused) {
const askGenerator = this.getRestingLimitAsks(
marketIndex,
slot,
marketType,
oraclePriceData
);
const fallbackBidWithBuffer = fallbackBid.sub(
fallbackBid.muln(makerRebateNumerator).divn(makerRebateDenominator)
);
const asksCrossingFallback = this.findNodesCrossingFallbackLiquidity(
marketType,
slot,
oraclePriceData,
askGenerator,
(askPrice) => {
return askPrice.lte(fallbackBidWithBuffer);
},
minAuctionDuration
);
for (const askCrossingFallback of asksCrossingFallback) {
nodesToFill.push(askCrossingFallback);
}
}
if (fallbackAsk && !isAmmPaused) {
const bidGenerator = this.getRestingLimitBids(
marketIndex,
slot,
marketType,
oraclePriceData
);
const fallbackAskWithBuffer = fallbackAsk.add(
fallbackAsk.muln(makerRebateNumerator).divn(makerRebateDenominator)
);
const bidsCrossingFallback = this.findNodesCrossingFallbackLiquidity(
marketType,
slot,
oraclePriceData,
bidGenerator,
(bidPrice) => {
return bidPrice.gte(fallbackAskWithBuffer);
},
minAuctionDuration
);
for (const bidCrossingFallback of bidsCrossingFallback) {
nodesToFill.push(bidCrossingFallback);
}
}
return nodesToFill;
}
public findTakingNodesToFill(
marketIndex: number,
slot: number,
marketType: MarketType,
oraclePriceData: OraclePriceData,
isAmmPaused: boolean,
minAuctionDuration: number,
fallbackAsk: BN | undefined,
fallbackBid?: BN | undefined
): NodeToFill[] {
const nodesToFill = new Array<NodeToFill>();
let takingOrderGenerator = this.getTakingAsks(
marketIndex,
marketType,
slot,
oraclePriceData
);
const takingAsksCrossingBids = this.findTakingNodesCrossingMakerNodes(
marketIndex,
slot,
marketType,
oraclePriceData,
takingOrderGenerator,
this.getRestingLimitBids.bind(this),
(takerPrice, makerPrice) => {
if (isVariant(marketType, 'spot')) {
if (takerPrice === undefined) {
return false;
}
if (fallbackBid && makerPrice.lt(fallbackBid)) {
return false;
}
}
return takerPrice === undefined || takerPrice.lte(makerPrice);
}
);
for (const takingAskCrossingBid of takingAsksCrossingBids) {
nodesToFill.push(takingAskCrossingBid);
}
if (fallbackBid && !isAmmPaused) {
takingOrderGenerator = this.getTakingAsks(
marketIndex,
marketType,
slot,
oraclePriceData
);
const takingAsksCrossingFallback =
this.findNodesCrossingFallbackLiquidity(
marketType,
slot,
oraclePriceData,
takingOrderGenerator,
(takerPrice) => {
return takerPrice === undefined || takerPrice.lte(fallbackBid);
},
minAuctionDuration
);
for (const takingAskCrossingFallback of takingAsksCrossingFallback) {
nodesToFill.push(takingAskCrossingFallback);
}
}
takingOrderGenerator = this.getTakingBids(
marketIndex,
marketType,
slot,
oraclePriceData
);
const takingBidsToFill = this.findTakingNodesCrossingMakerNodes(
marketIndex,
slot,
marketType,
oraclePriceData,
takingOrderGenerator,
this.getRestingLimitAsks.bind(this),
(takerPrice, makerPrice) => {
if (isVariant(marketType, 'spot')) {
if (takerPrice === undefined) {
return false;
}
if (fallbackAsk && makerPrice.gt(fallbackAsk)) {
return false;
}
}
return takerPrice === undefined || takerPrice.gte(makerPrice);
}
);
for (const takingBidToFill of takingBidsToFill) {
nodesToFill.push(takingBidToFill);
}
if (fallbackAsk && !isAmmPaused) {
takingOrderGenerator = this.getTakingBids(
marketIndex,
marketType,
slot,
oraclePriceData
);
const takingBidsCrossingFallback =
this.findNodesCrossingFallbackLiquidity(
marketType,
slot,
oraclePriceData,
takingOrderGenerator,
(takerPrice) => {
return takerPrice === undefined || takerPrice.gte(fallbackAsk);
},
minAuctionDuration
);
for (const marketBidCrossingFallback of takingBidsCrossingFallback) {
nodesToFill.push(marketBidCrossingFallback);
}
}
return nodesToFill;
}
public findTakingNodesCrossingMakerNodes(
marketIndex: number,
slot: number,
marketType: MarketType,
oraclePriceData: OraclePriceData,
takerNodeGenerator: Generator<DLOBNode>,
makerNodeGeneratorFn: (
marketIndex: number,
slot: number,
marketType: MarketType,
oraclePriceData: OraclePriceData
) => Generator<DLOBNode>,
doesCross: (takerPrice: BN | undefined, makerPrice: BN) => boolean
): NodeToFill[] {
const nodesToFill = new Array<NodeToFill>();
for (const takerNode of takerNodeGenerator) {
const makerNodeGenerator = makerNodeGeneratorFn(
marketIndex,
slot,
marketType,
oraclePriceData
);
for (const makerNode of makerNodeGenerator) {
// Can't match orders from the same user
const sameUser = takerNode.userAccount === makerNode.userAccount;
if (sameUser) {
continue;
}
const makerPrice = makerNode.getPrice(oraclePriceData, slot);
const takerPrice = takerNode.getPrice(oraclePriceData, slot);
const ordersCross = doesCross(takerPrice, makerPrice);
if (!ordersCross) {
// market orders aren't sorted by price, they are sorted by time, so we need to traverse
// through all of em
break;
}
nodesToFill.push({
node: takerNode,
makerNodes: [makerNode],
});
const makerOrder = makerNode.order;
const takerOrder = takerNode.order;
const makerBaseRemaining = makerOrder.baseAssetAmount.sub(
makerOrder.baseAssetAmountFilled
);
const takerBaseRemaining = takerOrder.baseAssetAmount.sub(
takerOrder.baseAssetAmountFilled
);
const baseFilled = BN.min(makerBaseRemaining, takerBaseRemaining);
const newMakerOrder = { ...makerOrder };
newMakerOrder.baseAssetAmountFilled =
makerOrder.baseAssetAmountFilled.add(baseFilled);
this.getListForOnChainOrder(newMakerOrder, slot).update(
newMakerOrder,
makerNode.userAccount
);
const newTakerOrder = { ...takerOrder };
newTakerOrder.baseAssetAmountFilled =
takerOrder.baseAssetAmountFilled.add(baseFilled);
this.getListForOnChainOrder(newTakerOrder, slot).update(
newTakerOrder,
takerNode.userAccount
);
if (
newTakerOrder.baseAssetAmountFilled.eq(takerOrder.baseAssetAmount)
) {
break;
}
}
}
return nodesToFill;
}
public findNodesCrossingFallbackLiquidity(
marketType: MarketType,
slot: number,
oraclePriceData: OraclePriceData,
nodeGenerator: Generator<DLOBNode>,
doesCross: (nodePrice: BN | undefined) => boolean,
minAuctionDuration: number
): NodeToFill[] {
const nodesToFill = new Array<NodeToFill>();
let nextNode = nodeGenerator.next();
while (!nextNode.done) {
const node = nextNode.value;
if (isVariant(marketType, 'spot') && node.order?.postOnly) {
nextNode = nodeGenerator.next();
continue;
}
const nodePrice = getLimitPrice(node.order, oraclePriceData, slot);
// order crosses if there is no limit price or it crosses fallback price
const crosses = doesCross(nodePrice);
// fallback is available if auction is complete or it's a spot order
const fallbackAvailable =
isVariant(marketType, 'spot') ||
isFallbackAvailableLiquiditySource(
node.order,
minAuctionDuration,
slot
);
if (crosses && fallbackAvailable) {
nodesToFill.push({
node: node,
makerNodes: [], // filled by fallback
});
}
nextNode = nodeGenerator.next();
}
return nodesToFill;
}
public findExpiredNodesToFill(
marketIndex: number,
ts: number,
marketType: MarketType,
slot?: BN
): NodeToFill[] {
const nodesToFill = new Array<NodeToFill>();
const marketTypeStr = getVariant(marketType) as MarketTypeStr;
const nodeLists = this.orderLists.get(marketTypeStr).get(marketIndex);
if (!nodeLists) {
return nodesToFill;
}
// All bids/asks that can expire
// dont try to expire limit orders with tif as its inefficient use of blockspace
const bidGenerators = [
nodeLists.takingLimit.bid.getGenerator(),
nodeLists.restingLimit.bid.getGenerator(),
nodeLists.floatingLimit.bid.getGenerator(),
nodeLists.market.bid.getGenerator(),
nodeLists.swift.bid.getGenerator(),
];
const askGenerators = [
nodeLists.takingLimit.ask.getGenerator(),
nodeLists.restingLimit.ask.getGenerator(),
nodeLists.floatingLimit.ask.getGenerator(),
nodeLists.market.ask.getGenerator(),
nodeLists.swift.ask.getGenerator(),
];
for (const bidGenerator of bidGenerators) {
for (const bid of bidGenerator) {
if (
bid.isSwift &&
slot.gt(bid.order.slot.addn(bid.order.auctionDuration))
) {
this.orderLists
.get(marketTypeStr)
.get(marketIndex)
.swift.bid.remove(bid.order, bid.userAccount);
} else if (isOrderExpired(bid.order, ts, true, 25)) {
nodesToFill.push({
node: bid,
makerNodes: [],
});
}
}
}
for (const askGenerator of askGenerators) {
for (const ask of askGenerator) {
if (isOrderExpired(ask.order, ts, true, 25)) {
nodesToFill.push({
node: ask,
makerNodes: [],
});
}
}
}
return nodesToFill;
}
*getTakingBids(
marketIndex: number,
marketType: MarketType,
slot: number,
oraclePriceData: OraclePriceData,
filterFcn?: DLOBFilterFcn
): Generator<DLOBNode> {
const marketTypeStr = getVariant(marketType) as MarketTypeStr;
const orderLists = this.orderLists.get(marketTypeStr).get(marketIndex);
if (!orderLists) {
return;
}
this.updateRestingLimitOrders(slot);
const generatorList = [
orderLists.market.bid.getGenerator(),
orderLists.takingLimit.bid.getGenerator(),
orderLists.swift.bid.getGenerator(),
];
yield* this.getBestNode(
generatorList,
oraclePriceData,
slot,
(bestNode, currentNode) => {
return bestNode.order.slot.lt(currentNode.order.slot);
},
filterFcn
);
}
*getTakingAsks(
marketIndex: number,
marketType: MarketType,
slot: number,
oraclePriceData: OraclePriceData,
filterFcn?: DLOBFilterFcn
): Generator<DLOBNode> {
const marketTypeStr = getVariant(marketType) as MarketTypeStr;
const orderLists = this.orderLists.get(marketTypeStr).get(marketIndex);
if (!orderLists) {
return;
}
this.updateRestingLimitOrders(slot);
const generatorList = [
orderLists.market.ask.getGenerator(),
orderLists.takingLimit.ask.getGenerator(),
orderLists.swift.ask.getGenerator(),
];
yield* this.getBestNode(
generatorList,
oraclePriceData,
slot,
(bestNode, currentNode) => {
return bestNode.order.slot.lt(currentNode.order.slot);
},
filterFcn
);
}
protected *getBestNode(
generatorList: Array<Generator<DLOBNode>>,
oraclePriceData: OraclePriceData,
slot: number,
compareFcn: (
bestDLOBNode: DLOBNode,
currentDLOBNode: DLOBNode,
slot: number,
oraclePriceData: OraclePriceData
) => boolean,
filterFcn?: DLOBFilterFcn
): Generator<DLOBNode> {
const generators = generatorList.map((generator) => {
return {
next: generator.next(),
generator,
};
});
let sideExhausted = false;
while (!sideExhausted) {
const bestGenerator = generators.reduce(
(bestGenerator, currentGenerator) => {
if (currentGenerator.next.done) {
return bestGenerator;
}
if (bestGenerator.next.done) {
return currentGenerator;
}
const bestValue = bestGenerator.next.value as DLOBNode;
const currentValue = currentGenerator.next.value as DLOBNode;
return compareFcn(bestValue, currentValue, slot, oraclePriceData)
? bestGenerator
: currentGenerator;
}
);
if (!bestGenerator.next.done) {
// skip this node if it's already completely filled
if (bestGenerator.next.value.isBaseFilled()) {
bestGenerator.next = bestGenerator.generator.next();
continue;
}
if (filterFcn && !filterFcn(bestGenerator.next.value)) {
bestGenerator.next = bestGenerator.generator.next();
continue;
}
yield bestGenerator.next.value;
bestGenerator.next = bestGenerator.generator.next();
} else {
sideExhausted = true;
}
}
}
*getRestingLimitAsks(
marketIndex: number,
slot: number,
marketType: MarketType,
oraclePriceData: OraclePriceData,
filterFcn?: DLOBFilterFcn
): Generator<DLOBNode> {
if (isVariant(marketType, 'spot') && !oraclePriceData) {
throw new Error('Must provide OraclePriceData to get spot asks');
}
this.updateRestingLimitOrders(slot);
const marketTypeStr = getVariant(marketType) as MarketTypeStr;
const nodeLists = this.orderLists.get(marketTypeStr).get(marketIndex);
if (!nodeLists) {
return;
}
const generatorList = [
nodeLists.restingLimit.ask.getGenerator(),
nodeLists.floatingLimit.ask.getGenerator(),
];
yield* this.getBestNode(
generatorList,
oraclePriceData,
slot,
(bestNode, currentNode, slot, oraclePriceData) => {
return bestNode
.getPrice(oraclePriceData, slot)
.lt(currentNode.getPrice(oraclePriceData, slot));
},
filterFcn
);
}
*getRestingLimitBids(
marketIndex: number,
slot: number,
marketType: MarketType,
oraclePriceData: OraclePriceData,
filterFcn?: DLOBFilterFcn
): Generator<DLOBNode> {
if (isVariant(marketType, 'spot') && !oraclePriceData) {
throw new Error('Must provide OraclePriceData to get spot bids');
}
this.updateRestingLimitOrders(slot);
const marketTypeStr = getVariant(marketType) as MarketTypeStr;
const nodeLists = this.orderLists.get(marketTypeStr).get(marketIndex);
if (!nodeLists) {
return;
}
const generatorList = [
nodeLists.restingLimit.bid.getGenerator(),
nodeLists.floatingLimit.bid.getGenerator(),
];
yield* this.getBestNode(
generatorList,
oraclePriceData,
slot,
(bestNode, currentNode, slot, oraclePriceData) => {
return bestNode
.getPrice(oraclePriceData, slot)
.gt(currentNode.getPrice(oraclePriceData, slot));
},
filterFcn
);
}
/**
* This will look at both the taking and resting limit asks
* @param marketIndex
* @param fallbackAsk
* @param slot
* @param marketType
* @param oraclePriceData
* @param filterFcn
*/
*getAsks(
marketIndex: number,
_fallbackAsk: BN | undefined,
slot: number,
marketType: MarketType,
oraclePriceData: OraclePriceData,
filterFcn?: DLOBFilterFcn
): Generator<DLOBNode> {
if (isVariant(marketType, 'spot') && !oraclePriceData) {
throw new Error('Must provide OraclePriceData to get spot asks');
}
const generatorList = [
this.getTakingAsks(marketIndex, marketType, slot, oraclePriceData),
this.getRestingLimitAsks(marketIndex, slot, marketType, oraclePriceData),
];
yield* this.getBestNode(
generatorList,
oraclePriceData,
slot,
(bestNode, currentNode, slot, oraclePriceData) => {
const bestNodePrice = bestNode.getPrice(oraclePriceData, slot) ?? ZERO;
const currentNodePrice =
currentNode.getPrice(oraclePriceData, slot) ?? ZERO;
if (bestNodePrice.eq(currentNodePrice)) {
return bestNode.order.slot.lt(currentNode.order.slot);
}
return bestNodePrice.lt(currentNodePrice);
},
filterFcn
);
}
/**
* This will look at both the taking and resting limit bids
* @param marketIndex
* @param fallbackBid
* @param slot
* @param marketType
* @param oraclePriceData
* @param filterFcn
*/
*getBids(
marketIndex: number,
_fallbackBid: BN | undefined,
slot: number,
marketType: MarketType,
oraclePriceData: OraclePriceData,
filterFcn?: DLOBFilterFcn
): Generator<DLOBNode> {
if (isVariant(marketType, 'spot') && !oraclePriceData) {
throw new Error('Must provide OraclePriceData to get spot bids');
}
const generatorList = [
this.getTakingBids(marketIndex, marketType, slot, oraclePriceData),
this.getRestingLimitBids(marketIndex, slot, marketType, oraclePriceData),
];
yield* this.getBestNode(
generatorList,
oraclePriceData,
slot,
(bestNode, currentNode, slot, oraclePriceData) => {
const bestNodePrice =
bestNode.getPrice(oraclePriceData, slot) ?? BN_MAX;
const currentNodePrice =
currentNode.getPrice(oraclePriceData, slot) ?? BN_MAX;
if (bestNodePrice.eq(currentNodePrice)) {
return bestNode.order.slot.lt(currentNode.order.slot);
}
return bestNodePrice.gt(currentNodePrice);
},
filterFcn
);
}
findCrossingRestingLimitOrders(
marketIndex: number,
slot: number,
marketType: MarketType,
oraclePriceData: OraclePriceData
): NodeToFill[] {
const nodesToFill = new Array<NodeToFill>();
for (const askNode of this.getRestingLimitAsks(
marketIndex,
slot,
marketType,
oraclePriceData
)) {
const bidGenerator = this.getRestingLimitBids(
marketIndex,
slot,
marketType,
oraclePriceData
);
for (const bidNode of bidGenerator) {
const bidPrice = bidNode.getPrice(oraclePriceData, slot);
const askPrice = askNode.getPrice(oraclePriceData, slot);
// orders don't cross
if (bidPrice.lt(askPrice)) {
break;
}
const bidOrder = bidNode.order;
const askOrder = askNode.order;
// Can't match orders from the same user
const sameUser = bidNode.userAccount === askNode.userAccount;
if (sameUser) {
continue;
}
const makerAndTaker = this.determineMakerAndTaker(askNode, bidNode);
// unable to match maker and taker due to post only or slot
if (!makerAndTaker) {
continue;
}
const { takerNode, makerNode } = makerAndTaker;
const bidBaseRemaining = bidOrder.baseAssetAmount.sub(
bidOrder.baseAssetAmountFilled
);
const askBaseRemaining = askOrder.baseAssetAmount.sub(
askOrder.baseAssetAmountFilled
);
const baseFilled = BN.min(bidBaseRemaining, askBaseRemaining);
const newBidOrder = { ...bidOrder };
newBidOrder.baseAssetAmountFilled =
bidOrder.baseAssetAmountFilled.add(baseFilled);
this.getListForOnChainOrder(newBidOrder, slot).update(
newBidOrder,
bidNode.userAccount
);
// ask completely filled
const newAskOrder = { ...askOrder };
newAskOrder.baseAssetAmountFilled =
askOrder.baseAssetAmountFilled.add(baseFilled);
this.getListForOnChainOrder(newAskOrder, slot).update(
newAskOrder,
askNode.userAccount
);
nodesToFill.push({
node: takerNode,
makerNodes: [makerNode],
});
if (newAskOrder.baseAssetAmount.eq(newAskOrder.baseAssetAmountFilled)) {
break;
}
}
}
return nodesToFill;
}
determineMakerAndTaker(
askNode: DLOBNode,
bidNode: DLOBNode
): { takerNode: DLOBNode; makerNode: DLOBNode } | undefined {
const askSlot = askNode.order.slot.add(
new BN(askNode.order.auctionDuration)
);
const bidSlot = bidNode.order.slot.add(
new BN(bidNode.order.auctionDuration)
);
if (bidNode.order.postOnly && askNode.order.postOnly) {
return undefined;
} else if (bidNode.order.postOnly) {
return {
takerNode: askNode,
makerNode: bidNode,
};
} else if (askNode.order.postOnly) {
return {
takerNode: bidNode,
makerNode: askNode,
};
} else if (askSlot.lte(bidSlot)) {
return {
takerNode: bidNode,
makerNode: askNode,
};
} else {
return {
takerNode: askNode,
makerNode: bidNode,
};
}
}
public getBestAsk(
marketIndex: number,
slot: number,
marketType: MarketType,
oraclePriceData: OraclePriceData
): BN | undefined {
const bestAsk = this.getRestingLimitAsks(
marketIndex,
slot,
marketType,
oraclePriceData
).next().value;
if (bestAsk) {
return bestAsk.getPrice(oraclePriceData, slot);
}
return undefined;
}
public getBestBid(
marketIndex: number,
slot: number,
marketType: MarketType,
oraclePriceData: OraclePriceData
): BN | undefined {
const bestBid = this.getRestingLimitBids(
marketIndex,
slot,
marketType,
oraclePriceData
).next().value;
if (bestBid) {
return bestBid.getPrice(oraclePriceData, slot);
}
return undefined;
}
public *getStopLosses(
marketIndex: number,
marketType: MarketType,
direction: PositionDirection
): Generator<DLOBNode> {
const marketTypeStr = getVariant(marketType) as MarketTypeStr;
const marketNodeLists = this.orderLists.get(marketTypeStr).get(marketIndex);
if (isVariant(direction, 'long') && marketNodeLists.trigger.below) {
for (const node of marketNodeLists.trigger.below.getGenerator()) {
if (isVariant(node.order.direction, 'short')) {
yield node;
}
}
} else if (isVariant(direction, 'short') && marketNodeLists.trigger.above) {
for (const node of marketNodeLists.trigger.above.getGenerator()) {
if (isVariant(node.order.direction, 'long')) {
yield node;
}
}
}
}
public *getStopLossMarkets(
marketIndex: number,
marketType: MarketType,
direction: PositionDirection
): Generator<DLOBNode> {
for (const node of this.getStopLosses(marketIndex, marketType, direction)) {
if (isVariant(node.order.orderType, 'triggerMarket')) {
yield node;
}
}
}
public *getStopLossLimits(
marketIndex: number,
marketType: MarketType,
direction: PositionDirection
): Generator<DLOBNode> {
for (const node of this.getStopLosses(marketIndex, marketType, direction)) {
if (isVariant(node.order.orderType, 'triggerLimit')) {
yield node;
}
}
}
public *getTakeProfits(
marketIndex: number,
marketType: MarketType,
direction: PositionDirection
): Generator<DLOBNode> {
const marketTypeStr = getVariant(marketType) as MarketTypeStr;
const marketNodeLists = this.orderLists.get(marketTypeStr).get(marketIndex);
if (isVariant(direction, 'long') && marketNodeLists.trigger.above) {
for (const node of marketNodeLists.trigger.above.getGenerator()) {
if (isVariant(node.order.direction, 'short')) {
yield node;
}
}
} else if (isVariant(direction, 'short') && marketNodeLists.trigger.below) {
for (const node of marketNodeLists.trigger.below.getGenerator()) {
if (isVariant(node.order.direction, 'long')) {
yield node;
}
}
}
}
public *getTakeProfitMarkets(
marketIndex: number,
marketType: MarketType,
direction: PositionDirection
): Generator<DLOBNode> {
for (const node of this.getTakeProfits(
marketIndex,
marketType,
direction
)) {
if (isVariant(node.order.orderType, 'triggerMarket')) {
yield node;
}
}
}
public *getTakeProfitLimits(
marketIndex: number,
marketType: MarketType,
direction: PositionDirection
): Generator<DLOBNode> {
for (const node of this.getTakeProfits(
marketIndex,
marketType,
direction
)) {
if (isVariant(node.order.orderType, 'triggerLimit')) {
yield node;
}
}
}
public findNodesToTrigger(
marketIndex: number,
slot: number,
oraclePrice: BN,
marketType: MarketType,
stateAccount: StateAccount
): NodeToTrigger[] {
if (exchangePaused(stateAccount)) {
return [];
}
const nodesToTrigger = [];
const marketTypeStr = getVariant(marketType) as MarketTypeStr;
const marketNodeLists = this.orderLists.get(marketTypeStr).get(marketIndex);
const triggerAboveList = marketNodeLists
? marketNodeLists.trigger.above
: undefined;
if (triggerAboveList) {
for (const node of triggerAboveList.getGenerator()) {
if (oraclePrice.gt(node.order.triggerPrice)) {
nodesToTrigger.push({
node: node,
});
} else {
break;
}
}
}
const triggerBelowList = marketNodeLists
? marketNodeLists.trigger.below
: undefined;
if (triggerBelowList) {
for (const node of triggerBelowList.getGenerator()) {
if (oraclePrice.lt(node.order.triggerPrice)) {
nodesToTrigger.push({
node: node,
});
} else {
break;
}
}
}
return nodesToTrigger;
}
public printTop(
driftClient: DriftClient,
slotSubscriber: SlotSubscriber,
marketIndex: number,
marketType: MarketType
) {
if (isVariant(marketType, 'perp')) {
const slot = slotSubscriber.getSlot();
const oraclePriceData =
driftClient.getOracleDataForPerpMarket(marketIndex);
const bestAsk = this.getBestAsk(
marketIndex,
slot,
marketType,
oraclePriceData
);
const bestBid = this.getBestBid(
marketIndex,
slot,
marketType,
oraclePriceData
);
const mid = bestAsk.add(bestBid).div(new BN(2));
const bidSpread =
(convertToNumber(bestBid, PRICE_PRECISION) /
convertToNumber(oraclePriceData.price, PRICE_PRECISION) -
1) *
100.0;
const askSpread =
(convertToNumber(bestAsk, PRICE_PRECISION) /
convertToNumber(oraclePriceData.price, PRICE_PRECISION) -
1) *
100.0;
const name = decodeName(
driftClient.getPerpMarketAccount(marketIndex).name
);
console.log(`Market ${name} Orders`);
console.log(
` Ask`,
convertToNumber(bestAsk, PRICE_PRECISION).toFixed(3),
`(${askSpread.toFixed(4)}%)`
);
console.log(` Mid`, convertToNumber(mid, PRICE_PRECISION).toFixed(3));
console.log(
` Bid`,
convertToNumber(bestBid, PRICE_PRECISION).toFixed(3),
`(${bidSpread.toFixed(4)}%)`
);
} else if (isVariant(marketType, 'spot')) {
const slot = slotSubscriber.getSlot();
const oraclePriceData =
driftClient.getOracleDataForPerpMarket(marketIndex);
const bestAsk = this.getBestAsk(
marketIndex,
slot,
marketType,
oraclePriceData
);
const bestBid = this.getBestBid(
marketIndex,
slot,
marketType,
oraclePriceData
);
const mid = bestAsk.add(bestBid).div(new BN(2));
const bidSpread =
(convertToNumber(bestBid, PRICE_PRECISION) /
convertToNumber(oraclePriceData.price, PRICE_PRECISION) -
1) *
100.0;
const askSpread =
(convertToNumber(bestAsk, PRICE_PRECISION) /
convertToNumber(oraclePriceData.price, PRICE_PRECISION) -
1) *
100.0;
const name = decodeName(
driftClient.getSpotMarketAccount(marketIndex).name
);
console.log(`Market ${name} Orders`);
console.log(
` Ask`,
convertToNumber(bestAsk, PRICE_PRECISION).toFixed(3),
`(${askSpread.toFixed(4)}%)`
);
console.log(` Mid`, convertToNumber(mid, PRICE_PRECISION).toFixed(3));
console.log(
` Bid`,
convertToNumber(bestBid, PRICE_PRECISION).toFixed(3),
`(${bidSpread.toFixed(4)}%)`
);
}
}
public getDLOBOrders(): DLOBOrders {
const dlobOrders: DLOBOrders = [];
for (const nodeList of this.getNodeLists()) {
for (const node of nodeList.getGenerator()) {
dlobOrders.push({
user: new PublicKey(node.userAccount),
order: node.order,
});
}
}
return dlobOrders;
}
*getNodeLists(): Generator<NodeList<DLOBNodeType>> {
for (const [_, nodeLists] of this.orderLists.get('perp')) {
yield nodeLists.restingLimit.bid;
yield nodeLists.restingLimit.ask;
yield nodeLists.takingLimit.bid;
yield nodeLists.takingLimit.ask;
yield nodeLists.market.bid;
yield nodeLists.market.ask;
yield nodeLists.floatingLimit.bid;
yield nodeLists.floatingLimit.ask;
yield nodeLists.trigger.above;
yield nodeLists.trigger.below;
}
for (const [_, nodeLists] of this.orderLists.get('spot')) {
yield nodeLists.restingLimit.bid;
yield nodeLists.restingLimit.ask;
yield nodeLists.takingLimit.bid;
yield nodeLists.takingLimit.ask;
yield nodeLists.market.bid;
yield nodeLists.market.ask;
yield nodeLists.floatingLimit.bid;
yield nodeLists.floatingLimit.ask;
yield nodeLists.trigger.above;
yield nodeLists.trigger.below;
}
}
/**
* Get an L2 view of the order book for a given market.
*
* @param marketIndex
* @param marketType
* @param slot
* @param oraclePriceData
* @param depth how many levels of the order book to return
* @param fallbackL2Generators L2 generators for fallback liquidity e.g. vAMM {@link getVammL2Generator}, openbook {@link SerumSubscriber}
*/
public getL2({
marketIndex,
marketType,
slot,
oraclePriceData,
depth,
fallbackL2Generators = [],
}: {
marketIndex: number;
marketType: MarketType;
slot: number;
oraclePriceData: OraclePriceData;
depth: number;
fallbackL2Generators?: L2OrderBookGenerator[];
}): L2OrderBook {
const makerAskL2LevelGenerator = getL2GeneratorFromDLOBNodes(
this.getRestingLimitAsks(marketIndex, slot, marketType, oraclePriceData),
oraclePriceData,
slot
);
const fallbackAskGenerators = fallbackL2Generators.map(
(fallbackL2Generator) => {
return fallbackL2Generator.getL2Asks();
}
);
const askL2LevelGenerator = mergeL2LevelGenerators(
[makerAskL2LevelGenerator, ...fallbackAskGenerators],
(a, b) => {
return a.price.lt(b.price);
}
);
const asks = createL2Levels(askL2LevelGenerator, depth);
const makerBidGenerator = getL2GeneratorFromDLOBNodes(
this.getRestingLimitBids(marketIndex, slot, marketType, oraclePriceData),
oraclePriceData,
slot
);
const fallbackBidGenerators = fallbackL2Generators.map((fallbackOrders) => {
return fallbackOrders.getL2Bids();
});
const bidL2LevelGenerator = mergeL2LevelGenerators(
[makerBidGenerator, ...fallbackBidGenerators],
(a, b) => {
return a.price.gt(b.price);
}
);
const bids = createL2Levels(bidL2LevelGenerator, depth);
return {
bids,
asks,
slot,
};
}
/**
* Get an L3 view of the order book for a given market. Does not include fallback liquidity sources
*
* @param marketIndex
* @param marketType
* @param slot
* @param oraclePriceData
*/
public getL3({
marketIndex,
marketType,
slot,
oraclePriceData,
}: {
marketIndex: number;
marketType: MarketType;
slot: number;
oraclePriceData: OraclePriceData;
}): L3OrderBook {
const bids: L3Level[] = [];
const asks: L3Level[] = [];
const restingAsks = this.getRestingLimitAsks(
marketIndex,
slot,
marketType,
oraclePriceData
);
for (const ask of restingAsks) {
asks.push({
price: ask.getPrice(oraclePriceData, slot),
size: ask.order.baseAssetAmount.sub(ask.order.baseAssetAmountFilled),
maker: new PublicKey(ask.userAccount),
orderId: ask.order.orderId,
});
}
const restingBids = this.getRestingLimitBids(
marketIndex,
slot,
marketType,
oraclePriceData
);
for (const bid of restingBids) {
bids.push({
price: bid.getPrice(oraclePriceData, slot),
size: bid.order.baseAssetAmount.sub(bid.order.baseAssetAmountFilled),
maker: new PublicKey(bid.userAccount),
orderId: bid.order.orderId,
});
}
return {
bids,
asks,
slot,
};
}
private estimateFillExactBaseAmountInForSide(
baseAmountIn: BN,
oraclePriceData: OraclePriceData,
slot: number,
dlobSide: Generator<DLOBNode>
): BN {
let runningSumQuote = ZERO;
let runningSumBase = ZERO;
for (const side of dlobSide) {
const price = side.getPrice(oraclePriceData, slot); //side.order.quoteAssetAmount.div(side.order.baseAssetAmount);
const baseAmountRemaining = side.order.baseAssetAmount.sub(
side.order.baseAssetAmountFilled
);
if (runningSumBase.add(baseAmountRemaining).gt(baseAmountIn)) {
const remainingBase = baseAmountIn.sub(runningSumBase);
runningSumBase = runningSumBase.add(remainingBase);
runningSumQuote = runningSumQuote.add(remainingBase.mul(price));
break;
} else {
runningSumBase = runningSumBase.add(baseAmountRemaining);
runningSumQuote = runningSumQuote.add(baseAmountRemaining.mul(price));
}
}
return runningSumQuote
.mul(QUOTE_PRECISION)
.div(BASE_PRECISION.mul(PRICE_PRECISION));
}
/**
*
* @param param.marketIndex the index of the market
* @param param.marketType the type of the market
* @param param.baseAmount the base amount in to estimate
* @param param.orderDirection the direction of the trade
* @param param.slot current slot for estimating dlob node price
* @param param.oraclePriceData the oracle price data
* @returns the estimated quote amount filled: QUOTE_PRECISION
*/
public estimateFillWithExactBaseAmount({
marketIndex,
marketType,
baseAmount,
orderDirection,
slot,
oraclePriceData,
}: {
marketIndex: number;
marketType: MarketType;
baseAmount: BN;
orderDirection: PositionDirection;
slot: number;
oraclePriceData: OraclePriceData;
}): BN {
if (isVariant(orderDirection, 'long')) {
return this.estimateFillExactBaseAmountInForSide(
baseAmount,
oraclePriceData,
slot,
this.getRestingLimitAsks(marketIndex, slot, marketType, oraclePriceData)
);
} else if (isVariant(orderDirection, 'short')) {
return this.estimateFillExactBaseAmountInForSide(
baseAmount,
oraclePriceData,
slot,
this.getRestingLimitBids(marketIndex, slot, marketType, oraclePriceData)
);
}
}
public getBestMakers({
marketIndex,
marketType,
direction,
slot,
oraclePriceData,
numMakers,
}: {
marketIndex: number;
marketType: MarketType;
direction: PositionDirection;
slot: number;
oraclePriceData: OraclePriceData;
numMakers: number;
}): PublicKey[] {
const makers = new Map<string, PublicKey>();
const generator = isVariant(direction, 'long')
? this.getRestingLimitBids(marketIndex, slot, marketType, oraclePriceData)
: this.getRestingLimitAsks(
marketIndex,
slot,
marketType,
oraclePriceData
);
for (const node of generator) {
if (!makers.has(node.userAccount.toString())) {
makers.set(
node.userAccount.toString(),
new PublicKey(node.userAccount)
);
}
if (makers.size === numMakers) {
break;
}
}
return Array.from(makers.values());
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/dlob/NodeList.ts
|
import { isVariant, MarketTypeStr, Order } from '..';
import { createNode, DLOBNode, DLOBNodeMap } from './DLOBNode';
export type SortDirection = 'asc' | 'desc';
export function getOrderSignature(
orderId: number,
userAccount: string
): string {
return `${userAccount.toString()}-${orderId.toString()}`;
}
export interface DLOBNodeGenerator {
getGenerator(): Generator<DLOBNode>;
}
export class NodeList<NodeType extends keyof DLOBNodeMap>
implements DLOBNodeGenerator
{
head?: DLOBNodeMap[NodeType];
length = 0;
nodeMap = new Map<string, DLOBNodeMap[NodeType]>();
constructor(
private nodeType: NodeType,
private sortDirection: SortDirection
) {}
public clear() {
this.head = undefined;
this.length = 0;
this.nodeMap.clear();
}
public insert(
order: Order,
marketType: MarketTypeStr,
userAccount: string,
isUserProtectedMaker: boolean
): void {
if (isVariant(order.status, 'init')) {
return;
}
const newNode = createNode(
this.nodeType,
order,
userAccount,
isUserProtectedMaker
);
const orderSignature = getOrderSignature(order.orderId, userAccount);
if (this.nodeMap.has(orderSignature)) {
return;
}
this.nodeMap.set(orderSignature, newNode);
this.length += 1;
if (this.head === undefined) {
this.head = newNode;
return;
}
if (this.prependNode(this.head, newNode)) {
this.head.previous = newNode;
newNode.next = this.head;
this.head = newNode;
return;
}
let currentNode = this.head;
while (
currentNode.next !== undefined &&
!this.prependNode(currentNode.next, newNode)
) {
currentNode = currentNode.next;
}
newNode.next = currentNode.next;
if (currentNode.next !== undefined) {
newNode.next.previous = newNode;
}
currentNode.next = newNode;
newNode.previous = currentNode;
}
prependNode(
currentNode: DLOBNodeMap[NodeType],
newNode: DLOBNodeMap[NodeType]
): boolean {
const currentOrder = currentNode.order;
const newOrder = newNode.order;
const currentOrderSortPrice = currentNode.sortValue;
const newOrderSortPrice = newNode.sortValue;
if (newOrderSortPrice.eq(currentOrderSortPrice)) {
return newOrder.slot.lt(currentOrder.slot);
}
if (this.sortDirection === 'asc') {
return newOrderSortPrice.lt(currentOrderSortPrice);
} else {
return newOrderSortPrice.gt(currentOrderSortPrice);
}
}
public update(order: Order, userAccount: string): void {
const orderId = getOrderSignature(order.orderId, userAccount);
if (this.nodeMap.has(orderId)) {
const node = this.nodeMap.get(orderId);
Object.assign(node.order, order);
node.haveFilled = false;
}
}
public remove(order: Order, userAccount: string): void {
const orderId = getOrderSignature(order.orderId, userAccount);
if (this.nodeMap.has(orderId)) {
const node = this.nodeMap.get(orderId);
if (node.next) {
node.next.previous = node.previous;
}
if (node.previous) {
node.previous.next = node.next;
}
if (this.head && node.order.orderId === this.head.order.orderId) {
this.head = node.next;
}
node.previous = undefined;
node.next = undefined;
this.nodeMap.delete(orderId);
this.length--;
}
}
*getGenerator(): Generator<DLOBNode> {
let node = this.head;
while (node !== undefined) {
yield node;
node = node.next;
}
}
public has(order: Order, userAccount: string): boolean {
return this.nodeMap.has(getOrderSignature(order.orderId, userAccount));
}
public get(orderSignature: string): DLOBNodeMap[NodeType] | undefined {
return this.nodeMap.get(orderSignature);
}
public print(): void {
let currentNode = this.head;
while (currentNode !== undefined) {
console.log(currentNode.getLabel());
currentNode = currentNode.next;
}
}
public printTop(): void {
if (this.head) {
console.log(this.sortDirection.toUpperCase(), this.head.getLabel());
} else {
console.log('---');
}
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/dlob/orderBookLevels.ts
|
import {
BASE_PRECISION,
BN,
calculateAmmReservesAfterSwap,
calculateMarketOpenBidAsk,
calculateQuoteAssetAmountSwapped,
calculateSpreadReserves,
calculateUpdatedAMM,
DLOBNode,
isOperationPaused,
isVariant,
OraclePriceData,
PerpMarketAccount,
PerpOperation,
PositionDirection,
QUOTE_PRECISION,
standardizePrice,
SwapDirection,
ZERO,
} from '..';
import { PublicKey } from '@solana/web3.js';
import { assert } from '../assert/assert';
type liquiditySource = 'serum' | 'vamm' | 'dlob' | 'phoenix' | 'openbook';
export type L2Level = {
price: BN;
size: BN;
sources: { [key in liquiditySource]?: BN };
};
export type L2OrderBook = {
asks: L2Level[];
bids: L2Level[];
slot?: number;
};
export interface L2OrderBookGenerator {
getL2Asks(): Generator<L2Level>;
getL2Bids(): Generator<L2Level>;
}
export type L3Level = {
price: BN;
size: BN;
maker: PublicKey;
orderId: number;
};
export type L3OrderBook = {
asks: L3Level[];
bids: L3Level[];
slot?: number;
};
export const DEFAULT_TOP_OF_BOOK_QUOTE_AMOUNTS = [
new BN(500).mul(QUOTE_PRECISION),
new BN(1000).mul(QUOTE_PRECISION),
new BN(2000).mul(QUOTE_PRECISION),
new BN(5000).mul(QUOTE_PRECISION),
];
/**
* Get an {@link Generator<L2Level>} generator from a {@link Generator<DLOBNode>}
* @param dlobNodes e.g. {@link DLOB#getRestingLimitAsks} or {@link DLOB#getRestingLimitBids}
* @param oraclePriceData
* @param slot
*/
export function* getL2GeneratorFromDLOBNodes(
dlobNodes: Generator<DLOBNode>,
oraclePriceData: OraclePriceData,
slot: number
): Generator<L2Level> {
for (const dlobNode of dlobNodes) {
const size = dlobNode.order.baseAssetAmount.sub(
dlobNode.order.baseAssetAmountFilled
) as BN;
yield {
size,
price: dlobNode.getPrice(oraclePriceData, slot),
sources: {
dlob: size,
},
};
}
}
export function* mergeL2LevelGenerators(
l2LevelGenerators: Generator<L2Level>[],
compare: (a: L2Level, b: L2Level) => boolean
): Generator<L2Level> {
const generators = l2LevelGenerators.map((generator) => {
return {
generator,
next: generator.next(),
};
});
let next;
do {
next = generators.reduce((best, next) => {
if (next.next.done) {
return best;
}
if (!best) {
return next;
}
if (compare(next.next.value, best.next.value)) {
return next;
} else {
return best;
}
}, undefined);
if (next) {
yield next.next.value;
next.next = next.generator.next();
}
} while (next !== undefined);
}
export function createL2Levels(
generator: Generator<L2Level>,
depth: number
): L2Level[] {
const levels = [];
for (const level of generator) {
const price = level.price;
const size = level.size;
if (levels.length > 0 && levels[levels.length - 1].price.eq(price)) {
const currentLevel = levels[levels.length - 1];
currentLevel.size = currentLevel.size.add(size);
for (const [source, size] of Object.entries(level.sources)) {
if (currentLevel.sources[source]) {
currentLevel.sources[source] = currentLevel.sources[source].add(size);
} else {
currentLevel.sources[source] = size;
}
}
} else if (levels.length === depth) {
break;
} else {
levels.push(level);
}
}
return levels;
}
export function getVammL2Generator({
marketAccount,
oraclePriceData,
numOrders,
now,
topOfBookQuoteAmounts,
}: {
marketAccount: PerpMarketAccount;
oraclePriceData: OraclePriceData;
numOrders: number;
now?: BN;
topOfBookQuoteAmounts?: BN[];
}): L2OrderBookGenerator {
let numBaseOrders = numOrders;
if (topOfBookQuoteAmounts) {
numBaseOrders = numOrders - topOfBookQuoteAmounts.length;
assert(topOfBookQuoteAmounts.length < numOrders);
}
const updatedAmm = calculateUpdatedAMM(marketAccount.amm, oraclePriceData);
const vammFillsDisabled = isOperationPaused(
marketAccount.pausedOperations,
PerpOperation.AMM_FILL
);
let [openBids, openAsks] = vammFillsDisabled
? [ZERO, ZERO]
: calculateMarketOpenBidAsk(
updatedAmm.baseAssetReserve,
updatedAmm.minBaseAssetReserve,
updatedAmm.maxBaseAssetReserve,
updatedAmm.orderStepSize
);
const minOrderSize = marketAccount.amm.minOrderSize;
if (openBids.lt(minOrderSize.muln(2))) {
openBids = ZERO;
}
if (openAsks.abs().lt(minOrderSize.muln(2))) {
openAsks = ZERO;
}
now = now ?? new BN(Date.now() / 1000);
const [bidReserves, askReserves] = calculateSpreadReserves(
updatedAmm,
oraclePriceData,
now,
isVariant(marketAccount.contractType, 'prediction')
);
let numBids = 0;
let topOfBookBidSize = ZERO;
let bidSize = openBids.div(new BN(numBaseOrders));
const bidAmm = {
baseAssetReserve: bidReserves.baseAssetReserve,
quoteAssetReserve: bidReserves.quoteAssetReserve,
sqrtK: updatedAmm.sqrtK,
pegMultiplier: updatedAmm.pegMultiplier,
};
const getL2Bids = function* () {
while (numBids < numOrders && bidSize.gt(ZERO)) {
let quoteSwapped = ZERO;
let baseSwapped = ZERO;
let [afterSwapQuoteReserves, afterSwapBaseReserves] = [ZERO, ZERO];
if (topOfBookQuoteAmounts && numBids < topOfBookQuoteAmounts?.length) {
const remainingBaseLiquidity = openBids.sub(topOfBookBidSize);
quoteSwapped = topOfBookQuoteAmounts[numBids];
[afterSwapQuoteReserves, afterSwapBaseReserves] =
calculateAmmReservesAfterSwap(
bidAmm,
'quote',
quoteSwapped,
SwapDirection.REMOVE
);
baseSwapped = bidAmm.baseAssetReserve.sub(afterSwapBaseReserves).abs();
if (baseSwapped.eq(ZERO)) {
return;
}
if (remainingBaseLiquidity.lt(baseSwapped)) {
baseSwapped = remainingBaseLiquidity;
[afterSwapQuoteReserves, afterSwapBaseReserves] =
calculateAmmReservesAfterSwap(
bidAmm,
'base',
baseSwapped,
SwapDirection.ADD
);
quoteSwapped = calculateQuoteAssetAmountSwapped(
bidAmm.quoteAssetReserve.sub(afterSwapQuoteReserves).abs(),
bidAmm.pegMultiplier,
SwapDirection.ADD
);
}
topOfBookBidSize = topOfBookBidSize.add(baseSwapped);
bidSize = openBids.sub(topOfBookBidSize).div(new BN(numBaseOrders));
} else {
baseSwapped = bidSize;
[afterSwapQuoteReserves, afterSwapBaseReserves] =
calculateAmmReservesAfterSwap(
bidAmm,
'base',
baseSwapped,
SwapDirection.ADD
);
quoteSwapped = calculateQuoteAssetAmountSwapped(
bidAmm.quoteAssetReserve.sub(afterSwapQuoteReserves).abs(),
bidAmm.pegMultiplier,
SwapDirection.ADD
);
}
const price = quoteSwapped.mul(BASE_PRECISION).div(baseSwapped);
bidAmm.baseAssetReserve = afterSwapBaseReserves;
bidAmm.quoteAssetReserve = afterSwapQuoteReserves;
yield {
price,
size: baseSwapped,
sources: { vamm: baseSwapped },
};
numBids++;
}
};
let numAsks = 0;
let topOfBookAskSize = ZERO;
let askSize = openAsks.abs().div(new BN(numBaseOrders));
const askAmm = {
baseAssetReserve: askReserves.baseAssetReserve,
quoteAssetReserve: askReserves.quoteAssetReserve,
sqrtK: updatedAmm.sqrtK,
pegMultiplier: updatedAmm.pegMultiplier,
};
const getL2Asks = function* () {
while (numAsks < numOrders && askSize.gt(ZERO)) {
let quoteSwapped: BN = ZERO;
let baseSwapped: BN = ZERO;
let [afterSwapQuoteReserves, afterSwapBaseReserves] = [ZERO, ZERO];
if (topOfBookQuoteAmounts && numAsks < topOfBookQuoteAmounts?.length) {
const remainingBaseLiquidity = openAsks
.mul(new BN(-1))
.sub(topOfBookAskSize);
quoteSwapped = topOfBookQuoteAmounts[numAsks];
[afterSwapQuoteReserves, afterSwapBaseReserves] =
calculateAmmReservesAfterSwap(
askAmm,
'quote',
quoteSwapped,
SwapDirection.ADD
);
baseSwapped = askAmm.baseAssetReserve.sub(afterSwapBaseReserves).abs();
if (baseSwapped.eq(ZERO)) {
return;
}
if (remainingBaseLiquidity.lt(baseSwapped)) {
baseSwapped = remainingBaseLiquidity;
[afterSwapQuoteReserves, afterSwapBaseReserves] =
calculateAmmReservesAfterSwap(
askAmm,
'base',
baseSwapped,
SwapDirection.REMOVE
);
quoteSwapped = calculateQuoteAssetAmountSwapped(
askAmm.quoteAssetReserve.sub(afterSwapQuoteReserves).abs(),
askAmm.pegMultiplier,
SwapDirection.REMOVE
);
}
topOfBookAskSize = topOfBookAskSize.add(baseSwapped);
askSize = openAsks
.abs()
.sub(topOfBookAskSize)
.div(new BN(numBaseOrders));
} else {
baseSwapped = askSize;
[afterSwapQuoteReserves, afterSwapBaseReserves] =
calculateAmmReservesAfterSwap(
askAmm,
'base',
askSize,
SwapDirection.REMOVE
);
quoteSwapped = calculateQuoteAssetAmountSwapped(
askAmm.quoteAssetReserve.sub(afterSwapQuoteReserves).abs(),
askAmm.pegMultiplier,
SwapDirection.REMOVE
);
}
const price = quoteSwapped.mul(BASE_PRECISION).div(baseSwapped);
askAmm.baseAssetReserve = afterSwapBaseReserves;
askAmm.quoteAssetReserve = afterSwapQuoteReserves;
yield {
price,
size: baseSwapped,
sources: { vamm: baseSwapped },
};
numAsks++;
}
};
return {
getL2Bids,
getL2Asks,
};
}
export function groupL2(
l2: L2OrderBook,
grouping: BN,
depth: number
): L2OrderBook {
return {
bids: groupL2Levels(l2.bids, grouping, PositionDirection.LONG, depth),
asks: groupL2Levels(l2.asks, grouping, PositionDirection.SHORT, depth),
slot: l2.slot,
};
}
function cloneL2Level(level: L2Level): L2Level {
if (!level) return level;
return {
price: level.price,
size: level.size,
sources: { ...level.sources },
};
}
function groupL2Levels(
levels: L2Level[],
grouping: BN,
direction: PositionDirection,
depth: number
): L2Level[] {
const groupedLevels: L2Level[] = [];
for (const level of levels) {
const price = standardizePrice(level.price, grouping, direction);
const size = level.size;
if (
groupedLevels.length > 0 &&
groupedLevels[groupedLevels.length - 1].price.eq(price)
) {
// Clones things so we don't mutate the original
const currentLevel = cloneL2Level(
groupedLevels[groupedLevels.length - 1]
);
currentLevel.size = currentLevel.size.add(size);
for (const [source, size] of Object.entries(level.sources)) {
if (currentLevel.sources[source]) {
currentLevel.sources[source] = currentLevel.sources[source].add(size);
} else {
currentLevel.sources[source] = size;
}
}
groupedLevels[groupedLevels.length - 1] = currentLevel;
} else {
const groupedLevel = {
price: price,
size,
sources: level.sources,
};
groupedLevels.push(groupedLevel);
}
if (groupedLevels.length === depth) {
break;
}
}
return groupedLevels;
}
/**
* Method to merge bids or asks by price
*/
const mergeByPrice = (bidsOrAsks: L2Level[]) => {
const merged = new Map<string, L2Level>();
for (const level of bidsOrAsks) {
const key = level.price.toString();
if (merged.has(key)) {
const existing = merged.get(key);
existing.size = existing.size.add(level.size);
for (const [source, size] of Object.entries(level.sources)) {
if (existing.sources[source]) {
existing.sources[source] = existing.sources[source].add(size);
} else {
existing.sources[source] = size;
}
}
} else {
merged.set(key, cloneL2Level(level));
}
}
return Array.from(merged.values());
};
/**
* The purpose of this function is uncross the L2 orderbook by modifying the bid/ask price at the top of the book
* This will make the liquidity look worse but more intuitive (users familiar with clob get confused w temporarily
* crossing book)
*
* Things to note about how it works:
* - it will not uncross the user's liquidity
* - it does the uncrossing by "shifting" the crossing liquidity to the nearest uncrossed levels. Thus the output liquidity maintains the same total size.
*
* @param bids
* @param asks
* @param oraclePrice
* @param oracleTwap5Min
* @param markTwap5Min
* @param grouping
* @param userBids
* @param userAsks
*/
export function uncrossL2(
bids: L2Level[],
asks: L2Level[],
oraclePrice: BN,
oracleTwap5Min: BN,
markTwap5Min: BN,
grouping: BN,
userBids: Set<string>,
userAsks: Set<string>
): { bids: L2Level[]; asks: L2Level[] } {
// If there are no bids or asks, there is nothing to center
if (bids.length === 0 || asks.length === 0) {
return { bids, asks };
}
// If the top of the book is already centered, there is nothing to do
if (bids[0].price.lt(asks[0].price)) {
return { bids, asks };
}
const newBids: L2Level[] = [];
const newAsks: L2Level[] = [];
const updateLevels = (newPrice: BN, oldLevel: L2Level, levels: L2Level[]) => {
if (levels.length > 0 && levels[levels.length - 1].price.eq(newPrice)) {
levels[levels.length - 1].size = levels[levels.length - 1].size.add(
oldLevel.size
);
for (const [source, size] of Object.entries(oldLevel.sources)) {
if (levels[levels.length - 1].sources[source]) {
levels[levels.length - 1].sources = {
...levels[levels.length - 1].sources,
[source]: levels[levels.length - 1].sources[source].add(size),
};
} else {
levels[levels.length - 1].sources[source] = size;
}
}
} else {
levels.push({
price: newPrice,
size: oldLevel.size,
sources: oldLevel.sources,
});
}
};
// This is the best estimate of the premium in the market vs oracle to filter crossing around
const referencePrice = oraclePrice.add(markTwap5Min.sub(oracleTwap5Min));
let bidIndex = 0;
let askIndex = 0;
let maxBid: BN;
let minAsk: BN;
const getPriceAndSetBound = (newPrice: BN, direction: PositionDirection) => {
if (isVariant(direction, 'long')) {
maxBid = maxBid ? BN.min(maxBid, newPrice) : newPrice;
return maxBid;
} else {
minAsk = minAsk ? BN.max(minAsk, newPrice) : newPrice;
return minAsk;
}
};
while (bidIndex < bids.length || askIndex < asks.length) {
const nextBid = cloneL2Level(bids[bidIndex]);
const nextAsk = cloneL2Level(asks[askIndex]);
if (!nextBid) {
newAsks.push(nextAsk);
askIndex++;
continue;
}
if (!nextAsk) {
newBids.push(nextBid);
bidIndex++;
continue;
}
if (userBids.has(nextBid.price.toString())) {
newBids.push(nextBid);
bidIndex++;
continue;
}
if (userAsks.has(nextAsk.price.toString())) {
newAsks.push(nextAsk);
askIndex++;
continue;
}
if (nextBid.price.gte(nextAsk.price)) {
if (
nextBid.price.gt(referencePrice) &&
nextAsk.price.gt(referencePrice)
) {
let newBidPrice = nextAsk.price.sub(grouping);
newBidPrice = getPriceAndSetBound(newBidPrice, PositionDirection.LONG);
updateLevels(newBidPrice, nextBid, newBids);
bidIndex++;
} else if (
nextAsk.price.lt(referencePrice) &&
nextBid.price.lt(referencePrice)
) {
let newAskPrice = nextBid.price.add(grouping);
newAskPrice = getPriceAndSetBound(newAskPrice, PositionDirection.SHORT);
updateLevels(newAskPrice, nextAsk, newAsks);
askIndex++;
} else {
let newBidPrice = referencePrice.sub(grouping);
let newAskPrice = referencePrice.add(grouping);
newBidPrice = getPriceAndSetBound(newBidPrice, PositionDirection.LONG);
newAskPrice = getPriceAndSetBound(newAskPrice, PositionDirection.SHORT);
updateLevels(newBidPrice, nextBid, newBids);
updateLevels(newAskPrice, nextAsk, newAsks);
bidIndex++;
askIndex++;
}
} else {
if (minAsk && nextAsk.price.lte(minAsk)) {
const newAskPrice = getPriceAndSetBound(
nextAsk.price,
PositionDirection.SHORT
);
updateLevels(newAskPrice, nextAsk, newAsks);
} else {
newAsks.push(nextAsk);
}
askIndex++;
if (maxBid && nextBid.price.gte(maxBid)) {
const newBidPrice = getPriceAndSetBound(
nextBid.price,
PositionDirection.LONG
);
updateLevels(newBidPrice, nextBid, newBids);
} else {
newBids.push(nextBid);
}
bidIndex++;
}
}
newBids.sort((a, b) => b.price.cmp(a.price));
newAsks.sort((a, b) => a.price.cmp(b.price));
const finalNewBids = mergeByPrice(newBids);
const finalNewAsks = mergeByPrice(newAsks);
return {
bids: finalNewBids,
asks: finalNewAsks,
};
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/dlob/DLOBSubscriber.ts
|
import { DLOB } from './DLOB';
import { EventEmitter } from 'events';
import StrictEventEmitter from 'strict-event-emitter-types';
import {
DLOBSource,
DLOBSubscriberEvents,
DLOBSubscriptionConfig,
SlotSource,
} from './types';
import { DriftClient } from '../driftClient';
import { isVariant, MarketType } from '../types';
import {
DEFAULT_TOP_OF_BOOK_QUOTE_AMOUNTS,
getVammL2Generator,
L2OrderBook,
L2OrderBookGenerator,
L3OrderBook,
} from './orderBookLevels';
export class DLOBSubscriber {
driftClient: DriftClient;
dlobSource: DLOBSource;
slotSource: SlotSource;
updateFrequency: number;
intervalId?: NodeJS.Timeout;
dlob = new DLOB();
public eventEmitter: StrictEventEmitter<EventEmitter, DLOBSubscriberEvents>;
constructor(config: DLOBSubscriptionConfig) {
this.driftClient = config.driftClient;
this.dlobSource = config.dlobSource;
this.slotSource = config.slotSource;
this.updateFrequency = config.updateFrequency;
this.eventEmitter = new EventEmitter();
}
public async subscribe(): Promise<void> {
if (this.intervalId) {
return;
}
await this.updateDLOB();
this.intervalId = setInterval(async () => {
try {
await this.updateDLOB();
this.eventEmitter.emit('update', this.dlob);
} catch (e) {
this.eventEmitter.emit('error', e);
}
}, this.updateFrequency);
}
async updateDLOB(): Promise<void> {
this.dlob = await this.dlobSource.getDLOB(this.slotSource.getSlot());
}
public getDLOB(): DLOB {
return this.dlob;
}
/**
* Get the L2 order book for a given market.
*
* @param marketName e.g. "SOL-PERP" or "SOL". If not provided, marketIndex and marketType must be provided.
* @param marketIndex
* @param marketType
* @param depth Number of orders to include in the order book. Defaults to 10.
* @param includeVamm Whether to include the VAMM orders in the order book. Defaults to false. If true, creates vAMM generator {@link getVammL2Generator} and adds it to fallbackL2Generators.
* @param fallbackL2Generators L2 generators for fallback liquidity e.g. vAMM {@link getVammL2Generator}, openbook {@link SerumSubscriber}
*/
public getL2({
marketName,
marketIndex,
marketType,
depth = 10,
includeVamm = false,
numVammOrders,
fallbackL2Generators = [],
}: {
marketName?: string;
marketIndex?: number;
marketType?: MarketType;
depth?: number;
includeVamm?: boolean;
numVammOrders?: number;
fallbackL2Generators?: L2OrderBookGenerator[];
}): L2OrderBook {
if (marketName) {
const derivedMarketInfo =
this.driftClient.getMarketIndexAndType(marketName);
if (!derivedMarketInfo) {
throw new Error(`Market ${marketName} not found`);
}
marketIndex = derivedMarketInfo.marketIndex;
marketType = derivedMarketInfo.marketType;
} else {
if (marketIndex === undefined || marketType === undefined) {
throw new Error(
'Either marketName or marketIndex and marketType must be provided'
);
}
}
let oraclePriceData;
const isPerp = isVariant(marketType, 'perp');
if (isPerp) {
const perpMarketAccount =
this.driftClient.getPerpMarketAccount(marketIndex);
oraclePriceData = this.driftClient.getOracleDataForPerpMarket(
perpMarketAccount.marketIndex
);
} else {
oraclePriceData =
this.driftClient.getOracleDataForSpotMarket(marketIndex);
}
if (isPerp && includeVamm) {
if (fallbackL2Generators.length > 0) {
throw new Error(
'includeVamm can only be used if fallbackL2Generators is empty'
);
}
fallbackL2Generators = [
getVammL2Generator({
marketAccount: this.driftClient.getPerpMarketAccount(marketIndex),
oraclePriceData,
numOrders: numVammOrders ?? depth,
topOfBookQuoteAmounts: DEFAULT_TOP_OF_BOOK_QUOTE_AMOUNTS,
}),
];
}
return this.dlob.getL2({
marketIndex,
marketType,
depth,
oraclePriceData,
slot: this.slotSource.getSlot(),
fallbackL2Generators: fallbackL2Generators,
});
}
/**
* Get the L3 order book for a given market.
*
* @param marketName e.g. "SOL-PERP" or "SOL". If not provided, marketIndex and marketType must be provided.
* @param marketIndex
* @param marketType
*/
public getL3({
marketName,
marketIndex,
marketType,
}: {
marketName?: string;
marketIndex?: number;
marketType?: MarketType;
}): L3OrderBook {
if (marketName) {
const derivedMarketInfo =
this.driftClient.getMarketIndexAndType(marketName);
if (!derivedMarketInfo) {
throw new Error(`Market ${marketName} not found`);
}
marketIndex = derivedMarketInfo.marketIndex;
marketType = derivedMarketInfo.marketType;
} else {
if (marketIndex === undefined || marketType === undefined) {
throw new Error(
'Either marketName or marketIndex and marketType must be provided'
);
}
}
let oraclePriceData;
const isPerp = isVariant(marketType, 'perp');
if (isPerp) {
oraclePriceData =
this.driftClient.getOracleDataForPerpMarket(marketIndex);
} else {
oraclePriceData =
this.driftClient.getOracleDataForSpotMarket(marketIndex);
}
return this.dlob.getL3({
marketIndex,
marketType,
oraclePriceData,
slot: this.slotSource.getSlot(),
});
}
public async unsubscribe(): Promise<void> {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = undefined;
}
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/dlob/types.ts
|
import { DLOB } from './DLOB';
import { DriftClient } from '../driftClient';
export type DLOBSubscriptionConfig = {
driftClient: DriftClient;
dlobSource: DLOBSource;
slotSource: SlotSource;
updateFrequency: number;
};
export interface DLOBSubscriberEvents {
update: (dlob: DLOB) => void;
error: (e: Error) => void;
}
export interface DLOBSource {
getDLOB(slot: number): Promise<DLOB>;
}
export interface SlotSource {
getSlot(): number;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/dlob/DLOBNode.ts
|
import {
AMM_RESERVE_PRECISION,
BN,
convertToNumber,
getLimitPrice,
isVariant,
PRICE_PRECISION,
OraclePriceData,
Order,
ZERO,
} from '..';
// import { PublicKey } from '@solana/web3.js';
import { getOrderSignature } from './NodeList';
export interface DLOBNode {
getPrice(oraclePriceData: OraclePriceData, slot: number): BN;
isVammNode(): boolean;
order: Order | undefined;
isBaseFilled(): boolean;
haveFilled: boolean;
userAccount: string | undefined;
isUserProtectedMaker: boolean;
isSwift: boolean | undefined;
}
export abstract class OrderNode implements DLOBNode {
order: Order;
userAccount: string;
sortValue: BN;
haveFilled = false;
haveTrigger = false;
isUserProtectedMaker: boolean;
isSwift: boolean;
constructor(
order: Order,
userAccount: string,
isUserProtectedMaker: boolean,
isSwift = false
) {
// Copy the order over to the node
this.order = { ...order };
this.userAccount = userAccount;
this.sortValue = this.getSortValue(order);
this.isUserProtectedMaker = isUserProtectedMaker;
this.isSwift = isSwift;
}
abstract getSortValue(order: Order): BN;
public getLabel(): string {
let msg = `Order ${getOrderSignature(
this.order.orderId,
this.userAccount
)}`;
msg += ` ${isVariant(this.order.direction, 'long') ? 'LONG' : 'SHORT'} `;
msg += `${convertToNumber(
this.order.baseAssetAmount,
AMM_RESERVE_PRECISION
).toFixed(3)}`;
if (this.order.price.gt(ZERO)) {
msg += ` @ ${convertToNumber(this.order.price, PRICE_PRECISION).toFixed(
3
)}`;
}
if (this.order.triggerPrice.gt(ZERO)) {
msg += ` ${
isVariant(this.order.triggerCondition, 'below') ? 'BELOW' : 'ABOVE'
}`;
msg += ` ${convertToNumber(
this.order.triggerPrice,
PRICE_PRECISION
).toFixed(3)}`;
}
return msg;
}
getPrice(oraclePriceData: OraclePriceData, slot: number): BN {
return getLimitPrice(this.order, oraclePriceData, slot);
}
isBaseFilled(): boolean {
return this.order.baseAssetAmountFilled.eq(this.order.baseAssetAmount);
}
isVammNode(): boolean {
return false;
}
}
export class TakingLimitOrderNode extends OrderNode {
next?: TakingLimitOrderNode;
previous?: TakingLimitOrderNode;
getSortValue(order: Order): BN {
return order.slot;
}
}
export class RestingLimitOrderNode extends OrderNode {
next?: RestingLimitOrderNode;
previous?: RestingLimitOrderNode;
getSortValue(order: Order): BN {
return order.price;
}
}
export class FloatingLimitOrderNode extends OrderNode {
next?: FloatingLimitOrderNode;
previous?: FloatingLimitOrderNode;
getSortValue(order: Order): BN {
return new BN(order.oraclePriceOffset);
}
}
export class MarketOrderNode extends OrderNode {
next?: MarketOrderNode;
previous?: MarketOrderNode;
getSortValue(order: Order): BN {
return order.slot;
}
}
export class TriggerOrderNode extends OrderNode {
next?: TriggerOrderNode;
previous?: TriggerOrderNode;
getSortValue(order: Order): BN {
return order.triggerPrice;
}
}
// We'll use the swift uuid for the order id since it's not yet on-chain
export class SwiftOrderNode extends OrderNode {
next?: SwiftOrderNode;
previous?: SwiftOrderNode;
constructor(order: Order, userAccount: string) {
super(order, userAccount, true);
}
getSortValue(order: Order): BN {
return order.slot;
}
}
export type DLOBNodeMap = {
restingLimit: RestingLimitOrderNode;
takingLimit: TakingLimitOrderNode;
floatingLimit: FloatingLimitOrderNode;
market: MarketOrderNode;
trigger: TriggerOrderNode;
swift: SwiftOrderNode;
};
export type DLOBNodeType =
| 'swift'
| 'restingLimit'
| 'takingLimit'
| 'floatingLimit'
| 'market'
| ('trigger' & keyof DLOBNodeMap);
export function createNode<T extends DLOBNodeType>(
nodeType: T,
order: Order,
userAccount: string,
isUserProtectedMaker: boolean
): DLOBNodeMap[T] {
switch (nodeType) {
case 'floatingLimit':
return new FloatingLimitOrderNode(
order,
userAccount,
isUserProtectedMaker
);
case 'restingLimit':
return new RestingLimitOrderNode(
order,
userAccount,
isUserProtectedMaker
);
case 'takingLimit':
return new TakingLimitOrderNode(order, userAccount, isUserProtectedMaker);
case 'market':
return new MarketOrderNode(order, userAccount, isUserProtectedMaker);
case 'trigger':
return new TriggerOrderNode(order, userAccount, isUserProtectedMaker);
case 'swift':
return new SwiftOrderNode(order, userAccount);
default:
throw Error(`Unknown DLOBNode type ${nodeType}`);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/oracles/pythLazerClient.ts
|
import { Connection, Keypair, PublicKey } from '@solana/web3.js';
import { OracleClient, OraclePriceData } from './types';
import { AnchorProvider, BN, Idl, Program } from '@coral-xyz/anchor';
import {
ONE,
PRICE_PRECISION,
QUOTE_PRECISION,
TEN,
} from '../constants/numericConstants';
import { DRIFT_PROGRAM_ID, Wallet } from '..';
import driftIDL from '../idl/drift.json';
export class PythLazerClient implements OracleClient {
private connection: Connection;
private multiple: BN;
private stableCoin: boolean;
private program: Program;
readonly decodeFunc: (name: string, data: Buffer) => any;
public constructor(
connection: Connection,
multiple = ONE,
stableCoin = false
) {
this.connection = connection;
this.multiple = multiple;
this.stableCoin = stableCoin;
const provider = new AnchorProvider(
this.connection,
//@ts-ignore
new Wallet(new Keypair()),
{
commitment: connection.commitment,
}
);
this.program = new Program(
driftIDL as Idl,
new PublicKey(DRIFT_PROGRAM_ID),
provider
);
this.decodeFunc =
this.program.account.pythLazerOracle.coder.accounts.decodeUnchecked.bind(
this.program.account.pythLazerOracle.coder.accounts
);
}
public async getOraclePriceData(
pricePublicKey: PublicKey
): Promise<OraclePriceData> {
const accountInfo = await this.connection.getAccountInfo(pricePublicKey);
return this.getOraclePriceDataFromBuffer(accountInfo.data);
}
public getOraclePriceDataFromBuffer(buffer: Buffer): OraclePriceData {
const priceData = this.decodeFunc('PythLazerOracle', buffer);
const confidence = convertPythPrice(
priceData.conf,
priceData.exponent,
this.multiple
);
let price = convertPythPrice(
priceData.price,
priceData.exponent,
this.multiple
);
if (this.stableCoin) {
price = getStableCoinPrice(price, confidence);
}
return {
price,
slot: priceData.postedSlot,
confidence,
twap: convertPythPrice(
priceData.price,
priceData.exponent,
this.multiple
),
twapConfidence: convertPythPrice(
priceData.price,
priceData.exponent,
this.multiple
),
hasSufficientNumberOfDataPoints: true,
};
}
}
function convertPythPrice(price: BN, exponent: number, multiple: BN): BN {
exponent = Math.abs(exponent);
const pythPrecision = TEN.pow(new BN(exponent).abs()).div(multiple);
return price.mul(PRICE_PRECISION).div(pythPrecision);
}
const fiveBPS = new BN(500);
function getStableCoinPrice(price: BN, confidence: BN): BN {
if (price.sub(QUOTE_PRECISION).abs().lt(BN.min(confidence, fiveBPS))) {
return QUOTE_PRECISION;
} else {
return price;
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/oracles/quoteAssetOracleClient.ts
|
import { PublicKey } from '@solana/web3.js';
import { OracleClient, OraclePriceData } from './types';
import { BN } from '@coral-xyz/anchor';
import { PRICE_PRECISION } from '../constants/numericConstants';
export const QUOTE_ORACLE_PRICE_DATA: OraclePriceData = {
price: PRICE_PRECISION,
slot: new BN(0),
confidence: new BN(1),
hasSufficientNumberOfDataPoints: true,
};
export class QuoteAssetOracleClient implements OracleClient {
public constructor() {}
public async getOraclePriceData(
_pricePublicKey: PublicKey
): Promise<OraclePriceData> {
return Promise.resolve(QUOTE_ORACLE_PRICE_DATA);
}
public getOraclePriceDataFromBuffer(_buffer: Buffer): OraclePriceData {
return QUOTE_ORACLE_PRICE_DATA;
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/oracles/oracleId.ts
|
import { PublicKey } from '@solana/web3.js';
import { OracleSource, OracleSourceNum } from '../types';
export function getOracleSourceNum(source: OracleSource): number {
if ('pyth' in source) return OracleSourceNum.PYTH;
if ('pyth1K' in source) return OracleSourceNum.PYTH_1K;
if ('pyth1M' in source) return OracleSourceNum.PYTH_1M;
if ('pythPull' in source) return OracleSourceNum.PYTH_PULL;
if ('pyth1KPull' in source) return OracleSourceNum.PYTH_1K_PULL;
if ('pyth1MPull' in source) return OracleSourceNum.PYTH_1M_PULL;
if ('switchboard' in source) return OracleSourceNum.SWITCHBOARD;
if ('quoteAsset' in source) return OracleSourceNum.QUOTE_ASSET;
if ('pythStableCoin' in source) return OracleSourceNum.PYTH_STABLE_COIN;
if ('pythStableCoinPull' in source)
return OracleSourceNum.PYTH_STABLE_COIN_PULL;
if ('prelaunch' in source) return OracleSourceNum.PRELAUNCH;
if ('switchboardOnDemand' in source)
return OracleSourceNum.SWITCHBOARD_ON_DEMAND;
if ('pythLazer' in source) return OracleSourceNum.PYTH_LAZER;
throw new Error('Invalid oracle source');
}
export function getOracleId(
publicKey: PublicKey,
source: OracleSource
): string {
return `${publicKey.toBase58()}-${getOracleSourceNum(source)}`;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/oracles/pythClient.ts
|
import { parsePriceData } from '@pythnetwork/client';
import { Connection, PublicKey } from '@solana/web3.js';
import { OracleClient, OraclePriceData } from './types';
import { BN } from '@coral-xyz/anchor';
import {
ONE,
PRICE_PRECISION,
QUOTE_PRECISION,
TEN,
} from '../constants/numericConstants';
export class PythClient implements OracleClient {
private connection: Connection;
private multiple: BN;
private stableCoin: boolean;
public constructor(
connection: Connection,
multiple = ONE,
stableCoin = false
) {
this.connection = connection;
this.multiple = multiple;
this.stableCoin = stableCoin;
}
public async getOraclePriceData(
pricePublicKey: PublicKey
): Promise<OraclePriceData> {
const accountInfo = await this.connection.getAccountInfo(pricePublicKey);
return this.getOraclePriceDataFromBuffer(accountInfo.data);
}
public getOraclePriceDataFromBuffer(buffer: Buffer): OraclePriceData {
const priceData = parsePriceData(buffer);
const confidence = convertPythPrice(
priceData.confidence,
priceData.exponent,
this.multiple
);
const minPublishers = Math.min(priceData.numComponentPrices, 3);
let price = convertPythPrice(
priceData.aggregate.price,
priceData.exponent,
this.multiple
);
if (this.stableCoin) {
price = getStableCoinPrice(price, confidence);
}
return {
price,
slot: new BN(priceData.lastSlot.toString()),
confidence,
twap: convertPythPrice(
priceData.twap.value,
priceData.exponent,
this.multiple
),
twapConfidence: convertPythPrice(
priceData.twac.value,
priceData.exponent,
this.multiple
),
hasSufficientNumberOfDataPoints: priceData.numQuoters >= minPublishers,
};
}
}
function convertPythPrice(price: number, exponent: number, multiple: BN): BN {
exponent = Math.abs(exponent);
const pythPrecision = TEN.pow(new BN(exponent).abs()).div(multiple);
return new BN(price * Math.pow(10, exponent))
.mul(PRICE_PRECISION)
.div(pythPrecision);
}
const fiveBPS = new BN(500);
function getStableCoinPrice(price: BN, confidence: BN): BN {
if (price.sub(QUOTE_PRECISION).abs().lt(BN.min(confidence, fiveBPS))) {
return QUOTE_PRECISION;
} else {
return price;
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/oracles/pythPullClient.ts
|
import { Connection, Keypair, PublicKey } from '@solana/web3.js';
import { OracleClient, OraclePriceData } from './types';
import { AnchorProvider, BN, Program } from '@coral-xyz/anchor';
import {
ONE,
PRICE_PRECISION,
QUOTE_PRECISION,
TEN,
} from '../constants/numericConstants';
import {
PythSolanaReceiverProgram,
pythSolanaReceiverIdl,
} from '@pythnetwork/pyth-solana-receiver';
import { PriceUpdateAccount } from '@pythnetwork/pyth-solana-receiver/lib/PythSolanaReceiver';
import { DRIFT_ORACLE_RECEIVER_ID, Wallet } from '..';
export class PythPullClient implements OracleClient {
private connection: Connection;
private multiple: BN;
private stableCoin: boolean;
readonly receiver: Program<PythSolanaReceiverProgram>;
readonly decodeFunc: (name: string, data: Buffer) => PriceUpdateAccount;
public constructor(
connection: Connection,
multiple = ONE,
stableCoin = false
) {
this.connection = connection;
this.multiple = multiple;
this.stableCoin = stableCoin;
const provider = new AnchorProvider(
this.connection,
//@ts-ignore
new Wallet(new Keypair()),
{
commitment: connection.commitment,
}
);
this.receiver = new Program<PythSolanaReceiverProgram>(
pythSolanaReceiverIdl as PythSolanaReceiverProgram,
DRIFT_ORACLE_RECEIVER_ID,
provider
);
this.decodeFunc =
this.receiver.account.priceUpdateV2.coder.accounts.decodeUnchecked.bind(
this.receiver.account.priceUpdateV2.coder.accounts
);
}
public async getOraclePriceData(
pricePublicKey: PublicKey
): Promise<OraclePriceData> {
const accountInfo = await this.connection.getAccountInfo(pricePublicKey);
return this.getOraclePriceDataFromBuffer(accountInfo.data);
}
public getOraclePriceDataFromBuffer(buffer: Buffer): OraclePriceData {
const message = this.decodeFunc('priceUpdateV2', buffer);
const priceData = message.priceMessage;
const confidence = convertPythPrice(
priceData.conf,
priceData.exponent,
this.multiple
);
let price = convertPythPrice(
priceData.price,
priceData.exponent,
this.multiple
);
if (this.stableCoin) {
price = getStableCoinPrice(price, confidence);
}
return {
price,
slot: message.postedSlot,
confidence,
twap: convertPythPrice(
priceData.price,
priceData.exponent,
this.multiple
),
twapConfidence: convertPythPrice(
priceData.price,
priceData.exponent,
this.multiple
),
hasSufficientNumberOfDataPoints: true,
};
}
}
export function convertPythPrice(
price: BN,
exponent: number,
multiple: BN
): BN {
exponent = Math.abs(exponent);
const pythPrecision = TEN.pow(new BN(exponent).abs()).div(multiple);
return price.mul(PRICE_PRECISION).div(pythPrecision);
}
const fiveBPS = new BN(500);
function getStableCoinPrice(price: BN, confidence: BN): BN {
if (price.sub(QUOTE_PRECISION).abs().lt(BN.min(confidence, fiveBPS))) {
return QUOTE_PRECISION;
} else {
return price;
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/oracles/types.ts
|
import { BN } from '@coral-xyz/anchor';
import { PublicKey } from '@solana/web3.js';
import { OracleSource } from '../types';
export type OraclePriceData = {
price: BN;
slot: BN;
confidence: BN;
hasSufficientNumberOfDataPoints: boolean;
twap?: BN;
twapConfidence?: BN;
maxPrice?: BN; // pre-launch markets only
};
export type OracleInfo = {
publicKey: PublicKey;
source: OracleSource;
};
export interface OracleClient {
getOraclePriceDataFromBuffer(buffer: Buffer): OraclePriceData;
getOraclePriceData(publicKey: PublicKey): Promise<OraclePriceData>;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/oracles/switchboardClient.ts
|
import { Connection, PublicKey } from '@solana/web3.js';
import { PRICE_PRECISION, TEN } from '../constants/numericConstants';
import { OracleClient, OraclePriceData } from './types';
import switchboardV2Idl from '../idl/switchboard.json';
import { BorshAccountsCoder, BN, Idl } from '@coral-xyz/anchor';
type SwitchboardDecimal = {
scale: number;
mantissa: BN;
};
type AggregatorAccountData = {
latestConfirmedRound: {
result: SwitchboardDecimal;
stdDeviation: SwitchboardDecimal;
numSuccess: number;
roundOpenSlot: BN;
};
minOracleResults: number;
};
export class SwitchboardClient implements OracleClient {
connection: Connection;
coder: BorshAccountsCoder;
public constructor(connection: Connection) {
this.connection = connection;
this.coder = new BorshAccountsCoder(switchboardV2Idl as Idl);
}
public async getOraclePriceData(
pricePublicKey: PublicKey
): Promise<OraclePriceData> {
const accountInfo = await this.connection.getAccountInfo(pricePublicKey);
return this.getOraclePriceDataFromBuffer(accountInfo.data);
}
public getOraclePriceDataFromBuffer(buffer: Buffer): OraclePriceData {
const aggregatorAccountData = this.coder.decodeUnchecked(
'AggregatorAccountData',
buffer
) as AggregatorAccountData;
const price = convertSwitchboardDecimal(
aggregatorAccountData.latestConfirmedRound.result
);
const confidence = BN.max(
convertSwitchboardDecimal(
aggregatorAccountData.latestConfirmedRound.stdDeviation
),
price.divn(1000)
);
const hasSufficientNumberOfDataPoints =
aggregatorAccountData.latestConfirmedRound.numSuccess >=
aggregatorAccountData.minOracleResults;
const slot: BN = aggregatorAccountData.latestConfirmedRound.roundOpenSlot;
return {
price,
slot,
confidence,
hasSufficientNumberOfDataPoints,
};
}
}
function convertSwitchboardDecimal(switchboardDecimal: {
scale: number;
mantissa: BN;
}): BN {
const switchboardPrecision = TEN.pow(new BN(switchboardDecimal.scale));
return switchboardDecimal.mantissa
.mul(PRICE_PRECISION)
.div(switchboardPrecision);
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/oracles/strictOraclePrice.ts
|
import { BN } from '@coral-xyz/anchor';
export class StrictOraclePrice {
current: BN;
twap?: BN;
constructor(current: BN, twap?: BN) {
this.current = current;
this.twap = twap;
}
public max(): BN {
return this.twap ? BN.max(this.twap, this.current) : this.current;
}
public min(): BN {
return this.twap ? BN.min(this.twap, this.current) : this.current;
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/oracles/oracleClientCache.ts
|
import { OracleClient } from './types';
import { OracleSource } from '../types';
import { getOracleClient } from '../factory/oracleClient';
import { Connection } from '@solana/web3.js';
import { Program } from '@coral-xyz/anchor';
export class OracleClientCache {
cache = new Map<string, OracleClient>();
public constructor() {}
public get(
oracleSource: OracleSource,
connection: Connection,
program: Program
) {
const key = Object.keys(oracleSource)[0];
if (this.cache.has(key)) {
return this.cache.get(key);
}
const client = getOracleClient(oracleSource, connection, program);
this.cache.set(key, client);
return client;
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/oracles/prelaunchOracleClient.ts
|
import { Connection, PublicKey } from '@solana/web3.js';
import { OracleClient, OraclePriceData } from './types';
import { Program } from '@coral-xyz/anchor';
import { PrelaunchOracle } from '../types';
export class PrelaunchOracleClient implements OracleClient {
private connection: Connection;
private program: Program;
public constructor(connection: Connection, program: Program) {
this.connection = connection;
this.program = program;
}
public async getOraclePriceData(
pricePublicKey: PublicKey
): Promise<OraclePriceData> {
const accountInfo = await this.connection.getAccountInfo(pricePublicKey);
return this.getOraclePriceDataFromBuffer(accountInfo.data);
}
public getOraclePriceDataFromBuffer(buffer: Buffer): OraclePriceData {
const prelaunchOracle =
this.program.account.prelaunchOracle.coder.accounts.decodeUnchecked(
'PrelaunchOracle',
buffer
) as PrelaunchOracle;
return {
price: prelaunchOracle.price,
slot: prelaunchOracle.ammLastUpdateSlot,
confidence: prelaunchOracle.confidence,
hasSufficientNumberOfDataPoints: true,
maxPrice: prelaunchOracle.maxPrice,
};
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/oracles/switchboardOnDemandClient.ts
|
import { Connection, PublicKey } from '@solana/web3.js';
import { OracleClient, OraclePriceData } from './types';
import { BN } from '@coral-xyz/anchor';
import switchboardOnDemandIdl from '../idl/switchboard_on_demand_30.json';
import { PRICE_PRECISION_EXP } from '../constants/numericConstants';
import {
BorshAccountsCoder as BorshAccountsCoder30,
Idl as Idl30,
} from '@coral-xyz/anchor-30';
const SB_PRECISION_EXP = new BN(18);
const SB_PRECISION = new BN(10).pow(SB_PRECISION_EXP.sub(PRICE_PRECISION_EXP));
type PullFeedAccountData = {
result: {
value: BN;
std_dev: BN;
mean: BN;
slot: BN;
range: BN;
};
last_update_timestamp: BN;
max_variance: BN;
min_responses: BN;
};
export class SwitchboardOnDemandClient implements OracleClient {
connection: Connection;
coder: BorshAccountsCoder30;
public constructor(connection: Connection) {
this.connection = connection;
this.coder = new BorshAccountsCoder30(switchboardOnDemandIdl as Idl30);
}
public async getOraclePriceData(
pricePublicKey: PublicKey
): Promise<OraclePriceData> {
const accountInfo = await this.connection.getAccountInfo(pricePublicKey);
return this.getOraclePriceDataFromBuffer(accountInfo.data);
}
public getOraclePriceDataFromBuffer(buffer: Buffer): OraclePriceData {
const pullFeedAccountData = this.coder.decodeUnchecked(
'PullFeedAccountData',
buffer
) as PullFeedAccountData;
return {
price: pullFeedAccountData.result.value.div(SB_PRECISION),
slot: pullFeedAccountData.result.slot,
confidence: pullFeedAccountData.result.range.div(SB_PRECISION),
hasSufficientNumberOfDataPoints: true,
};
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/priorityFee/priorityFeeSubscriberMap.ts
|
import {
DriftMarketInfo,
DriftPriorityFeeLevels,
DriftPriorityFeeResponse,
fetchDriftPriorityFee,
} from './driftPriorityFeeMethod';
import {
DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS,
PriorityFeeSubscriberMapConfig,
} from './types';
/**
* takes advantage of /batchPriorityFees endpoint from drift hosted priority fee service
*/
export class PriorityFeeSubscriberMap {
frequencyMs: number;
intervalId?: ReturnType<typeof setTimeout>;
driftMarkets?: DriftMarketInfo[];
driftPriorityFeeEndpoint?: string;
feesMap: Map<string, Map<number, DriftPriorityFeeLevels>>; // marketType -> marketIndex -> priority fee
public constructor(config: PriorityFeeSubscriberMapConfig) {
this.frequencyMs = config.frequencyMs;
this.frequencyMs =
config.frequencyMs ?? DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS;
this.driftPriorityFeeEndpoint = config.driftPriorityFeeEndpoint;
this.driftMarkets = config.driftMarkets;
this.feesMap = new Map<string, Map<number, DriftPriorityFeeLevels>>();
this.feesMap.set('perp', new Map<number, DriftPriorityFeeLevels>());
this.feesMap.set('spot', new Map<number, DriftPriorityFeeLevels>());
}
private updateFeesMap(driftPriorityFeeResponse: DriftPriorityFeeResponse) {
driftPriorityFeeResponse.forEach((fee: DriftPriorityFeeLevels) => {
this.feesMap.get(fee.marketType)!.set(fee.marketIndex, fee);
});
}
public async subscribe(): Promise<void> {
if (this.intervalId) {
return;
}
await this.load();
this.intervalId = setInterval(this.load.bind(this), this.frequencyMs);
}
public async unsubscribe(): Promise<void> {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = undefined;
}
}
public async load(): Promise<void> {
try {
if (!this.driftMarkets) {
return;
}
const fees = await fetchDriftPriorityFee(
this.driftPriorityFeeEndpoint!,
this.driftMarkets.map((m) => m.marketType),
this.driftMarkets.map((m) => m.marketIndex)
);
this.updateFeesMap(fees);
} catch (e) {
console.error('Error fetching drift priority fees', e);
}
}
public updateMarketTypeAndIndex(driftMarkets: DriftMarketInfo[]) {
this.driftMarkets = driftMarkets;
}
public getPriorityFees(
marketType: string,
marketIndex: number
): DriftPriorityFeeLevels | undefined {
return this.feesMap.get(marketType)?.get(marketIndex);
}
}
/** Example usage:
async function main() {
const driftMarkets: DriftMarketInfo[] = [
{ marketType: 'perp', marketIndex: 0 },
{ marketType: 'perp', marketIndex: 1 },
{ marketType: 'spot', marketIndex: 2 }
];
const subscriber = new PriorityFeeSubscriberMap({
driftPriorityFeeEndpoint: 'https://dlob.drift.trade',
frequencyMs: 5000,
driftMarkets
});
await subscriber.subscribe();
for (let i = 0; i < 20; i++) {
await new Promise(resolve => setTimeout(resolve, 1000));
driftMarkets.forEach(market => {
const fees = subscriber.getPriorityFees(market.marketType, market.marketIndex);
console.log(`Priority fees for ${market.marketType} market ${market.marketIndex}:`, fees);
});
}
await subscriber.unsubscribe();
}
main().catch(console.error);
*/
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/priorityFee/maxOverSlotsStrategy.ts
|
import { SolanaPriorityFeeResponse } from './solanaPriorityFeeMethod';
import { PriorityFeeStrategy } from './types';
export class MaxOverSlotsStrategy implements PriorityFeeStrategy {
calculate(samples: SolanaPriorityFeeResponse[]): number {
if (samples.length === 0) {
return 0;
}
// Assuming samples are sorted in descending order of slot.
let currMaxFee = samples[0].prioritizationFee;
for (let i = 0; i < samples.length; i++) {
currMaxFee = Math.max(samples[i].prioritizationFee, currMaxFee);
}
return currMaxFee;
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/priorityFee/driftPriorityFeeMethod.ts
|
import fetch from 'node-fetch';
import { HeliusPriorityLevel } from './heliusPriorityFeeMethod';
export type DriftMarketInfo = {
marketType: string;
marketIndex: number;
};
export type DriftPriorityFeeLevels = {
[key in HeliusPriorityLevel]: number;
} & {
marketType: 'perp' | 'spot';
marketIndex: number;
};
export type DriftPriorityFeeResponse = DriftPriorityFeeLevels[];
export async function fetchDriftPriorityFee(
url: string,
marketTypes: string[],
marketIndexes: number[]
): Promise<DriftPriorityFeeResponse> {
try {
const response = await fetch(
`${url}/batchPriorityFees?marketType=${marketTypes.join(
','
)}&marketIndex=${marketIndexes.join(',')}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (err) {
if (err instanceof Error) {
console.error('Error fetching priority fees:', err.message);
} else {
console.error('Unknown error fetching priority fees:', err);
}
}
return [];
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/priorityFee/solanaPriorityFeeMethod.ts
|
import { Connection } from '@solana/web3.js';
export type SolanaPriorityFeeResponse = {
slot: number;
prioritizationFee: number;
};
export async function fetchSolanaPriorityFee(
connection: Connection,
lookbackDistance: number,
addresses: string[]
): Promise<SolanaPriorityFeeResponse[]> {
try {
// @ts-ignore
const rpcJSONResponse: any = await connection._rpcRequest(
'getRecentPrioritizationFees',
[addresses]
);
const results: SolanaPriorityFeeResponse[] = rpcJSONResponse?.result;
if (!results.length) return;
// Sort and filter results based on the slot lookback setting
const descResults = results.sort((a, b) => b.slot - a.slot);
const cutoffSlot = descResults[0].slot - lookbackDistance;
return descResults.filter((result) => result.slot >= cutoffSlot);
} catch (err) {
console.error(err);
}
return [];
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/priorityFee/maxStrategy.ts
|
import { PriorityFeeStrategy } from './types';
export class MaxStrategy implements PriorityFeeStrategy {
calculate(samples: { slot: number; prioritizationFee: number }[]): number {
return Math.max(...samples.map((result) => result.prioritizationFee));
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/priorityFee/heliusPriorityFeeMethod.ts
|
import fetch from 'node-fetch';
export enum HeliusPriorityLevel {
MIN = 'min', // 25th percentile
LOW = 'low', // 25th percentile
MEDIUM = 'medium', // 50th percentile
HIGH = 'high', // 75th percentile
VERY_HIGH = 'veryHigh', // 95th percentile
UNSAFE_MAX = 'unsafeMax', // 100th percentile
}
export type HeliusPriorityFeeLevels = {
[key in HeliusPriorityLevel]: number;
};
export type HeliusPriorityFeeResponse = {
jsonrpc: string;
result: {
priorityFeeEstimate?: number;
priorityFeeLevels?: HeliusPriorityFeeLevels;
};
id: string;
};
/// Fetches the priority fee from the Helius API
/// https://docs.helius.dev/solana-rpc-nodes/alpha-priority-fee-api
export async function fetchHeliusPriorityFee(
heliusRpcUrl: string,
lookbackDistance: number,
addresses: string[]
): Promise<HeliusPriorityFeeResponse> {
try {
const response = await fetch(heliusRpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
id: '1',
method: 'getPriorityFeeEstimate',
params: [
{
accountKeys: addresses,
options: {
includeAllPriorityFeeLevels: true,
lookbackSlots: lookbackDistance,
},
},
],
}),
});
return await response.json();
} catch (err) {
console.error(err);
}
return undefined;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/priorityFee/averageStrategy.ts
|
import { SolanaPriorityFeeResponse } from './solanaPriorityFeeMethod';
import { PriorityFeeStrategy } from './types';
export class AverageStrategy implements PriorityFeeStrategy {
calculate(samples: SolanaPriorityFeeResponse[]): number {
return (
samples.reduce((a, b) => {
return a + b.prioritizationFee;
}, 0) / samples.length
);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/priorityFee/types.ts
|
import { Connection, PublicKey } from '@solana/web3.js';
import { SolanaPriorityFeeResponse } from './solanaPriorityFeeMethod';
import { HeliusPriorityFeeResponse } from './heliusPriorityFeeMethod';
import {
DriftMarketInfo,
DriftPriorityFeeResponse,
} from './driftPriorityFeeMethod';
export const DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS = 10_000;
export interface PriorityFeeStrategy {
// calculate the priority fee for a given set of samples.
// expect samples to be sorted in descending order (by slot)
calculate(
samples:
| SolanaPriorityFeeResponse[]
| HeliusPriorityFeeResponse
| DriftPriorityFeeResponse
): number;
}
export enum PriorityFeeMethod {
SOLANA = 'solana',
HELIUS = 'helius',
DRIFT = 'drift',
}
export type PriorityFeeSubscriberConfig = {
/// rpc connection, optional if using priorityFeeMethod.HELIUS
connection?: Connection;
/// frequency to make RPC calls to update priority fee samples, in milliseconds
frequencyMs?: number;
/// addresses you plan to write lock, used to determine priority fees
addresses?: PublicKey[];
/// drift market type and index, optionally provide at initialization time if using priorityFeeMethod.DRIFT
driftMarkets?: DriftMarketInfo[];
/// custom strategy to calculate priority fees, defaults to AVERAGE
customStrategy?: PriorityFeeStrategy;
/// method for fetching priority fee samples
priorityFeeMethod?: PriorityFeeMethod;
/// lookback window to determine priority fees, in slots.
slotsToCheck?: number;
/// url for helius rpc, required if using priorityFeeMethod.HELIUS
heliusRpcUrl?: string;
/// url for drift cached priority fee endpoint, required if using priorityFeeMethod.DRIFT
driftPriorityFeeEndpoint?: string;
/// clamp any returned priority fee value to this value.
maxFeeMicroLamports?: number;
/// multiplier applied to priority fee before maxFeeMicroLamports, defaults to 1.0
priorityFeeMultiplier?: number;
};
export type PriorityFeeSubscriberMapConfig = {
/// frequency to make RPC calls to update priority fee samples, in milliseconds
frequencyMs?: number;
/// drift market type and associated market index to query
driftMarkets?: DriftMarketInfo[];
/// url for drift cached priority fee endpoint
driftPriorityFeeEndpoint: string;
};
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/priorityFee/ewmaStrategy.ts
|
import { SolanaPriorityFeeResponse } from './solanaPriorityFeeMethod';
import { PriorityFeeStrategy } from './types';
class EwmaStrategy implements PriorityFeeStrategy {
private halfLife: number;
/**
* @param halfLife The half life of the EWMA in slots. Default is 25 slots, approx 10 seconds.
*/
constructor(halfLife = 25) {
this.halfLife = halfLife;
}
// samples provided in desc slot order
calculate(samples: SolanaPriorityFeeResponse[]): number {
if (samples.length === 0) {
return 0;
}
if (samples.length === 1) {
return samples[0].prioritizationFee;
}
let ewma = 0;
const samplesReversed = samples.slice().reverse();
for (let i = 0; i < samplesReversed.length; i++) {
if (i === 0) {
ewma = samplesReversed[i].prioritizationFee;
continue;
}
const gap = samplesReversed[i].slot - samplesReversed[i - 1].slot;
const alpha = 1 - Math.exp((Math.log(0.5) / this.halfLife) * gap);
ewma = alpha * samplesReversed[i].prioritizationFee + (1 - alpha) * ewma;
}
return ewma;
}
}
export { EwmaStrategy };
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/priorityFee/priorityFeeSubscriber.ts
|
import { Connection, PublicKey } from '@solana/web3.js';
import {
DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS,
PriorityFeeMethod,
PriorityFeeStrategy,
PriorityFeeSubscriberConfig,
} from './types';
import { AverageOverSlotsStrategy } from './averageOverSlotsStrategy';
import { MaxOverSlotsStrategy } from './maxOverSlotsStrategy';
import { fetchSolanaPriorityFee } from './solanaPriorityFeeMethod';
import {
HeliusPriorityFeeLevels,
HeliusPriorityLevel,
fetchHeliusPriorityFee,
} from './heliusPriorityFeeMethod';
import {
fetchDriftPriorityFee,
DriftMarketInfo,
} from './driftPriorityFeeMethod';
export class PriorityFeeSubscriber {
connection: Connection;
frequencyMs: number;
addresses: string[];
driftMarkets?: DriftMarketInfo[];
customStrategy?: PriorityFeeStrategy;
averageStrategy = new AverageOverSlotsStrategy();
maxStrategy = new MaxOverSlotsStrategy();
priorityFeeMethod = PriorityFeeMethod.SOLANA;
lookbackDistance: number;
maxFeeMicroLamports?: number;
priorityFeeMultiplier?: number;
driftPriorityFeeEndpoint?: string;
heliusRpcUrl?: string;
lastHeliusSample?: HeliusPriorityFeeLevels;
intervalId?: ReturnType<typeof setTimeout>;
latestPriorityFee = 0;
lastCustomStrategyResult = 0;
lastAvgStrategyResult = 0;
lastMaxStrategyResult = 0;
lastSlotSeen = 0;
public constructor(config: PriorityFeeSubscriberConfig) {
this.connection = config.connection;
this.frequencyMs =
config.frequencyMs ?? DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS;
this.addresses = config.addresses
? config.addresses.map((address) => address.toBase58())
: [];
this.driftMarkets = config.driftMarkets;
if (config.customStrategy) {
this.customStrategy = config.customStrategy;
} else {
this.customStrategy = this.averageStrategy;
}
this.lookbackDistance = config.slotsToCheck ?? 50;
if (config.priorityFeeMethod) {
this.priorityFeeMethod = config.priorityFeeMethod;
if (this.priorityFeeMethod === PriorityFeeMethod.HELIUS) {
if (config.heliusRpcUrl === undefined) {
if (this.connection.rpcEndpoint.includes('helius')) {
this.heliusRpcUrl = this.connection.rpcEndpoint;
} else {
throw new Error(
'Connection must be helius, or heliusRpcUrl must be provided to use PriorityFeeMethod.HELIUS'
);
}
} else {
this.heliusRpcUrl = config.heliusRpcUrl;
}
} else if (this.priorityFeeMethod === PriorityFeeMethod.DRIFT) {
this.driftPriorityFeeEndpoint = config.driftPriorityFeeEndpoint;
}
}
if (this.priorityFeeMethod === PriorityFeeMethod.SOLANA) {
if (this.connection === undefined) {
throw new Error(
'connection must be provided to use SOLANA priority fee API'
);
}
}
this.maxFeeMicroLamports = config.maxFeeMicroLamports;
this.priorityFeeMultiplier = config.priorityFeeMultiplier ?? 1.0;
}
public async subscribe(): Promise<void> {
if (this.intervalId) {
return;
}
this.intervalId = setInterval(this.load.bind(this), this.frequencyMs); // we set the intervalId first, preventing a side effect of unsubscribing failing during the race condition where unsubscribes happens before subscribe is finished
await this.load();
}
private async loadForSolana(): Promise<void> {
const samples = await fetchSolanaPriorityFee(
this.connection!,
this.lookbackDistance,
this.addresses
);
if (samples.length > 0) {
this.latestPriorityFee = samples[0].prioritizationFee;
this.lastSlotSeen = samples[0].slot;
this.lastAvgStrategyResult = this.averageStrategy.calculate(samples);
this.lastMaxStrategyResult = this.maxStrategy.calculate(samples);
if (this.customStrategy) {
this.lastCustomStrategyResult = this.customStrategy.calculate(samples);
}
}
}
private async loadForHelius(): Promise<void> {
const sample = await fetchHeliusPriorityFee(
this.heliusRpcUrl,
this.lookbackDistance,
this.addresses
);
this.lastHeliusSample = sample?.result?.priorityFeeLevels ?? undefined;
if (this.lastHeliusSample) {
this.lastAvgStrategyResult =
this.lastHeliusSample[HeliusPriorityLevel.MEDIUM];
this.lastMaxStrategyResult =
this.lastHeliusSample[HeliusPriorityLevel.UNSAFE_MAX];
if (this.customStrategy) {
this.lastCustomStrategyResult = this.customStrategy.calculate(sample!);
}
}
}
private async loadForDrift(): Promise<void> {
if (!this.driftMarkets) {
return;
}
const sample = await fetchDriftPriorityFee(
this.driftPriorityFeeEndpoint!,
this.driftMarkets.map((m) => m.marketType),
this.driftMarkets.map((m) => m.marketIndex)
);
if (sample.length > 0) {
this.lastAvgStrategyResult = sample[HeliusPriorityLevel.MEDIUM];
this.lastMaxStrategyResult = sample[HeliusPriorityLevel.UNSAFE_MAX];
if (this.customStrategy) {
this.lastCustomStrategyResult = this.customStrategy.calculate(sample);
}
}
}
public getMaxPriorityFee(): number | undefined {
return this.maxFeeMicroLamports;
}
public updateMaxPriorityFee(newMaxFee: number | undefined) {
this.maxFeeMicroLamports = newMaxFee;
}
public getPriorityFeeMultiplier(): number {
return this.priorityFeeMultiplier ?? 1.0;
}
public updatePriorityFeeMultiplier(newPriorityFeeMultiplier: number) {
this.priorityFeeMultiplier = newPriorityFeeMultiplier;
}
public updateCustomStrategy(newStrategy: PriorityFeeStrategy) {
this.customStrategy = newStrategy;
}
public getHeliusPriorityFeeLevel(
level: HeliusPriorityLevel = HeliusPriorityLevel.MEDIUM
): number {
if (this.lastHeliusSample === undefined) {
return 0;
}
if (this.maxFeeMicroLamports !== undefined) {
return Math.min(this.maxFeeMicroLamports, this.lastHeliusSample[level]);
}
return this.lastHeliusSample[level];
}
public getCustomStrategyResult(): number {
const result =
this.lastCustomStrategyResult * this.getPriorityFeeMultiplier();
if (this.maxFeeMicroLamports !== undefined) {
return Math.min(this.maxFeeMicroLamports, result);
}
return result;
}
public getAvgStrategyResult(): number {
const result = this.lastAvgStrategyResult * this.getPriorityFeeMultiplier();
if (this.maxFeeMicroLamports !== undefined) {
return Math.min(this.maxFeeMicroLamports, result);
}
return result;
}
public getMaxStrategyResult(): number {
const result = this.lastMaxStrategyResult * this.getPriorityFeeMultiplier();
if (this.maxFeeMicroLamports !== undefined) {
return Math.min(this.maxFeeMicroLamports, result);
}
return result;
}
public async load(): Promise<void> {
try {
if (this.priorityFeeMethod === PriorityFeeMethod.SOLANA) {
await this.loadForSolana();
} else if (this.priorityFeeMethod === PriorityFeeMethod.HELIUS) {
await this.loadForHelius();
} else if (this.priorityFeeMethod === PriorityFeeMethod.DRIFT) {
await this.loadForDrift();
} else {
throw new Error(`${this.priorityFeeMethod} load not implemented`);
}
} catch (err) {
const e = err as Error;
console.error(
`Error loading priority fee ${this.priorityFeeMethod}: ${e.message}\n${
e.stack ? e.stack : ''
}`
);
return;
}
}
public async unsubscribe(): Promise<void> {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = undefined;
}
}
public updateAddresses(addresses: PublicKey[]) {
this.addresses = addresses.map((k) => k.toBase58());
}
public updateMarketTypeAndIndex(driftMarkets: DriftMarketInfo[]) {
this.driftMarkets = driftMarkets;
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/priorityFee/index.ts
|
export * from './averageOverSlotsStrategy';
export * from './averageStrategy';
export * from './ewmaStrategy';
export * from './maxOverSlotsStrategy';
export * from './maxStrategy';
export * from './priorityFeeSubscriber';
export * from './priorityFeeSubscriberMap';
export * from './solanaPriorityFeeMethod';
export * from './heliusPriorityFeeMethod';
export * from './driftPriorityFeeMethod';
export * from './types';
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/priorityFee/averageOverSlotsStrategy.ts
|
import { SolanaPriorityFeeResponse } from './solanaPriorityFeeMethod';
import { PriorityFeeStrategy } from './types';
export class AverageOverSlotsStrategy implements PriorityFeeStrategy {
calculate(samples: SolanaPriorityFeeResponse[]): number {
if (samples.length === 0) {
return 0;
}
let runningSumFees = 0;
for (let i = 0; i < samples.length; i++) {
runningSumFees += samples[i].prioritizationFee;
}
return runningSumFees / samples.length;
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/orderSubscriber/PollingSubscription.ts
|
import { OrderSubscriber } from './OrderSubscriber';
export class PollingSubscription {
private orderSubscriber: OrderSubscriber;
private frequency: number;
intervalId?: ReturnType<typeof setTimeout>;
constructor({
orderSubscriber,
frequency,
}: {
orderSubscriber: OrderSubscriber;
frequency: number;
}) {
this.orderSubscriber = orderSubscriber;
this.frequency = frequency;
}
public async subscribe(): Promise<void> {
if (this.intervalId) {
return;
}
this.intervalId = setInterval(
this.orderSubscriber.fetch.bind(this.orderSubscriber),
this.frequency
);
await this.orderSubscriber.fetch();
}
public async unsubscribe(): Promise<void> {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = undefined;
}
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/orderSubscriber/WebsocketSubscription.ts
|
import { OrderSubscriber } from './OrderSubscriber';
import { getNonIdleUserFilter, getUserFilter } from '../memcmp';
import { WebSocketProgramAccountSubscriber } from '../accounts/webSocketProgramAccountSubscriber';
import { UserAccount } from '../types';
import { Commitment, Context, PublicKey } from '@solana/web3.js';
import { ResubOpts } from '../accounts/types';
export class WebsocketSubscription {
private orderSubscriber: OrderSubscriber;
private commitment: Commitment;
private skipInitialLoad: boolean;
private resubOpts?: ResubOpts;
private resyncIntervalMs?: number;
private subscriber?: WebSocketProgramAccountSubscriber<UserAccount>;
private resyncTimeoutId?: NodeJS.Timeout;
private decoded?: boolean;
constructor({
orderSubscriber,
commitment,
skipInitialLoad = false,
resubOpts,
resyncIntervalMs,
decoded = true,
}: {
orderSubscriber: OrderSubscriber;
commitment: Commitment;
skipInitialLoad?: boolean;
resubOpts?: ResubOpts;
resyncIntervalMs?: number;
decoded?: boolean;
}) {
this.orderSubscriber = orderSubscriber;
this.commitment = commitment;
this.skipInitialLoad = skipInitialLoad;
this.resubOpts = resubOpts;
this.resyncIntervalMs = resyncIntervalMs;
this.decoded = decoded;
}
public async subscribe(): Promise<void> {
if (this.subscriber) {
return;
}
this.subscriber = new WebSocketProgramAccountSubscriber<UserAccount>(
'OrderSubscriber',
'User',
this.orderSubscriber.driftClient.program,
this.orderSubscriber.decodeFn,
{
filters: [getUserFilter(), getNonIdleUserFilter()],
commitment: this.commitment,
},
this.resubOpts
);
await this.subscriber.subscribe(
(
accountId: PublicKey,
account: UserAccount,
context: Context,
buffer: Buffer
) => {
const userKey = accountId.toBase58();
if (this.decoded ?? true) {
this.orderSubscriber.tryUpdateUserAccount(
userKey,
'decoded',
account,
context.slot
);
} else {
this.orderSubscriber.tryUpdateUserAccount(
userKey,
'buffer',
buffer,
context.slot
);
}
}
);
if (!this.skipInitialLoad) {
await this.orderSubscriber.fetch();
}
if (this.resyncIntervalMs) {
const recursiveResync = () => {
this.resyncTimeoutId = setTimeout(() => {
this.orderSubscriber
.fetch()
.catch((e) => {
console.error('Failed to resync in OrderSubscriber');
console.log(e);
})
.finally(() => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
if (!this.resyncTimeoutId) return;
recursiveResync();
});
}, this.resyncIntervalMs);
};
recursiveResync();
}
}
public async unsubscribe(): Promise<void> {
if (!this.subscriber) return;
await this.subscriber.unsubscribe();
this.subscriber = undefined;
if (this.resyncTimeoutId !== undefined) {
clearTimeout(this.resyncTimeoutId);
this.resyncTimeoutId = undefined;
}
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/orderSubscriber/types.ts
|
import { Commitment, PublicKey } from '@solana/web3.js';
import { Order, UserAccount } from '../types';
import { DriftClient } from '../driftClient';
import { GrpcConfigs } from '../accounts/types';
export type OrderSubscriberConfig = {
driftClient: DriftClient;
subscriptionConfig:
| {
type: 'polling';
frequency: number;
commitment?: Commitment;
}
| {
type: 'websocket';
skipInitialLoad?: boolean;
resubTimeoutMs?: number;
logResubMessages?: boolean;
resyncIntervalMs?: number;
commitment?: Commitment;
}
| {
type: 'grpc';
grpcConfigs: GrpcConfigs;
skipInitialLoad?: boolean;
resubTimeoutMs?: number;
logResubMessages?: boolean;
resyncIntervalMs?: number;
commitment?: Commitment;
};
fastDecode?: boolean;
decodeData?: boolean;
};
export interface OrderSubscriberEvents {
orderCreated: (
account: UserAccount,
updatedOrders: Order[],
pubkey: PublicKey,
slot: number,
dataType: 'raw' | 'decoded' | 'buffer'
) => void;
userUpdated: (
account: UserAccount,
pubkey: PublicKey,
slot: number,
dataType: 'raw' | 'decoded' | 'buffer'
) => void;
updateReceived: (
pubkey: PublicKey,
slot: number,
dataType: 'raw' | 'decoded' | 'buffer'
) => void;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/orderSubscriber/grpcSubscription.ts
|
import { Context, PublicKey } from '@solana/web3.js';
import { Buffer } from 'buffer';
import { grpcProgramAccountSubscriber } from '../accounts/grpcProgramAccountSubscriber';
import { OrderSubscriber } from './OrderSubscriber';
import { GrpcConfigs, ResubOpts } from '../accounts/types';
import { UserAccount } from '../types';
import { getUserFilter, getNonIdleUserFilter } from '../memcmp';
export class grpcSubscription {
private orderSubscriber: OrderSubscriber;
private skipInitialLoad: boolean;
private resubOpts?: ResubOpts;
private resyncIntervalMs?: number;
private subscriber?: grpcProgramAccountSubscriber<UserAccount>;
private resyncTimeoutId?: NodeJS.Timeout;
private decoded?: boolean;
private grpcConfigs: GrpcConfigs;
constructor({
grpcConfigs,
orderSubscriber,
skipInitialLoad = false,
resubOpts,
resyncIntervalMs,
decoded = true,
}: {
grpcConfigs: GrpcConfigs;
orderSubscriber: OrderSubscriber;
skipInitialLoad?: boolean;
resubOpts?: ResubOpts;
resyncIntervalMs?: number;
decoded?: boolean;
}) {
this.orderSubscriber = orderSubscriber;
this.skipInitialLoad = skipInitialLoad;
this.resubOpts = resubOpts;
this.resyncIntervalMs = resyncIntervalMs;
this.decoded = decoded;
this.grpcConfigs = grpcConfigs;
}
public async subscribe(): Promise<void> {
if (this.subscriber) {
return;
}
this.subscriber = new grpcProgramAccountSubscriber<UserAccount>(
this.grpcConfigs,
'OrderSubscriber',
'User',
this.orderSubscriber.driftClient.program,
this.orderSubscriber.decodeFn,
{
filters: [getUserFilter(), getNonIdleUserFilter()],
},
this.resubOpts
);
await this.subscriber.subscribe(
(
accountId: PublicKey,
account: UserAccount,
context: Context,
buffer: Buffer
) => {
const userKey = accountId.toBase58();
if (this.decoded ?? true) {
this.orderSubscriber.tryUpdateUserAccount(
userKey,
'decoded',
account,
context.slot
);
} else {
this.orderSubscriber.tryUpdateUserAccount(
userKey,
'buffer',
buffer,
context.slot
);
}
}
);
if (!this.skipInitialLoad) {
await this.orderSubscriber.fetch();
}
if (this.resyncIntervalMs) {
const recursiveResync = () => {
this.resyncTimeoutId = setTimeout(() => {
this.orderSubscriber
.fetch()
.catch((e) => {
console.error('Failed to resync in OrderSubscriber');
console.log(e);
})
.finally(() => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
if (!this.resyncTimeoutId) return;
recursiveResync();
});
}, this.resyncIntervalMs);
};
recursiveResync();
}
}
public async unsubscribe(): Promise<void> {
if (!this.subscriber) return;
await this.subscriber.unsubscribe();
this.subscriber = undefined;
if (this.resyncTimeoutId !== undefined) {
clearTimeout(this.resyncTimeoutId);
this.resyncTimeoutId = undefined;
}
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/orderSubscriber/index.ts
|
export * from './OrderSubscriber';
export * from './types';
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/orderSubscriber/OrderSubscriber.ts
|
import { DriftClient } from '../driftClient';
import { UserAccount } from '../types';
import { getUserFilter, getUserWithOrderFilter } from '../memcmp';
import { Commitment, PublicKey, RpcResponseAndContext } from '@solana/web3.js';
import { Buffer } from 'buffer';
import { DLOB } from '../dlob/DLOB';
import { OrderSubscriberConfig, OrderSubscriberEvents } from './types';
import { PollingSubscription } from './PollingSubscription';
import { WebsocketSubscription } from './WebsocketSubscription';
import StrictEventEmitter from 'strict-event-emitter-types';
import { EventEmitter } from 'events';
import { BN } from '../index';
import { decodeUser } from '../decode/user';
import { grpcSubscription } from './grpcSubscription';
import { isUserProtectedMaker } from '../math/userStatus';
export class OrderSubscriber {
driftClient: DriftClient;
usersAccounts = new Map<string, { slot: number; userAccount: UserAccount }>();
subscription: PollingSubscription | WebsocketSubscription | grpcSubscription;
commitment: Commitment;
eventEmitter: StrictEventEmitter<EventEmitter, OrderSubscriberEvents>;
fetchPromise?: Promise<void>;
fetchPromiseResolver: () => void;
mostRecentSlot: number;
decodeFn: (name: string, data: Buffer) => UserAccount;
decodeData?: boolean;
constructor(config: OrderSubscriberConfig) {
this.driftClient = config.driftClient;
this.commitment = config.subscriptionConfig.commitment || 'processed';
if (config.subscriptionConfig.type === 'polling') {
this.subscription = new PollingSubscription({
orderSubscriber: this,
frequency: config.subscriptionConfig.frequency,
});
} else if (config.subscriptionConfig.type === 'grpc') {
this.subscription = new grpcSubscription({
orderSubscriber: this,
grpcConfigs: config.subscriptionConfig.grpcConfigs,
skipInitialLoad: config.subscriptionConfig.skipInitialLoad,
resubOpts: {
resubTimeoutMs: config.subscriptionConfig?.resubTimeoutMs,
logResubMessages: config.subscriptionConfig?.logResubMessages,
},
resyncIntervalMs: config.subscriptionConfig.resyncIntervalMs,
decoded: config.decodeData,
});
} else {
this.subscription = new WebsocketSubscription({
orderSubscriber: this,
commitment: this.commitment,
skipInitialLoad: config.subscriptionConfig.skipInitialLoad,
resubOpts: {
resubTimeoutMs: config.subscriptionConfig?.resubTimeoutMs,
logResubMessages: config.subscriptionConfig?.logResubMessages,
},
resyncIntervalMs: config.subscriptionConfig.resyncIntervalMs,
decoded: config.decodeData,
});
}
if (config.fastDecode ?? true) {
this.decodeFn = (name, data) => decodeUser(data);
} else {
this.decodeFn =
this.driftClient.program.account.user.coder.accounts.decodeUnchecked.bind(
this.driftClient.program.account.user.coder.accounts
);
}
this.eventEmitter = new EventEmitter();
}
public async subscribe(): Promise<void> {
await this.subscription.subscribe();
}
async fetch(): Promise<void> {
if (this.fetchPromise) {
return this.fetchPromise;
}
this.fetchPromise = new Promise((resolver) => {
this.fetchPromiseResolver = resolver;
});
try {
const rpcRequestArgs = [
this.driftClient.program.programId.toBase58(),
{
commitment: this.commitment,
filters: [getUserFilter(), getUserWithOrderFilter()],
encoding: 'base64',
withContext: true,
},
];
const rpcJSONResponse: any =
// @ts-ignore
await this.driftClient.connection._rpcRequest(
'getProgramAccounts',
rpcRequestArgs
);
const rpcResponseAndContext: RpcResponseAndContext<
Array<{
pubkey: PublicKey;
account: {
data: [string, string];
};
}>
> = rpcJSONResponse.result;
const slot: number = rpcResponseAndContext.context.slot;
for (const programAccount of rpcResponseAndContext.value) {
const key = programAccount.pubkey.toString();
this.tryUpdateUserAccount(
key,
'raw',
programAccount.account.data,
slot
);
// give event loop a chance to breathe
await new Promise((resolve) => setTimeout(resolve, 0));
}
} catch (e) {
console.error(e);
} finally {
this.fetchPromiseResolver();
this.fetchPromise = undefined;
}
}
tryUpdateUserAccount(
key: string,
dataType: 'raw' | 'decoded' | 'buffer',
data: string[] | UserAccount | Buffer,
slot: number
): void {
if (!this.mostRecentSlot || slot > this.mostRecentSlot) {
this.mostRecentSlot = slot;
}
this.eventEmitter.emit(
'updateReceived',
new PublicKey(key),
slot,
dataType
);
const slotAndUserAccount = this.usersAccounts.get(key);
if (!slotAndUserAccount || slotAndUserAccount.slot <= slot) {
let userAccount: UserAccount;
// Polling leads to a lot of redundant decoding, so we only decode if data is from a fresh slot
if (dataType === 'raw') {
// @ts-ignore
const buffer = Buffer.from(data[0], data[1]);
const newLastActiveSlot = new BN(
buffer.subarray(4328, 4328 + 8),
undefined,
'le'
);
if (
slotAndUserAccount &&
slotAndUserAccount.userAccount.lastActiveSlot.gt(newLastActiveSlot)
) {
return;
}
userAccount = this.decodeFn('User', buffer) as UserAccount;
} else if (dataType === 'buffer') {
const buffer: Buffer = data as Buffer;
const newLastActiveSlot = new BN(
buffer.subarray(4328, 4328 + 8),
undefined,
'le'
);
if (
slotAndUserAccount &&
slotAndUserAccount.userAccount.lastActiveSlot.gt(newLastActiveSlot)
) {
return;
}
userAccount = this.decodeFn('User', data as Buffer) as UserAccount;
} else {
userAccount = data as UserAccount;
}
this.eventEmitter.emit(
'userUpdated',
userAccount,
new PublicKey(key),
slot,
dataType
);
const newOrders = userAccount.orders.filter(
(order) =>
order.slot.toNumber() > (slotAndUserAccount?.slot ?? 0) &&
order.slot.toNumber() <= slot
);
if (newOrders.length > 0) {
this.eventEmitter.emit(
'orderCreated',
userAccount,
newOrders,
new PublicKey(key),
slot,
dataType
);
}
this.usersAccounts.set(key, { slot, userAccount });
}
}
/**
* Creates a new DLOB for the order subscriber to fill. This will allow a
* caller to extend the DLOB Subscriber with a custom DLOB type.
* @returns New, empty DLOB object.
*/
protected createDLOB(): DLOB {
return new DLOB();
}
public async getDLOB(slot: number): Promise<DLOB> {
const dlob = this.createDLOB();
for (const [key, { userAccount }] of this.usersAccounts.entries()) {
const protectedMaker = isUserProtectedMaker(userAccount);
for (const order of userAccount.orders) {
dlob.insertOrder(order, key, slot, protectedMaker);
}
}
return dlob;
}
public getSlot(): number {
return this.mostRecentSlot ?? 0;
}
public async unsubscribe(): Promise<void> {
this.usersAccounts.clear();
await this.subscription.unsubscribe();
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/util/pythOracleUtils.ts
|
import {
SYSVAR_INSTRUCTIONS_PUBKEY,
TransactionInstruction,
Ed25519Program,
} from '@solana/web3.js';
export function trimFeedId(feedId: string): string {
if (feedId.startsWith('0x')) {
return feedId.slice(2);
}
return feedId;
}
export function getFeedIdUint8Array(feedId: string): Uint8Array {
const trimmedFeedId = trimFeedId(feedId);
return Uint8Array.from(Buffer.from(trimmedFeedId, 'hex'));
}
const SIGNATURE_LEN = 64;
const PUBKEY_LEN = 32;
const MAGIC_LEN = 4;
const MESSAGE_SIZE_LEN = 2;
export function getEd25519ArgsFromHex(hex: string): {
publicKey: Uint8Array;
signature: Uint8Array;
message: Uint8Array;
} {
const cleanedHex = hex.startsWith('0x') ? hex.slice(2) : hex;
const buffer = new Uint8Array(Buffer.from(cleanedHex, 'hex'));
const signatureOffset = MAGIC_LEN;
const publicKeyOffset = signatureOffset + SIGNATURE_LEN;
const messageDataSizeOffset = publicKeyOffset + PUBKEY_LEN;
const messageDataOffset = messageDataSizeOffset + MESSAGE_SIZE_LEN;
const signature = buffer.slice(
signatureOffset,
signatureOffset + SIGNATURE_LEN
);
const publicKey = buffer.slice(publicKeyOffset, publicKeyOffset + PUBKEY_LEN);
const messageSize =
buffer[messageDataSizeOffset] | (buffer[messageDataSizeOffset + 1] << 8);
const message = buffer.slice(
messageDataOffset,
messageDataOffset + messageSize
);
if (publicKey.length !== PUBKEY_LEN) {
throw new Error('Invalid public key length');
}
if (signature.length !== SIGNATURE_LEN) {
throw new Error('Invalid signature length');
}
return {
publicKey,
signature,
message,
};
}
/**
* Constructs a minimal Ed25519 verification instruction that references the data
* inside the main instruction (postPythLazerOracleUpdate).
*
* @param customInstructionIndex The index of the custom instruction in the transaction (typically 1 if this is second).
* @param messageOffset The offset within the custom instruction data where the pythMessage begins.
* @param customInstructionData The entire instruction data array for the custom instruction.
*/
export function createMinimalEd25519VerifyIx(
customInstructionIndex: number,
messageOffset: number,
customInstructionData: Uint8Array
): TransactionInstruction {
const signatureOffset = messageOffset + MAGIC_LEN;
const publicKeyOffset = signatureOffset + SIGNATURE_LEN;
const messageDataSizeOffset = publicKeyOffset + PUBKEY_LEN;
const messageDataOffset = messageDataSizeOffset + MESSAGE_SIZE_LEN;
if (messageDataOffset > customInstructionData.length) {
throw new Error('Not enough data in main instruction to read message size');
}
const messageSize =
customInstructionData[messageDataSizeOffset] |
(customInstructionData[messageDataSizeOffset + 1] << 8);
// Construct Ed25519SignatureOffsets
// struct Ed25519SignatureOffsets (14 bytes):
// u16 signature_offset
// u16 signature_instruction_index
// u16 public_key_offset
// u16 public_key_instruction_index
// u16 message_data_offset
// u16 message_data_size
// u16 message_instruction_index
const offsets = new Uint8Array(14);
const dv = new DataView(offsets.buffer);
let byteOffset = 0;
dv.setUint16(byteOffset, signatureOffset, true);
byteOffset += 2;
dv.setUint16(byteOffset, customInstructionIndex, true);
byteOffset += 2;
dv.setUint16(byteOffset, publicKeyOffset, true);
byteOffset += 2;
dv.setUint16(byteOffset, customInstructionIndex, true);
byteOffset += 2;
dv.setUint16(byteOffset, messageDataOffset, true);
byteOffset += 2;
dv.setUint16(byteOffset, messageSize, true);
byteOffset += 2;
dv.setUint16(byteOffset, customInstructionIndex, true);
byteOffset += 2;
const numSignatures = 1;
const padding = 0;
const ixData = new Uint8Array(2 + offsets.length);
ixData[0] = numSignatures;
ixData[1] = padding;
ixData.set(offsets, 2);
return new TransactionInstruction({
keys: [
{
pubkey: SYSVAR_INSTRUCTIONS_PUBKEY,
isSigner: false,
isWritable: false,
},
],
programId: Ed25519Program.programId,
data: Buffer.from(ixData),
});
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/util/computeUnits.ts
|
import {
ComputeBudgetProgram,
Connection,
Finality,
PublicKey,
TransactionInstruction,
} from '@solana/web3.js';
export async function findComputeUnitConsumption(
programId: PublicKey,
connection: Connection,
txSignature: string,
commitment: Finality = 'confirmed'
): Promise<number[]> {
const tx = await connection.getTransaction(txSignature, { commitment });
const computeUnits = [];
const regex = new RegExp(
`Program ${programId.toString()} consumed ([0-9]{0,6}) of ([0-9]{0,7}) compute units`
);
tx.meta.logMessages.forEach((logMessage) => {
const match = logMessage.match(regex);
if (match && match[1]) {
computeUnits.push(match[1]);
}
});
return computeUnits;
}
export function isSetComputeUnitsIx(ix: TransactionInstruction): boolean {
// Compute budget program discriminator is first byte
// 2: set compute unit limit
// 3: set compute unit price
if (
ix.programId.equals(ComputeBudgetProgram.programId) &&
// @ts-ignore
ix.data.at(0) === 2
) {
return true;
}
return false;
}
export function isSetComputeUnitPriceIx(ix: TransactionInstruction): boolean {
// Compute budget program discriminator is first byte
// 2: set compute unit limit
// 3: set compute unit price
if (
ix.programId.equals(ComputeBudgetProgram.programId) &&
// @ts-ignore
ix.data.at(0) === 3
) {
return true;
}
return false;
}
export function containsComputeUnitIxs(ixs: TransactionInstruction[]): {
hasSetComputeUnitLimitIx: boolean;
hasSetComputeUnitPriceIx: boolean;
} {
return {
hasSetComputeUnitLimitIx: ixs.some(isSetComputeUnitsIx),
hasSetComputeUnitPriceIx: ixs.some(isSetComputeUnitPriceIx),
};
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/util/chainClock.ts
|
import { Commitment } from '@solana/web3.js';
export type ChainClockProgress = {
blockHeight?: number;
slot?: number;
ts?: number;
};
export type ChainClockUpdateProps = {
commitment: Commitment;
} & ChainClockProgress;
export type ChainClockState = Map<Commitment, ChainClockProgress>;
export type ChainClickInitialisationProps = ChainClockUpdateProps[];
export class ChainClock {
private _state: ChainClockState;
constructor(props: ChainClickInitialisationProps) {
this._state = new Map<Commitment, ChainClockUpdateProps>();
props.forEach((prop) => {
this._state.set(prop.commitment, prop);
});
}
update(props: ChainClockUpdateProps): void {
const state = this._state.get(props.commitment);
if (state) {
if (props.blockHeight) state.blockHeight = props.blockHeight;
if (props.slot) state.slot = props.slot;
if (props.ts) state.ts = props.ts;
} else {
this._state.set(props.commitment, props);
}
}
public getState(commitment: Commitment): ChainClockProgress {
return this._state.get(commitment);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/util/promiseTimeout.ts
|
export function promiseTimeout<T>(
promise: Promise<T>,
timeoutMs: number
): Promise<T | null> {
let timeoutId: ReturnType<typeof setTimeout>;
const timeoutPromise: Promise<null> = new Promise((resolve) => {
timeoutId = setTimeout(() => resolve(null), timeoutMs);
});
return Promise.race([promise, timeoutPromise]).then((result: T | null) => {
clearTimeout(timeoutId);
return result;
});
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/util/TransactionConfirmationManager.ts
|
import {
ClientSubscriptionId,
Connection,
Context,
RpcResponseAndContext,
SignatureResult,
SignatureStatus,
TransactionConfirmationStatus,
} from '@solana/web3.js';
import { DEFAULT_CONFIRMATION_OPTS } from '../config';
import { TxSendError } from '..';
import { NOT_CONFIRMED_ERROR_CODE } from '../constants/txConstants';
import {
getTransactionErrorFromTxSig,
throwTransactionError,
} from '../tx/reportTransactionError';
import { promiseTimeout } from './promiseTimeout';
type ResolveReference = {
resolve?: () => void;
};
const confirmationStatusValues: Record<TransactionConfirmationStatus, number> =
{
processed: 0,
confirmed: 1,
finalized: 2,
};
interface TransactionConfirmationRequest {
txSig: string;
desiredConfirmationStatus: TransactionConfirmationStatus;
timeout: number;
pollInterval: number;
searchTransactionHistory: boolean;
startTime: number;
resolve: (status: SignatureStatus) => void;
reject: (error: Error) => void;
}
/**
* Class to await for transaction confirmations in an optimised manner. It tracks a shared list of all pending transactions and fetches them in bulk in a shared RPC request whenever they have an "overlapping" polling interval. E.g. tx1 with an interval of 200ms and tx2 with an interval of 300ms (if sent at the same time) will be fetched together at at 600ms, 1200ms, 1800ms, etc.
*/
export class TransactionConfirmationManager {
private connection: Connection;
private pendingConfirmations: Map<string, TransactionConfirmationRequest> =
new Map();
private intervalId: NodeJS.Timeout | null = null;
constructor(connection: Connection) {
this.connection = connection;
}
async confirmTransactionWebSocket(
txSig: string,
timeout = 30000,
desiredConfirmationStatus = DEFAULT_CONFIRMATION_OPTS.commitment as TransactionConfirmationStatus
): Promise<RpcResponseAndContext<SignatureResult>> {
const start = Date.now();
const subscriptionCommitment =
desiredConfirmationStatus || DEFAULT_CONFIRMATION_OPTS.commitment;
let response: RpcResponseAndContext<SignatureResult> | null = null;
let subscriptionId: ClientSubscriptionId;
const confirmationPromise = new Promise((resolve, reject) => {
try {
subscriptionId = this.connection.onSignature(
txSig,
(result: SignatureResult, context: Context) => {
response = {
context,
value: result,
};
resolve(null);
},
subscriptionCommitment
);
} catch (err) {
reject(err);
}
});
// We do a one-shot confirmation check just in case the transaction is ALREADY confirmed when we create the websocket confirmation .. We want to run this concurrently with the onSignature subscription. If this returns true then we can return early as the transaction has already been confirmed.
const oneShotConfirmationPromise = this.connection.getSignatureStatuses([
txSig,
]);
const resolveReference: ResolveReference = {};
// This is the promise we are waiting on to resolve the overall confirmation. It will resolve the faster of a positive oneShot confirmation, or the websocket confirmation, or the timeout.
const overallWaitingForConfirmationPromise = new Promise<void>(
(resolve) => {
resolveReference.resolve = resolve;
}
);
// Await for the one shot confirmation and resolve the waiting promise if we get a positive confirmation result
oneShotConfirmationPromise.then(
async (oneShotResponse) => {
if (!oneShotResponse || !oneShotResponse?.value?.[0]) return;
const resultValue = oneShotResponse.value[0];
if (resultValue.err) {
await throwTransactionError(txSig, this.connection);
}
if (
this.checkStatusMatchesDesiredConfirmationStatus(
resultValue,
desiredConfirmationStatus
)
) {
response = {
context: oneShotResponse.context,
value: oneShotResponse.value[0],
};
resolveReference.resolve?.();
}
},
(onRejected) => {
throw onRejected;
}
);
// Await for the websocket confirmation with the configured timeout
promiseTimeout(confirmationPromise, timeout).then(
() => {
resolveReference.resolve?.();
},
(onRejected) => {
throw onRejected;
}
);
try {
await overallWaitingForConfirmationPromise;
} finally {
if (subscriptionId !== undefined) {
this.connection.removeSignatureListener(subscriptionId);
}
}
const duration = (Date.now() - start) / 1000;
if (response === null) {
throw new TxSendError(
`Transaction was not confirmed in ${duration.toFixed(
2
)} seconds. It is unknown if it succeeded or failed. Check signature ${txSig} using the Solana Explorer or CLI tools.`,
NOT_CONFIRMED_ERROR_CODE
);
}
return response;
}
async confirmTransactionPolling(
txSig: string,
desiredConfirmationStatus = DEFAULT_CONFIRMATION_OPTS.commitment as TransactionConfirmationStatus,
timeout = 30000,
pollInterval = 1000,
searchTransactionHistory = false
): Promise<SignatureStatus> {
// Interval must be > 400ms and a multiple of 100ms
if (pollInterval < 400 || pollInterval % 100 !== 0) {
throw new Error(
'Transaction confirmation polling interval must be at least 400ms and a multiple of 100ms'
);
}
return new Promise((resolve, reject) => {
this.pendingConfirmations.set(txSig, {
txSig,
desiredConfirmationStatus,
timeout,
pollInterval,
searchTransactionHistory,
startTime: Date.now(),
resolve,
reject,
});
if (!this.intervalId) {
this.startConfirmationLoop();
}
});
}
private startConfirmationLoop() {
this.intervalId = setInterval(() => this.checkPendingConfirmations(), 100);
}
private async checkPendingConfirmations() {
const now = Date.now();
const transactionsToCheck: TransactionConfirmationRequest[] = [];
for (const [txSig, request] of this.pendingConfirmations.entries()) {
if (now - request.startTime >= request.timeout) {
request.reject(
new Error(
`Transaction confirmation timeout after ${request.timeout}ms`
)
);
this.pendingConfirmations.delete(txSig);
} else if ((now - request.startTime) % request.pollInterval < 100) {
transactionsToCheck.push(request);
}
}
if (transactionsToCheck.length > 0) {
await this.checkTransactionStatuses(transactionsToCheck);
}
if (this.pendingConfirmations.size === 0 && this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
private checkStatusMatchesDesiredConfirmationStatus(
status: SignatureStatus,
desiredConfirmationStatus: TransactionConfirmationStatus
): boolean {
if (
status.confirmationStatus &&
confirmationStatusValues[status.confirmationStatus] >=
confirmationStatusValues[desiredConfirmationStatus]
) {
return true;
}
return false;
}
private async checkTransactionStatuses(
requests: TransactionConfirmationRequest[]
) {
const txSigs = requests.map((request) => request.txSig);
const { value: statuses } = await this.connection.getSignatureStatuses(
txSigs,
{
searchTransactionHistory: requests.some(
(req) => req.searchTransactionHistory
),
}
);
if (!statuses || statuses.length !== txSigs.length) {
throw new Error('Failed to get signature statuses');
}
for (let i = 0; i < statuses.length; i++) {
const status = statuses[i];
const request = requests[i];
if (status === null) {
continue;
}
if (status.err) {
this.pendingConfirmations.delete(request.txSig);
request.reject(
await getTransactionErrorFromTxSig(request.txSig, this.connection)
);
continue;
}
if (
confirmationStatusValues[status.confirmationStatus] === undefined ||
confirmationStatusValues[request.desiredConfirmationStatus] ===
undefined
) {
throw new Error(
`Invalid confirmation status when awaiting confirmation: ${status.confirmationStatus}`
);
}
if (
this.checkStatusMatchesDesiredConfirmationStatus(
status,
request.desiredConfirmationStatus
)
) {
request.resolve(status);
this.pendingConfirmations.delete(request.txSig);
}
}
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/util/tps.ts
|
import { Connection, PublicKey } from '@solana/web3.js';
export async function estimateTps(
programId: PublicKey,
connection: Connection,
failed: boolean
): Promise<number> {
let signatures = await connection.getSignaturesForAddress(
programId,
undefined,
'finalized'
);
if (failed) {
signatures = signatures.filter((signature) => signature.err);
}
const numberOfSignatures = signatures.length;
if (numberOfSignatures === 0) {
return 0;
}
return (
numberOfSignatures /
(signatures[0].blockTime - signatures[numberOfSignatures - 1].blockTime)
);
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/util/digest.ts
|
import { createHash } from 'crypto';
export function digest(data: Buffer): Buffer {
const hash = createHash('sha256');
hash.update(data);
return hash.digest();
}
export function digestSignature(signature: Uint8Array): string {
return createHash('sha256').update(signature).digest('base64');
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/openbook/openbookV2Subscriber.ts
|
import { Connection, Keypair, PublicKey } from '@solana/web3.js';
import { BulkAccountLoader } from '../accounts/bulkAccountLoader';
import { PRICE_PRECISION } from '../constants/numericConstants';
import { AnchorProvider, BN, Idl, Program, Wallet } from '@coral-xyz/anchor';
import { L2Level, L2OrderBookGenerator } from '../dlob/orderBookLevels';
import { Market, OpenBookV2Client } from '@openbook-dex/openbook-v2';
import openbookV2Idl from '../idl/openbook.json';
export type OpenbookV2SubscriberConfig = {
connection: Connection;
programId: PublicKey;
marketAddress: PublicKey;
accountSubscription:
| {
// enables use to add web sockets in the future
type: 'polling';
accountLoader: BulkAccountLoader;
}
| {
type: 'websocket';
};
};
export class OpenbookV2Subscriber implements L2OrderBookGenerator {
connection: Connection;
programId: PublicKey;
marketAddress: PublicKey;
subscriptionType: 'polling' | 'websocket';
accountLoader: BulkAccountLoader | undefined;
subscribed: boolean;
market: Market;
marketCallbackId: string | number;
client: OpenBookV2Client;
public constructor(config: OpenbookV2SubscriberConfig) {
this.connection = config.connection;
this.programId = config.programId;
this.marketAddress = config.marketAddress;
this.subscribed = false;
if (config.accountSubscription.type === 'polling') {
this.subscriptionType = 'polling';
this.accountLoader = config.accountSubscription.accountLoader;
} else {
this.subscriptionType = 'websocket';
}
}
public async subscribe(): Promise<void> {
if (this.subscribed === true) {
return;
}
const anchorProvider = new AnchorProvider(
this.connection,
new Wallet(Keypair.generate()),
{}
);
const openbookV2Program = new Program(
openbookV2Idl as Idl,
this.programId,
anchorProvider
);
this.client = new OpenBookV2Client(anchorProvider);
const market = await Market.load(this.client, this.marketAddress);
this.market = await market.loadOrderBook();
if (this.subscriptionType === 'websocket') {
this.marketCallbackId = this.connection.onAccountChange(
this.marketAddress,
async (accountInfo, _) => {
const marketRaw = openbookV2Program.coder.accounts.decode(
'Market',
accountInfo.data
);
const market = new Market(this.client, this.marketAddress, marketRaw);
await market.loadOrderBook();
this.market = market;
}
);
} else {
this.marketCallbackId = await this.accountLoader.addAccount(
this.marketAddress,
async (buffer, _) => {
const marketRaw = openbookV2Program.coder.accounts.decode(
'Market',
buffer
);
const market = new Market(this.client, this.marketAddress, marketRaw);
await market.loadOrderBook();
this.market = market;
}
);
}
this.subscribed = true;
}
public getBestBid(): BN | undefined {
const bestBid = this.market.bids?.best();
if (bestBid === undefined) {
return undefined;
}
return new BN(Math.floor(bestBid.price * PRICE_PRECISION.toNumber()));
}
public getBestAsk(): BN | undefined {
const bestAsk = this.market.asks?.best();
if (bestAsk === undefined) {
return undefined;
}
return new BN(Math.floor(bestAsk.price * PRICE_PRECISION.toNumber()));
}
public getL2Bids(): Generator<L2Level> {
return this.getL2Levels('bids');
}
public getL2Asks(): Generator<L2Level> {
return this.getL2Levels('asks');
}
*getL2Levels(side: 'bids' | 'asks'): Generator<L2Level> {
const basePrecision = Math.ceil(
1 / this.market.baseNativeFactor.toNumber()
);
const pricePrecision = PRICE_PRECISION.toNumber();
const levels = side === 'bids' ? this.market.bids : this.market.asks;
for (const order of levels?.items()) {
const size = new BN(order.size * basePrecision);
const price = new BN(order.price * pricePrecision);
yield {
price,
size,
sources: {
openbook: size,
},
};
}
}
public async unsubscribe(): Promise<void> {
if (!this.subscribed) {
return;
}
if (this.subscriptionType === 'websocket') {
await this.connection.removeAccountChangeListener(
this.marketCallbackId as number
);
} else {
this.accountLoader.removeAccount(
this.marketAddress,
this.marketCallbackId as string
);
}
this.subscribed = false;
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/openbook/openbookV2FulfillmentConfigMap.ts
|
import { PublicKey } from '@solana/web3.js';
import { OpenbookV2FulfillmentConfigAccount } from '../types';
import { DriftClient } from '../driftClient';
export class OpenbookV2FulfillmentConfigMap {
driftClient: DriftClient;
map = new Map<number, OpenbookV2FulfillmentConfigAccount>();
public constructor(driftClient: DriftClient) {
this.driftClient = driftClient;
}
public async add(
marketIndex: number,
openbookV2MarketAddress: PublicKey
): Promise<void> {
const account = await this.driftClient.getOpenbookV2FulfillmentConfig(
openbookV2MarketAddress
);
this.map.set(marketIndex, account);
}
public get(
marketIndex: number
): OpenbookV2FulfillmentConfigAccount | undefined {
return this.map.get(marketIndex);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/isomorphic/grpc.browser.ts
|
// Export a function to create a new Client instance
export function createClient(..._args: any) {
throw new Error('Only available in node context');
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/isomorphic/grpc.node.ts
|
import Client from '@triton-one/yellowstone-grpc';
import {
SubscribeRequest,
SubscribeUpdate,
CommitmentLevel,
} from '@triton-one/yellowstone-grpc';
import { ClientDuplexStream, ChannelOptions } from '@grpc/grpc-js';
export {
ClientDuplexStream,
ChannelOptions,
SubscribeRequest,
SubscribeUpdate,
CommitmentLevel,
Client,
};
// Export a function to create a new Client instance
export function createClient(
...args: ConstructorParameters<typeof Client>
): Client {
return new Client(...args);
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/isomorphic/grpc.ts
|
export * from './grpc.node';
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/constants/spotMarkets.ts
|
import { PublicKey } from '@solana/web3.js';
import { BN, DriftEnv, OracleSource } from '../';
import {
QUOTE_PRECISION,
QUOTE_PRECISION_EXP,
LAMPORTS_EXP,
LAMPORTS_PRECISION,
SIX,
EIGHT,
NINE,
FIVE,
} from './numericConstants';
export type SpotMarketConfig = {
symbol: string;
marketIndex: number;
poolId: number;
oracle: PublicKey;
mint: PublicKey;
oracleSource: OracleSource;
precision: BN;
precisionExp: BN;
serumMarket?: PublicKey;
phoenixMarket?: PublicKey;
openbookMarket?: PublicKey;
launchTs?: number;
pythFeedId?: string;
};
export const WRAPPED_SOL_MINT = new PublicKey(
'So11111111111111111111111111111111111111112'
);
export const DevnetSpotMarkets: SpotMarketConfig[] = [
{
symbol: 'USDC',
marketIndex: 0,
poolId: 0,
oracle: new PublicKey('En8hkHLkRe9d9DraYmBTrus518BvmVH448YcvmrFM6Ce'),
oracleSource: OracleSource.PYTH_STABLE_COIN_PULL,
mint: new PublicKey('8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
pythFeedId:
'0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a',
},
{
symbol: 'SOL',
marketIndex: 1,
poolId: 0,
oracle: new PublicKey('BAtFj4kQttZRVep3UZS2aZRDixkGYgWsbqTBVDbnSsPF'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey(WRAPPED_SOL_MINT),
precision: LAMPORTS_PRECISION,
precisionExp: LAMPORTS_EXP,
serumMarket: new PublicKey('8N37SsnTu8RYxtjrV9SStjkkwVhmU8aCWhLvwduAPEKW'),
phoenixMarket: new PublicKey(
'78ehDnHgbkFxqXZwdFxa8HK7saX58GymeX2wNGdkqYLp'
),
pythFeedId:
'0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d',
},
{
symbol: 'BTC',
marketIndex: 2,
poolId: 0,
oracle: new PublicKey('486kr3pmFPfTsS4aZgcsQ7kS4i9rjMsYYZup6HQNSTT4'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('3BZPwbcqB5kKScF3TEXxwNfx5ipV13kbRVDvfVp5c6fv'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
serumMarket: new PublicKey('AGsmbVu3MS9u68GEYABWosQQCZwmLcBHu4pWEuBYH7Za'),
pythFeedId:
'0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43',
},
{
symbol: 'PYUSD',
marketIndex: 3,
poolId: 0,
oracle: new PublicKey('HpMoKp3TCd3QT4MWYUKk2zCBwmhr5Df45fB6wdxYqEeh'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('GLfF72ZCUnS6N9iDJw8kedHzd6WFVf3VbpwdKKy76FRk'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
pythFeedId:
'0xc1da1b73d7f01e7ddd54b3766cf7fcd644395ad14f70aa706ec5384c59e76692',
},
{
symbol: 'Bonk',
marketIndex: 4,
poolId: 0,
oracle: new PublicKey('GojbSnJuPdKDT1ZuHuAM5t9oz6bxTo1xhUKpTua2F72p'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('7SekVZDmKCCDgTP8m6Hk4CfexFSru9RkwDCczmcwcsP6'),
precision: new BN(10).pow(FIVE),
precisionExp: FIVE,
pythFeedId:
'0x72b021217ca3fe68922a19aaf990109cb9d84e9ad004b4d2025ad6f529314419',
},
{
symbol: 'JLP',
marketIndex: 5,
poolId: 1,
oracle: new PublicKey('5Mb11e5rt1Sp6A286B145E4TmgMzsM2UX9nCF2vas5bs'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('HGe9FejFyhWSx6zdvx2RjynX7rmoEXFiJiLU437NXemZ'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
pythFeedId:
'0xc811abc82b4bad1f9bd711a2773ccaa935b03ecef974236942cec5e0eb845a3a',
},
{
symbol: 'USDC',
marketIndex: 6,
poolId: 1,
oracle: new PublicKey('En8hkHLkRe9d9DraYmBTrus518BvmVH448YcvmrFM6Ce'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
pythFeedId:
'0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a',
},
];
export const MainnetSpotMarkets: SpotMarketConfig[] = [
{
symbol: 'USDC',
marketIndex: 0,
poolId: 0,
oracle: new PublicKey('En8hkHLkRe9d9DraYmBTrus518BvmVH448YcvmrFM6Ce'),
oracleSource: OracleSource.PYTH_STABLE_COIN_PULL,
mint: new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),
precision: QUOTE_PRECISION,
precisionExp: QUOTE_PRECISION_EXP,
pythFeedId:
'0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a',
},
{
symbol: 'SOL',
marketIndex: 1,
poolId: 0,
oracle: new PublicKey('BAtFj4kQttZRVep3UZS2aZRDixkGYgWsbqTBVDbnSsPF'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey(WRAPPED_SOL_MINT),
precision: LAMPORTS_PRECISION,
precisionExp: LAMPORTS_EXP,
serumMarket: new PublicKey('8BnEgHoWFysVcuFFX7QztDmzuH8r5ZFvyP3sYwn1XTh6'),
phoenixMarket: new PublicKey(
'4DoNfFBfF7UokCC2FQzriy7yHK6DY6NVdYpuekQ5pRgg'
),
openbookMarket: new PublicKey(
'AFgkED1FUVfBe2trPUDqSqK9QKd4stJrfzq5q1RwAFTa'
),
pythFeedId:
'0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d',
},
{
symbol: 'mSOL',
marketIndex: 2,
poolId: 0,
oracle: new PublicKey('FAq7hqjn7FWGXKDwJHzsXGgBcydGTcK4kziJpAGWXjDb'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So'),
precision: new BN(10).pow(NINE),
precisionExp: NINE,
serumMarket: new PublicKey('9Lyhks5bQQxb9EyyX55NtgKQzpM4WK7JCmeaWuQ5MoXD'),
pythFeedId:
'0xc2289a6a43d2ce91c6f55caec370f4acc38a2ed477f58813334c6d03749ff2a4',
},
{
symbol: 'wBTC',
marketIndex: 3,
poolId: 0,
oracle: new PublicKey('9Tq8iN5WnMX2PcZGj4iSFEAgHCi8cM6x8LsDUbuzq8uw'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh'),
precision: new BN(10).pow(EIGHT),
precisionExp: EIGHT,
serumMarket: new PublicKey('3BAKsQd3RuhZKES2DGysMhjBdwjZYKYmxRqnSMtZ4KSN'),
pythFeedId:
'0xc9d8b075a5c69303365ae23633d4e085199bf5c520a3b90fed1322a0342ffc33',
},
{
symbol: 'wETH',
marketIndex: 4,
poolId: 0,
oracle: new PublicKey('6bEp2MiyoiiiDxcVqE8rUHQWwHirXUXtKfAEATTVqNzT'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs'),
precision: new BN(10).pow(EIGHT),
precisionExp: EIGHT,
serumMarket: new PublicKey('BbJgE7HZMaDp5NTYvRh5jZSkQPVDTU8ubPFtpogUkEj4'),
phoenixMarket: new PublicKey(
'Ew3vFDdtdGrknJAVVfraxCA37uNJtimXYPY4QjnfhFHH'
),
openbookMarket: new PublicKey(
'AT1R2jUNb9iTo4EaRfKSTPiNTX4Jb64KSwnVmig6Hu4t'
),
pythFeedId:
'0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace',
},
{
symbol: 'USDT',
marketIndex: 5,
poolId: 0,
oracle: new PublicKey('BekJ3P5G3iFeC97sXHuKnUHofCFj9Sbo7uyF2fkKwvit'),
oracleSource: OracleSource.PYTH_STABLE_COIN_PULL,
mint: new PublicKey('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'),
precision: QUOTE_PRECISION,
precisionExp: QUOTE_PRECISION_EXP,
serumMarket: new PublicKey('B2na8Awyd7cpC59iEU43FagJAPLigr3AP3s38KM982bu'),
pythFeedId:
'0x2b89b9dc8fdf9f34709a5b106b472f0f39bb6ca9ce04b0fd7f2e971688e2e53b',
},
{
symbol: 'jitoSOL',
marketIndex: 6,
poolId: 0,
oracle: new PublicKey('9QE1P5EfzthYDgoQ9oPeTByCEKaRJeZbVVqKJfgU9iau'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn'),
precision: new BN(10).pow(NINE),
precisionExp: NINE,
serumMarket: new PublicKey('DkbVbMhFxswS32xnn1K2UY4aoBugXooBTxdzkWWDWRkH'),
phoenixMarket: new PublicKey(
'5LQLfGtqcC5rm2WuGxJf4tjqYmDjsQAbKo2AMLQ8KB7p'
),
pythFeedId:
'0x67be9f519b95cf24338801051f9a808eff0a578ccb388db73b7f6fe1de019ffb',
},
{
symbol: 'PYTH',
marketIndex: 7,
poolId: 0,
oracle: new PublicKey('GqkCu7CbsPVz1H6W6AAHuReqbJckYG59TXz7Y5HDV7hr'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('HZ1JovNiVvGrGNiiYvEozEVgZ58xaU3RKwX8eACQBCt3'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
serumMarket: new PublicKey('4E17F3BxtNVqzVsirxguuqkpYLtFgCR6NfTpccPh82WE'),
phoenixMarket: new PublicKey(
'2sTMN9A1D1qeZLF95XQgJCUPiKe5DiV52jLfZGqMP46m'
),
pythFeedId:
'0x0bbf28e9a841a1cc788f6a361b17ca072d0ea3098a1e5df1c3922d06719579ff',
},
{
symbol: 'bSOL',
marketIndex: 8,
poolId: 0,
oracle: new PublicKey('BmDWPMsytWmYkh9n6o7m79eVshVYf2B5GVaqQ2EWKnGH'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('bSo13r4TkiE4KumL71LsHTPpL2euBYLFx6h9HP3piy1'),
precision: new BN(10).pow(NINE),
precisionExp: NINE,
serumMarket: new PublicKey('ARjaHVxGCQfTvvKjLd7U7srvk6orthZSE6uqWchCczZc'),
pythFeedId:
'0x89875379e70f8fbadc17aef315adf3a8d5d160b811435537e03c97e8aac97d9c',
},
{
symbol: 'JTO',
marketIndex: 9,
poolId: 0,
oracle: new PublicKey('Ffq6ACJ17NAgaxC6ocfMzVXL3K61qxB2xHg6WUawWPfP'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('jtojtomepa8beP8AuQc6eXt5FriJwfFMwQx2v2f9mCL'),
precision: new BN(10).pow(NINE),
precisionExp: NINE,
serumMarket: new PublicKey('H87FfmHABiZLRGrDsXRZtqq25YpARzaokCzL1vMYGiep'),
phoenixMarket: new PublicKey(
'BRLLmdtPGuuFn3BU6orYw4KHaohAEptBToi3dwRUnHQZ'
),
pythFeedId:
'0xb43660a5f790c69354b0729a5ef9d50d68f1df92107540210b9cccba1f947cc2',
},
{
symbol: 'WIF',
marketIndex: 10,
poolId: 0,
oracle: new PublicKey('6x6KfE7nY2xoLCRSMPT1u83wQ5fpGXoKNBqFjrCwzsCQ'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
serumMarket: new PublicKey('2BtDHBTCTUxvdur498ZEcMgimasaFrY5GzLv8wS8XgCb'),
phoenixMarket: new PublicKey(
'6ojSigXF7nDPyhFRgmn3V9ywhYseKF9J32ZrranMGVSX'
),
openbookMarket: new PublicKey(
'CwGmEwYFo7u5D7vghGwtcCbRToWosytaZa3Ys3JAto6J'
),
pythFeedId:
'0x4ca4beeca86f0d164160323817a4e42b10010a724c2217c6ee41b54cd4cc61fc',
},
{
symbol: 'JUP',
marketIndex: 11,
poolId: 0,
oracle: new PublicKey('AwqRpfJ36jnSZQykyL1jYY35mhMteeEAjh7o8LveRQin'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
phoenixMarket: new PublicKey(
'2pspvjWWaf3dNgt3jsgSzFCNvMGPb7t8FrEYvLGjvcCe'
),
launchTs: 1706731200000,
pythFeedId:
'0x0a0408d619e9380abad35060f9192039ed5042fa6f82301d0e48bb52be830996',
},
{
symbol: 'RENDER',
marketIndex: 12,
poolId: 0,
oracle: new PublicKey('8TQztfGcNjHGRusX4ejQQtPZs3Ypczt9jWF6pkgQMqUX'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('rndrizKT3MK1iimdxRdWabcF7Zg7AR5T4nud4EkHBof'),
precision: new BN(10).pow(EIGHT),
precisionExp: EIGHT,
serumMarket: new PublicKey('2m7ZLEKtxWF29727DSb5D91erpXPUY1bqhRWRC3wQX7u'),
launchTs: 1708964021000,
pythFeedId:
'0x3d4a2bd9535be6ce8059d75eadeba507b043257321aa544717c56fa19b49e35d',
},
{
symbol: 'W',
marketIndex: 13,
poolId: 0,
oracle: new PublicKey('4HbitGsdcFbtFotmYscikQFAAKJ3nYx4t7sV7fTvsk8U'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('85VBFQZC9TZkfaptBWjvUw7YbZjy52A6mjtPGjstQAmQ'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
phoenixMarket: new PublicKey(
'8dFTCTAbtGuHsdDL8WEPrTU6pXFDrU1QSjBTutw8fwZk'
),
launchTs: 1712149014000,
pythFeedId:
'0xeff7446475e218517566ea99e72a4abec2e1bd8498b43b7d8331e29dcb059389',
},
{
symbol: 'TNSR',
marketIndex: 14,
poolId: 0,
oracle: new PublicKey('13jpjpVyU5hGpjsZ4HzCcmBo85wze4N8Au7U6cC3GMip'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('TNSRxcUxoT9xBG3de7PiJyTDYu7kskLqcpddxnEJAS6'),
precision: new BN(10).pow(NINE),
precisionExp: NINE,
phoenixMarket: new PublicKey(
'AbJCZ9TAJiby5AY3cHcXS2gUdENC6mtsm6m7XpC2ZMvE'
),
launchTs: 1712593532000,
pythFeedId:
'0x05ecd4597cd48fe13d6cc3596c62af4f9675aee06e2e0b94c06d8bee2b659e05',
},
{
symbol: 'DRIFT',
marketIndex: 15,
poolId: 0,
oracle: new PublicKey('23KmX7SNikmUr2axSCy6Zer7XPBnvmVcASALnDGqBVRR'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('DriFtupJYLTosbwoN8koMbEYSx54aFAVLddWsbksjwg7'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
phoenixMarket: new PublicKey(
'8BV6rrWsUabnTDA3dE6A69oUDJAj3hMhtBHTJyXB7czp'
),
launchTs: 1715860800000,
pythFeedId:
'0x5c1690b27bb02446db17cdda13ccc2c1d609ad6d2ef5bf4983a85ea8b6f19d07',
},
{
symbol: 'INF',
marketIndex: 16,
poolId: 0,
oracle: new PublicKey('B7RUYg2zF6UdUSHv2RmpnriPVJccYWojgFydNS1NY5F8'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('5oVNBeEEQvYi1cX3ir8Dx5n1P7pdxydbGF2X4TxVusJm'),
precision: new BN(10).pow(NINE),
precisionExp: NINE,
launchTs: 1716595200000,
pythFeedId:
'0xf51570985c642c49c2d6e50156390fdba80bb6d5f7fa389d2f012ced4f7d208f',
},
{
symbol: 'dSOL',
marketIndex: 17,
poolId: 0,
oracle: new PublicKey('7QJ6e57t3yM8HYVg6bAnJiCiZ3wQQ5CSVsa6GA16nJuK'),
oracleSource: OracleSource.SWITCHBOARD_ON_DEMAND,
mint: new PublicKey('Dso1bDeDjCQxTrWHqUUi63oBvV7Mdm6WaobLbQ7gnPQ'),
precision: new BN(10).pow(NINE),
precisionExp: NINE,
launchTs: 1716595200000,
},
{
symbol: 'USDY',
marketIndex: 18,
poolId: 0,
oracle: new PublicKey('BPTQgHV4y2x4jvKPPkkd9aS8jY7L3DGZBwjEZC8Vm27o'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('A1KLoBrKBde8Ty9qtNQUtq3C2ortoC3u7twggz7sEto6'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
launchTs: 1718811089000,
pythFeedId:
'0xe393449f6aff8a4b6d3e1165a7c9ebec103685f3b41e60db4277b5b6d10e7326',
},
{
symbol: 'JLP',
marketIndex: 19,
poolId: 0,
oracle: new PublicKey('5Mb11e5rt1Sp6A286B145E4TmgMzsM2UX9nCF2vas5bs'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('27G8MtK7VtTcCHkpASjSDdkWWYfoqT6ggEuKidVJidD4'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
launchTs: 1719415157000,
pythFeedId:
'0xc811abc82b4bad1f9bd711a2773ccaa935b03ecef974236942cec5e0eb845a3a',
},
{
symbol: 'POPCAT',
marketIndex: 20,
poolId: 0,
oracle: new PublicKey('H3pn43tkNvsG5z3qzmERguSvKoyHZvvY6VPmNrJqiW5X'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr'),
precision: new BN(10).pow(NINE),
precisionExp: NINE,
launchTs: 1720013054000,
phoenixMarket: new PublicKey(
'31XgvAQ1HgFQEk31KdszbPkVXKaQqB1bgYZPoDrFpSR2'
),
pythFeedId:
'0xb9312a7ee50e189ef045aa3c7842e099b061bd9bdc99ac645956c3b660dc8cce',
},
{
symbol: 'CLOUD',
marketIndex: 21,
poolId: 0,
oracle: new PublicKey('FNFejcXENaPgKaCTfstew9vSSvdQPnXjGTkJjUnnYvHU'),
oracleSource: OracleSource.SWITCHBOARD_ON_DEMAND,
mint: new PublicKey('CLoUDKc4Ane7HeQcPpE3YHnznRxhMimJ4MyaUqyHFzAu'),
precision: new BN(10).pow(NINE),
precisionExp: NINE,
launchTs: 1721316817000,
},
{
symbol: 'PYUSD',
marketIndex: 22,
poolId: 0,
oracle: new PublicKey('HpMoKp3TCd3QT4MWYUKk2zCBwmhr5Df45fB6wdxYqEeh'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
pythFeedId:
'0xc1da1b73d7f01e7ddd54b3766cf7fcd644395ad14f70aa706ec5384c59e76692',
},
{
symbol: 'USDe',
marketIndex: 23,
poolId: 0,
oracle: new PublicKey('BXej5boX2nWudwAfZQedo212B9XJxhjTeeF3GbCwXmYa'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('DEkqHyPN7GMRJ5cArtQFAWefqbZb33Hyf6s5iCwjEonT'),
precision: new BN(10).pow(NINE),
precisionExp: NINE,
pythFeedId:
'0x6ec879b1e9963de5ee97e9c8710b742d6228252a5e2ca12d4ae81d7fe5ee8c5d',
},
{
symbol: 'sUSDe',
marketIndex: 24,
poolId: 0,
oracle: new PublicKey('BRuNuzLAPHHGSSVAJPKMcmJMdgDfrekvnSxkxPDGdeqp'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('Eh6XEPhSwoLv5wFApukmnaVSHQ6sAnoD9BmgmwQoN2sN'),
precision: new BN(10).pow(NINE),
precisionExp: NINE,
pythFeedId:
'0xca3ba9a619a4b3755c10ac7d5e760275aa95e9823d38a84fedd416856cdba37c',
},
{
symbol: 'BNSOL',
marketIndex: 25,
poolId: 0,
oracle: new PublicKey('8DmXTfhhtb9kTcpTVfb6Ygx8WhZ8wexGqcpxfn23zooe'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('BNso1VUJnh4zcfpZa6986Ea66P6TCp59hvtNJ8b1X85'),
precision: LAMPORTS_PRECISION,
precisionExp: LAMPORTS_EXP,
pythFeedId:
'0x55f8289be7450f1ae564dd9798e49e7d797d89adbc54fe4f8c906b1fcb94b0c3',
},
{
symbol: 'MOTHER',
marketIndex: 26,
poolId: 0,
oracle: new PublicKey('56ap2coZG7FPWUigVm9XrpQs3xuCwnwQaWtjWZcffEUG'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('3S8qX1MsMqRbiwKg2cQyx7nis1oHMgaCuc9c4VfvVdPN'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
pythFeedId:
'0x62742a997d01f7524f791fdb2dd43aaf0e567d765ebf8fd0406a994239e874d4',
},
{
symbol: 'cbBTC',
marketIndex: 27,
poolId: 0,
oracle: new PublicKey('486kr3pmFPfTsS4aZgcsQ7kS4i9rjMsYYZup6HQNSTT4'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('cbbtcf3aa214zXHbiAZQwf4122FBYbraNdFqgw4iMij'),
precision: new BN(10).pow(EIGHT),
precisionExp: EIGHT,
openbookMarket: new PublicKey(
'2HXgKaXKsMUEzQaSBZiXSd54eMHaS3roiefyGWtkW97W'
),
pythFeedId:
'0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43',
},
{
symbol: 'USDS',
marketIndex: 28,
poolId: 0,
oracle: new PublicKey('7pT9mxKXyvfaZKeKy1oe2oV2K1RFtF7tPEJHUY3h2vVV'),
oracleSource: OracleSource.PYTH_STABLE_COIN_PULL,
mint: new PublicKey('USDSwr9ApdHk5bvJKMjzff41FfuX8bSxdKcR81vTwcA'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
pythFeedId:
'0x77f0971af11cc8bac224917275c1bf55f2319ed5c654a1ca955c82fa2d297ea1',
},
{
symbol: 'META',
marketIndex: 29,
poolId: 0,
oracle: new PublicKey('DwYF1yveo8XTF1oqfsqykj332rjSxAd7bR6Gu6i4iUET'),
oracleSource: OracleSource.SWITCHBOARD_ON_DEMAND,
mint: new PublicKey('METADDFL6wWMWEoKTFJwcThTbUmtarRJZjRpzUvkxhr'),
precision: new BN(10).pow(NINE),
precisionExp: NINE,
},
{
symbol: 'ME',
marketIndex: 30,
poolId: 0,
oracle: new PublicKey('FLQjrmEPGwbCKRYZ1eYM5FPccHBrCv2cN4GBu3mWfmPH'),
oracleSource: OracleSource.PYTH_PULL,
mint: new PublicKey('MEFNBXixkEbait3xn9bkm8WsJzXtVsaJEn4c8Sam21u'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
pythFeedId:
'0x91519e3e48571e1232a85a938e714da19fe5ce05107f3eebb8a870b2e8020169',
},
];
export const SpotMarkets: { [key in DriftEnv]: SpotMarketConfig[] } = {
devnet: DevnetSpotMarkets,
'mainnet-beta': MainnetSpotMarkets,
};
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/constants/txConstants.ts
|
export const NOT_CONFIRMED_ERROR_CODE = -1001;
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/constants/numericConstants.ts
|
import { LAMPORTS_PER_SOL } from '@solana/web3.js';
import { BN } from '../';
export const ZERO = new BN(0);
export const ONE = new BN(1);
export const TWO = new BN(2);
export const THREE = new BN(3);
export const FOUR = new BN(4);
export const FIVE = new BN(5);
export const SIX = new BN(6);
export const SEVEN = new BN(7);
export const EIGHT = new BN(8);
export const NINE = new BN(9);
export const TEN = new BN(10);
export const TEN_THOUSAND = new BN(10000);
export const BN_MAX = new BN(Number.MAX_SAFE_INTEGER);
export const TEN_MILLION = TEN_THOUSAND.mul(TEN_THOUSAND);
export const MAX_LEVERAGE = new BN(5);
export const MAX_LEVERAGE_ORDER_SIZE = new BN('18446744073709551615');
export const PERCENTAGE_PRECISION_EXP = new BN(6);
export const PERCENTAGE_PRECISION = new BN(10).pow(PERCENTAGE_PRECISION_EXP);
export const CONCENTRATION_PRECISION = PERCENTAGE_PRECISION;
export const QUOTE_PRECISION_EXP = new BN(6);
export const FUNDING_RATE_BUFFER_PRECISION_EXP = new BN(3);
export const PRICE_PRECISION_EXP = new BN(6);
export const FUNDING_RATE_PRECISION_EXP = PRICE_PRECISION_EXP.add(
FUNDING_RATE_BUFFER_PRECISION_EXP
);
export const PEG_PRECISION_EXP = new BN(6);
export const AMM_RESERVE_PRECISION_EXP = new BN(9);
export const SPOT_MARKET_RATE_PRECISION_EXP = new BN(6);
export const SPOT_MARKET_RATE_PRECISION = new BN(10).pow(
SPOT_MARKET_RATE_PRECISION_EXP
);
export const SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION_EXP = new BN(10);
export const SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION = new BN(10).pow(
SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION_EXP
);
export const SPOT_MARKET_UTILIZATION_PRECISION_EXP = new BN(6);
export const SPOT_MARKET_UTILIZATION_PRECISION = new BN(10).pow(
SPOT_MARKET_UTILIZATION_PRECISION_EXP
);
export const SPOT_MARKET_WEIGHT_PRECISION = new BN(10000);
export const SPOT_MARKET_BALANCE_PRECISION_EXP = new BN(9);
export const SPOT_MARKET_BALANCE_PRECISION = new BN(10).pow(
SPOT_MARKET_BALANCE_PRECISION_EXP
);
export const SPOT_MARKET_IMF_PRECISION_EXP = new BN(6);
export const SPOT_MARKET_IMF_PRECISION = new BN(10).pow(
SPOT_MARKET_IMF_PRECISION_EXP
);
export const LIQUIDATION_FEE_PRECISION = new BN(1000000);
export const QUOTE_PRECISION = new BN(10).pow(QUOTE_PRECISION_EXP);
export const PRICE_PRECISION = new BN(10).pow(PRICE_PRECISION_EXP);
export const FUNDING_RATE_PRECISION = new BN(10).pow(
FUNDING_RATE_PRECISION_EXP
);
export const FUNDING_RATE_BUFFER_PRECISION = new BN(10).pow(
FUNDING_RATE_BUFFER_PRECISION_EXP
);
export const PEG_PRECISION = new BN(10).pow(PEG_PRECISION_EXP);
export const AMM_RESERVE_PRECISION = new BN(10).pow(AMM_RESERVE_PRECISION_EXP);
export const BASE_PRECISION = AMM_RESERVE_PRECISION;
export const BASE_PRECISION_EXP = AMM_RESERVE_PRECISION_EXP;
export const AMM_TO_QUOTE_PRECISION_RATIO =
AMM_RESERVE_PRECISION.div(QUOTE_PRECISION); // 10^3
export const PRICE_DIV_PEG = PRICE_PRECISION.div(PEG_PRECISION); //10^1
export const PRICE_TO_QUOTE_PRECISION = PRICE_PRECISION.div(QUOTE_PRECISION); // 10^1
export const AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO =
AMM_RESERVE_PRECISION.mul(PEG_PRECISION).div(QUOTE_PRECISION); // 10^9
export const MARGIN_PRECISION = TEN_THOUSAND;
export const BID_ASK_SPREAD_PRECISION = new BN(1000000); // 10^6
export const LIQUIDATION_PCT_PRECISION = TEN_THOUSAND;
export const FUNDING_RATE_OFFSET_DENOMINATOR = new BN(5000);
export const FIVE_MINUTE = new BN(60 * 5);
export const ONE_HOUR = new BN(60 * 60);
export const ONE_YEAR = new BN(31536000);
export const QUOTE_SPOT_MARKET_INDEX = 0;
export const GOV_SPOT_MARKET_INDEX = 15;
export const LAMPORTS_PRECISION = new BN(LAMPORTS_PER_SOL);
export const LAMPORTS_EXP = new BN(Math.log10(LAMPORTS_PER_SOL));
export const OPEN_ORDER_MARGIN_REQUIREMENT = QUOTE_PRECISION.div(new BN(100));
export const DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT = new BN(
-25
).mul(QUOTE_PRECISION);
export const ACCOUNT_AGE_DELETION_CUTOFF_SECONDS = 60 * 60 * 24 * 13; // 13 days
export const IDLE_TIME_SLOTS = 9000;
export const SLOT_TIME_ESTIMATE_MS = 400;
export const DUST_POSITION_SIZE = QUOTE_PRECISION.divn(100); // Dust position is any position smaller than 1c
export const FUEL_WINDOW = new BN(60 * 60 * 24 * 28); // 28 days
export const FUEL_START_TS = new BN(1723147200); // unix timestamp
export const MAX_PREDICTION_PRICE = PRICE_PRECISION;
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/constants/perpMarkets.ts
|
import { OracleSource } from '../';
import { DriftEnv } from '../';
import { PublicKey } from '@solana/web3.js';
export type PerpMarketConfig = {
fullName?: string;
category?: string[];
symbol: string;
baseAssetSymbol: string;
marketIndex: number;
launchTs: number;
oracle: PublicKey;
oracleSource: OracleSource;
pythFeedId?: string;
};
export const DevnetPerpMarkets: PerpMarketConfig[] = [
{
fullName: 'Solana',
category: ['L1', 'Infra'],
symbol: 'SOL-PERP',
baseAssetSymbol: 'SOL',
marketIndex: 0,
oracle: new PublicKey('BAtFj4kQttZRVep3UZS2aZRDixkGYgWsbqTBVDbnSsPF'),
launchTs: 1655751353000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d',
},
{
fullName: 'Bitcoin',
category: ['L1', 'Payment'],
symbol: 'BTC-PERP',
baseAssetSymbol: 'BTC',
marketIndex: 1,
oracle: new PublicKey('486kr3pmFPfTsS4aZgcsQ7kS4i9rjMsYYZup6HQNSTT4'),
launchTs: 1655751353000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43',
},
{
fullName: 'Ethereum',
category: ['L1', 'Infra'],
symbol: 'ETH-PERP',
baseAssetSymbol: 'ETH',
marketIndex: 2,
oracle: new PublicKey('6bEp2MiyoiiiDxcVqE8rUHQWwHirXUXtKfAEATTVqNzT'),
launchTs: 1637691133472,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace',
},
{
fullName: 'Aptos',
category: ['L1', 'Infra'],
symbol: 'APT-PERP',
baseAssetSymbol: 'APT',
marketIndex: 3,
oracle: new PublicKey('79EWaCYU9jiQN8SbvVzGFAhAncUZYp3PjNg7KxmN5cLE'),
launchTs: 1675610186000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x03ae4db29ed4ae33d323568895aa00337e658e348b37509f5372ae51f0af00d5',
},
{
fullName: 'Bonk',
category: ['Meme', 'Dog'],
symbol: '1MBONK-PERP',
baseAssetSymbol: '1MBONK',
marketIndex: 4,
oracle: new PublicKey('GojbSnJuPdKDT1ZuHuAM5t9oz6bxTo1xhUKpTua2F72p'),
launchTs: 1677068931000,
oracleSource: OracleSource.PYTH_1M_PULL,
pythFeedId:
'0x72b021217ca3fe68922a19aaf990109cb9d84e9ad004b4d2025ad6f529314419',
},
{
fullName: 'Polygon',
category: ['L2', 'Infra'],
symbol: 'POL-PERP',
baseAssetSymbol: 'POL',
marketIndex: 5,
oracle: new PublicKey('BrzyDgwELy4jjjsqLQpBeUxzrsueYyMhuWpYBaUYcXvi'),
launchTs: 1677690149000, //todo
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xffd11c5a1cfd42f80afb2df4d9f264c15f956d68153335374ec10722edd70472',
},
{
fullName: 'Arbitrum',
category: ['L2', 'Infra'],
symbol: 'ARB-PERP',
baseAssetSymbol: 'ARB',
marketIndex: 6,
oracle: new PublicKey('8ocfAdqVRnzvfdubQaTxar4Kz5HJhNbPNmkLxswqiHUD'),
launchTs: 1679501812000, //todo
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x3fa4252848f9f0a1480be62745a4629d9eb1322aebab8a791e344b3b9c1adcf5',
},
{
fullName: 'Doge',
category: ['Meme', 'Dog'],
symbol: 'DOGE-PERP',
baseAssetSymbol: 'DOGE',
marketIndex: 7,
oracle: new PublicKey('23y63pHVwKfYSCDFdiGRaGbTYWoyr8UzhUE7zukyf6gK'),
launchTs: 1680808053000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xdcef50dd0a4cd2dcc17e45df1676dcb336a11a61c69df7a0299b0150c672d25c',
},
{
fullName: 'Binance Coin',
category: ['Exchange'],
symbol: 'BNB-PERP',
baseAssetSymbol: 'BNB',
marketIndex: 8,
oracle: new PublicKey('Dk8eWjuQHMbxJAwB9Sg7pXQPH4kgbg8qZGcUrWcD9gTm'),
launchTs: 1680808053000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x2f95862b045670cd22bee3114c39763a4a08beeb663b145d283c31d7d1101c4f',
},
{
fullName: 'Sui',
category: ['L1'],
symbol: 'SUI-PERP',
baseAssetSymbol: 'SUI',
marketIndex: 9,
oracle: new PublicKey('HBordkz5YxjzNURmKUY4vfEYFG9fZyZNeNF1VDLMoemT'),
launchTs: 1683125906000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744',
},
{
fullName: 'Pepe',
category: ['Meme'],
symbol: '1MPEPE-PERP',
baseAssetSymbol: '1MPEPE',
marketIndex: 10,
oracle: new PublicKey('CLxofhtzvLiErpn25wvUzpZXEqBhuZ6WMEckEraxyuGt'),
launchTs: 1683781239000,
oracleSource: OracleSource.PYTH_1M_PULL,
pythFeedId:
'0xd69731a2e74ac1ce884fc3890f7ee324b6deb66147055249568869ed700882e4',
},
{
fullName: 'OP',
category: ['L2', 'Infra'],
symbol: 'OP-PERP',
baseAssetSymbol: 'OP',
marketIndex: 11,
oracle: new PublicKey('C9Zi2Y3Mt6Zt6pcFvobN3N29HcrzKujPAPBDDTDRcUa2'),
launchTs: 1686091480000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x385f64d993f7b77d8182ed5003d97c60aa3361f3cecfe711544d2d59165e9bdf',
},
{
fullName: 'RENDER',
category: ['Infra'],
symbol: 'RENDER-PERP',
baseAssetSymbol: 'RENDER',
marketIndex: 12,
oracle: new PublicKey('8TQztfGcNjHGRusX4ejQQtPZs3Ypczt9jWF6pkgQMqUX'),
launchTs: 1687201081000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x3d4a2bd9535be6ce8059d75eadeba507b043257321aa544717c56fa19b49e35d',
},
{
fullName: 'XRP',
category: ['Payments'],
symbol: 'XRP-PERP',
baseAssetSymbol: 'XRP',
marketIndex: 13,
oracle: new PublicKey('9757epAjXWCWQH98kyK9vzgehd1XDVEf7joNHUaKk3iV'),
launchTs: 1689270550000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xec5d399846a9209f3fe5881d70aae9268c94339ff9817e8d18ff19fa05eea1c8',
},
{
fullName: 'HNT',
category: ['IoT'],
symbol: 'HNT-PERP',
baseAssetSymbol: 'HNT',
marketIndex: 14,
oracle: new PublicKey('9b1rcK9RUPK2vAqwNYCYEG34gUVpS2WGs2YCZZy2X5Tb'),
launchTs: 1692294955000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x649fdd7ec08e8e2a20f425729854e90293dcbe2376abc47197a14da6ff339756',
},
{
fullName: 'INJ',
category: ['L1', 'Exchange'],
symbol: 'INJ-PERP',
baseAssetSymbol: 'INJ',
marketIndex: 15,
oracle: new PublicKey('BfXcyDWJmYADa5eZD7gySSDd6giqgjvm7xsAhQ239SUD'),
launchTs: 1698074659000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x7a5bc1d2b56ad029048cd63964b3ad2776eadf812edc1a43a31406cb54bff592',
},
{
fullName: 'LINK',
category: ['Oracle'],
symbol: 'LINK-PERP',
baseAssetSymbol: 'LINK',
marketIndex: 16,
oracle: new PublicKey('Gwvob7yoLMgQRVWjScCRyQFMsgpRKrSAYisYEyjDJwEp'),
launchTs: 1698074659000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x8ac0c70fff57e9aefdf5edf44b51d62c2d433653cbb2cf5cc06bb115af04d221',
},
{
fullName: 'Rollbit',
category: ['Exchange'],
symbol: 'RLB-PERP',
baseAssetSymbol: 'RLB',
marketIndex: 17,
oracle: new PublicKey('4CyhPqyVK3UQHFWhEpk91Aw4WbBsN3JtyosXH6zjoRqG'),
launchTs: 1699265968000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x2f2d17abbc1e781bd87b4a5d52c8b2856886f5c482fa3593cebf6795040ab0b6',
},
{
fullName: 'Pyth',
category: ['Oracle'],
symbol: 'PYTH-PERP',
baseAssetSymbol: 'PYTH',
marketIndex: 18,
oracle: new PublicKey('GqkCu7CbsPVz1H6W6AAHuReqbJckYG59TXz7Y5HDV7hr'),
launchTs: 1700542800000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x0bbf28e9a841a1cc788f6a361b17ca072d0ea3098a1e5df1c3922d06719579ff',
},
{
fullName: 'Celestia',
category: ['Data'],
symbol: 'TIA-PERP',
baseAssetSymbol: 'TIA',
marketIndex: 19,
oracle: new PublicKey('C6LHPUrgjrgo5eNUitC8raNEdEttfoRhmqdJ3BHVBJhi'),
launchTs: 1701880540000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x09f7c1d7dfbb7df2b8fe3d3d87ee94a2259d212da4f30c1f0540d066dfa44723',
},
{
fullName: 'Jito',
category: ['MEV'],
symbol: 'JTO-PERP',
baseAssetSymbol: 'JTO',
marketIndex: 20,
oracle: new PublicKey('Ffq6ACJ17NAgaxC6ocfMzVXL3K61qxB2xHg6WUawWPfP'),
launchTs: 1701967240000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xb43660a5f790c69354b0729a5ef9d50d68f1df92107540210b9cccba1f947cc2',
},
{
fullName: 'SEI',
category: ['L1'],
symbol: 'SEI-PERP',
baseAssetSymbol: 'SEI',
marketIndex: 21,
oracle: new PublicKey('EVyoxFo5jWpv1vV7p6KVjDWwVqtTqvrZ4JMFkieVkVsD'),
launchTs: 1703173331000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x53614f1cb0c031d4af66c04cb9c756234adad0e1cee85303795091499a4084eb',
},
{
fullName: 'AVAX',
category: ['Rollup', 'Infra'],
symbol: 'AVAX-PERP',
baseAssetSymbol: 'AVAX',
marketIndex: 22,
oracle: new PublicKey('FgBGHNex4urrBmNbSj8ntNQDGqeHcWewKtkvL6JE6dEX'),
launchTs: 1704209558000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x93da3352f9f1d105fdfe4971cfa80e9dd777bfc5d0f683ebb6e1294b92137bb7',
},
{
fullName: 'Wormhole',
category: ['Bridge'],
symbol: 'W-PERP',
baseAssetSymbol: 'W',
marketIndex: 23,
oracle: new PublicKey('J9nrFWjDUeDVZ4BhhxsbQXWgLcLEgQyNBrCbwSADmJdr'),
launchTs: 1709852537000,
oracleSource: OracleSource.SWITCHBOARD_ON_DEMAND,
pythFeedId:
'0xeff7446475e218517566ea99e72a4abec2e1bd8498b43b7d8331e29dcb059389',
},
{
fullName: 'Kamino',
category: ['Lending'],
symbol: 'KMNO-PERP',
baseAssetSymbol: 'KMNO',
marketIndex: 24,
oracle: new PublicKey('7aqj2wH1BH8XT3QQ3MWtvt3My7RAGf5Stm3vx5fiysJz'),
launchTs: 1711475936000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xb17e5bc5de742a8a378b54c9c75442b7d51e30ada63f28d9bd28d3c0e26511a0',
},
{
fullName: 'Wen',
category: ['Solana', 'Meme'],
symbol: '1KWEN-PERP',
baseAssetSymbol: '1KWEN',
marketIndex: 25,
oracle: new PublicKey('F47c7aJgYkfKXQ9gzrJaEpsNwUKHprysregTWXrtYLFp'),
launchTs: 1720572064000,
oracleSource: OracleSource.PYTH_1K_PULL,
pythFeedId:
'0x5169491cd7e2a44c98353b779d5eb612e4ac32e073f5cc534303d86307c2f1bc',
},
{
fullName: 'TRUMP-WIN-2024',
category: ['Prediction', 'Election'],
symbol: 'TRUMP-WIN-2024-PREDICT',
baseAssetSymbol: 'TRUMP-WIN-2024',
marketIndex: 26,
oracle: new PublicKey('3TVuLmEGBRfVgrmFRtYTheczXaaoRBwcHw1yibZHSeNA'),
launchTs: 1722214583000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'KAMALA-POPULAR-VOTE-2024',
category: ['Prediction', 'Election'],
symbol: 'KAMALA-POPULAR-VOTE-2024-PREDICT',
baseAssetSymbol: 'KAMALA-POPULAR-VOTE',
marketIndex: 27,
oracle: new PublicKey('GU6CA7a2KCyhpfqZNb36UAfc9uzKBM8jHjGdt245QhYX'),
launchTs: 1722214583000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'RANDOM-2024',
category: ['Prediction'],
symbol: 'RANDOM-2024-PREDICT',
baseAssetSymbol: 'RANDOM-2024',
marketIndex: 28,
oracle: new PublicKey('sDAQaZQJQ4RXAxH3x526mbEXyQZT15ktkL84d7hmk7M'),
launchTs: 1729622442000,
oracleSource: OracleSource.Prelaunch,
},
];
export const MainnetPerpMarkets: PerpMarketConfig[] = [
{
fullName: 'Solana',
category: ['L1', 'Infra', 'Solana'],
symbol: 'SOL-PERP',
baseAssetSymbol: 'SOL',
marketIndex: 0,
oracle: new PublicKey('BAtFj4kQttZRVep3UZS2aZRDixkGYgWsbqTBVDbnSsPF'),
launchTs: 1667560505000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d',
},
{
fullName: 'Bitcoin',
category: ['L1', 'Payment'],
symbol: 'BTC-PERP',
baseAssetSymbol: 'BTC',
marketIndex: 1,
oracle: new PublicKey('486kr3pmFPfTsS4aZgcsQ7kS4i9rjMsYYZup6HQNSTT4'),
launchTs: 1670347281000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43',
},
{
fullName: 'Ethereum',
category: ['L1', 'Infra'],
symbol: 'ETH-PERP',
baseAssetSymbol: 'ETH',
marketIndex: 2,
oracle: new PublicKey('6bEp2MiyoiiiDxcVqE8rUHQWwHirXUXtKfAEATTVqNzT'),
launchTs: 1670347281000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace',
},
{
fullName: 'Aptos',
category: ['L1', 'Infra'],
symbol: 'APT-PERP',
baseAssetSymbol: 'APT',
marketIndex: 3,
oracle: new PublicKey('79EWaCYU9jiQN8SbvVzGFAhAncUZYp3PjNg7KxmN5cLE'),
launchTs: 1675802661000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x03ae4db29ed4ae33d323568895aa00337e658e348b37509f5372ae51f0af00d5',
},
{
fullName: 'Bonk',
category: ['Meme', 'Solana'],
symbol: '1MBONK-PERP',
baseAssetSymbol: '1MBONK',
marketIndex: 4,
oracle: new PublicKey('GojbSnJuPdKDT1ZuHuAM5t9oz6bxTo1xhUKpTua2F72p'),
launchTs: 1677690149000,
oracleSource: OracleSource.PYTH_1M_PULL,
pythFeedId:
'0x72b021217ca3fe68922a19aaf990109cb9d84e9ad004b4d2025ad6f529314419',
},
{
fullName: 'Polygon',
category: ['L2', 'Infra'],
symbol: 'POL-PERP',
baseAssetSymbol: 'POL',
marketIndex: 5,
oracle: new PublicKey('BrzyDgwELy4jjjsqLQpBeUxzrsueYyMhuWpYBaUYcXvi'),
launchTs: 1677690149000, //todo
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xffd11c5a1cfd42f80afb2df4d9f264c15f956d68153335374ec10722edd70472',
},
{
fullName: 'Arbitrum',
category: ['L2', 'Infra'],
symbol: 'ARB-PERP',
baseAssetSymbol: 'ARB',
marketIndex: 6,
oracle: new PublicKey('8ocfAdqVRnzvfdubQaTxar4Kz5HJhNbPNmkLxswqiHUD'),
launchTs: 1679501812000, //todo
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x3fa4252848f9f0a1480be62745a4629d9eb1322aebab8a791e344b3b9c1adcf5',
},
{
fullName: 'Doge',
category: ['Meme', 'Dog'],
symbol: 'DOGE-PERP',
baseAssetSymbol: 'DOGE',
marketIndex: 7,
oracle: new PublicKey('23y63pHVwKfYSCDFdiGRaGbTYWoyr8UzhUE7zukyf6gK'),
launchTs: 1680808053000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xdcef50dd0a4cd2dcc17e45df1676dcb336a11a61c69df7a0299b0150c672d25c',
},
{
fullName: 'Binance Coin',
category: ['Exchange'],
symbol: 'BNB-PERP',
baseAssetSymbol: 'BNB',
marketIndex: 8,
oracle: new PublicKey('Dk8eWjuQHMbxJAwB9Sg7pXQPH4kgbg8qZGcUrWcD9gTm'),
launchTs: 1680808053000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x2f95862b045670cd22bee3114c39763a4a08beeb663b145d283c31d7d1101c4f',
},
{
fullName: 'Sui',
category: ['L1'],
symbol: 'SUI-PERP',
baseAssetSymbol: 'SUI',
marketIndex: 9,
oracle: new PublicKey('HBordkz5YxjzNURmKUY4vfEYFG9fZyZNeNF1VDLMoemT'),
launchTs: 1683125906000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744',
},
{
fullName: 'Pepe',
category: ['Meme'],
symbol: '1MPEPE-PERP',
baseAssetSymbol: '1MPEPE',
marketIndex: 10,
oracle: new PublicKey('CLxofhtzvLiErpn25wvUzpZXEqBhuZ6WMEckEraxyuGt'),
launchTs: 1683781239000,
oracleSource: OracleSource.PYTH_1M_PULL,
pythFeedId:
'0xd69731a2e74ac1ce884fc3890f7ee324b6deb66147055249568869ed700882e4',
},
{
fullName: 'OP',
category: ['L2', 'Infra'],
symbol: 'OP-PERP',
baseAssetSymbol: 'OP',
marketIndex: 11,
oracle: new PublicKey('C9Zi2Y3Mt6Zt6pcFvobN3N29HcrzKujPAPBDDTDRcUa2'),
launchTs: 1686091480000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x385f64d993f7b77d8182ed5003d97c60aa3361f3cecfe711544d2d59165e9bdf',
},
{
fullName: 'RENDER',
category: ['Infra', 'Solana'],
symbol: 'RENDER-PERP',
baseAssetSymbol: 'RENDER',
marketIndex: 12,
oracle: new PublicKey('8TQztfGcNjHGRusX4ejQQtPZs3Ypczt9jWF6pkgQMqUX'),
launchTs: 1687201081000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x3d4a2bd9535be6ce8059d75eadeba507b043257321aa544717c56fa19b49e35d',
},
{
fullName: 'XRP',
category: ['Payments'],
symbol: 'XRP-PERP',
baseAssetSymbol: 'XRP',
marketIndex: 13,
oracle: new PublicKey('9757epAjXWCWQH98kyK9vzgehd1XDVEf7joNHUaKk3iV'),
launchTs: 1689270550000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xec5d399846a9209f3fe5881d70aae9268c94339ff9817e8d18ff19fa05eea1c8',
},
{
fullName: 'HNT',
category: ['IoT', 'Solana'],
symbol: 'HNT-PERP',
baseAssetSymbol: 'HNT',
marketIndex: 14,
oracle: new PublicKey('9b1rcK9RUPK2vAqwNYCYEG34gUVpS2WGs2YCZZy2X5Tb'),
launchTs: 1692294955000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x649fdd7ec08e8e2a20f425729854e90293dcbe2376abc47197a14da6ff339756',
},
{
fullName: 'INJ',
category: ['L1', 'Exchange'],
symbol: 'INJ-PERP',
baseAssetSymbol: 'INJ',
marketIndex: 15,
oracle: new PublicKey('BfXcyDWJmYADa5eZD7gySSDd6giqgjvm7xsAhQ239SUD'),
launchTs: 1698074659000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x7a5bc1d2b56ad029048cd63964b3ad2776eadf812edc1a43a31406cb54bff592',
},
{
fullName: 'LINK',
category: ['Oracle'],
symbol: 'LINK-PERP',
baseAssetSymbol: 'LINK',
marketIndex: 16,
oracle: new PublicKey('Gwvob7yoLMgQRVWjScCRyQFMsgpRKrSAYisYEyjDJwEp'),
launchTs: 1698074659000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x8ac0c70fff57e9aefdf5edf44b51d62c2d433653cbb2cf5cc06bb115af04d221',
},
{
fullName: 'Rollbit',
category: ['Exchange'],
symbol: 'RLB-PERP',
baseAssetSymbol: 'RLB',
marketIndex: 17,
oracle: new PublicKey('4CyhPqyVK3UQHFWhEpk91Aw4WbBsN3JtyosXH6zjoRqG'),
launchTs: 1699265968000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x2f2d17abbc1e781bd87b4a5d52c8b2856886f5c482fa3593cebf6795040ab0b6',
},
{
fullName: 'Pyth',
category: ['Oracle', 'Solana'],
symbol: 'PYTH-PERP',
baseAssetSymbol: 'PYTH',
marketIndex: 18,
oracle: new PublicKey('GqkCu7CbsPVz1H6W6AAHuReqbJckYG59TXz7Y5HDV7hr'),
launchTs: 1700542800000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x0bbf28e9a841a1cc788f6a361b17ca072d0ea3098a1e5df1c3922d06719579ff',
},
{
fullName: 'Celestia',
category: ['Data'],
symbol: 'TIA-PERP',
baseAssetSymbol: 'TIA',
marketIndex: 19,
oracle: new PublicKey('C6LHPUrgjrgo5eNUitC8raNEdEttfoRhmqdJ3BHVBJhi'),
launchTs: 1701880540000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x09f7c1d7dfbb7df2b8fe3d3d87ee94a2259d212da4f30c1f0540d066dfa44723',
},
{
fullName: 'Jito',
category: ['MEV', 'Solana'],
symbol: 'JTO-PERP',
baseAssetSymbol: 'JTO',
marketIndex: 20,
oracle: new PublicKey('Ffq6ACJ17NAgaxC6ocfMzVXL3K61qxB2xHg6WUawWPfP'),
launchTs: 1701967240000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xb43660a5f790c69354b0729a5ef9d50d68f1df92107540210b9cccba1f947cc2',
},
{
fullName: 'SEI',
category: ['L1'],
symbol: 'SEI-PERP',
baseAssetSymbol: 'SEI',
marketIndex: 21,
oracle: new PublicKey('EVyoxFo5jWpv1vV7p6KVjDWwVqtTqvrZ4JMFkieVkVsD'),
launchTs: 1703173331000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x53614f1cb0c031d4af66c04cb9c756234adad0e1cee85303795091499a4084eb',
},
{
fullName: 'AVAX',
category: ['Rollup', 'Infra'],
symbol: 'AVAX-PERP',
baseAssetSymbol: 'AVAX',
marketIndex: 22,
oracle: new PublicKey('FgBGHNex4urrBmNbSj8ntNQDGqeHcWewKtkvL6JE6dEX'),
launchTs: 1704209558000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x93da3352f9f1d105fdfe4971cfa80e9dd777bfc5d0f683ebb6e1294b92137bb7',
},
{
fullName: 'WIF',
category: ['Meme', 'Dog', 'Solana'],
symbol: 'WIF-PERP',
baseAssetSymbol: 'WIF',
marketIndex: 23,
oracle: new PublicKey('6x6KfE7nY2xoLCRSMPT1u83wQ5fpGXoKNBqFjrCwzsCQ'),
launchTs: 1706219971000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x4ca4beeca86f0d164160323817a4e42b10010a724c2217c6ee41b54cd4cc61fc',
},
{
fullName: 'JUP',
category: ['Exchange', 'Infra', 'Solana'],
symbol: 'JUP-PERP',
baseAssetSymbol: 'JUP',
marketIndex: 24,
oracle: new PublicKey('AwqRpfJ36jnSZQykyL1jYY35mhMteeEAjh7o8LveRQin'),
launchTs: 1706713201000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x0a0408d619e9380abad35060f9192039ed5042fa6f82301d0e48bb52be830996',
},
{
fullName: 'Dymension',
category: ['Rollup', 'Infra'],
symbol: 'DYM-PERP',
baseAssetSymbol: 'DYM',
marketIndex: 25,
oracle: new PublicKey('hnefGsC8hJi8MBajpRSkUY97wJmLoBQYXaHkz3nmw1z'),
launchTs: 1708448765000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xa9f3b2a89c6f85a6c20a9518abde39b944e839ca49a0c92307c65974d3f14a57',
},
{
fullName: 'BITTENSOR',
category: ['AI', 'Infra'],
symbol: 'TAO-PERP',
baseAssetSymbol: 'TAO',
marketIndex: 26,
oracle: new PublicKey('5ZPtwR9QpBLcZQVMnVURuYBmZMu1qQrBcA9Gutc5eKN3'),
launchTs: 1709136669000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x410f41de235f2db824e562ea7ab2d3d3d4ff048316c61d629c0b93f58584e1af',
},
{
fullName: 'Wormhole',
category: ['Bridge'],
symbol: 'W-PERP',
baseAssetSymbol: 'W',
marketIndex: 27,
oracle: new PublicKey('4HbitGsdcFbtFotmYscikQFAAKJ3nYx4t7sV7fTvsk8U'),
launchTs: 1710418343000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xeff7446475e218517566ea99e72a4abec2e1bd8498b43b7d8331e29dcb059389',
},
{
fullName: 'Kamino',
category: ['Lending', 'Solana'],
symbol: 'KMNO-PERP',
baseAssetSymbol: 'KMNO',
marketIndex: 28,
oracle: new PublicKey('7aqj2wH1BH8XT3QQ3MWtvt3My7RAGf5Stm3vx5fiysJz'),
launchTs: 1712240681000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xb17e5bc5de742a8a378b54c9c75442b7d51e30ada63f28d9bd28d3c0e26511a0',
},
{
fullName: 'Tensor',
category: ['NFT', 'Solana'],
symbol: 'TNSR-PERP',
baseAssetSymbol: 'TNSR',
marketIndex: 29,
oracle: new PublicKey('13jpjpVyU5hGpjsZ4HzCcmBo85wze4N8Au7U6cC3GMip'),
launchTs: 1712593532000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x05ecd4597cd48fe13d6cc3596c62af4f9675aee06e2e0b94c06d8bee2b659e05',
},
{
fullName: 'Drift',
category: ['DEX', 'Solana'],
symbol: 'DRIFT-PERP',
baseAssetSymbol: 'DRIFT',
marketIndex: 30,
oracle: new PublicKey('23KmX7SNikmUr2axSCy6Zer7XPBnvmVcASALnDGqBVRR'),
launchTs: 1716595200000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x5c1690b27bb02446db17cdda13ccc2c1d609ad6d2ef5bf4983a85ea8b6f19d07',
},
{
fullName: 'Sanctum',
category: ['LST', 'Solana'],
symbol: 'CLOUD-PERP',
baseAssetSymbol: 'CLOUD',
marketIndex: 31,
oracle: new PublicKey('FNFejcXENaPgKaCTfstew9vSSvdQPnXjGTkJjUnnYvHU'),
launchTs: 1717597648000,
oracleSource: OracleSource.SWITCHBOARD_ON_DEMAND,
},
{
fullName: 'IO',
category: ['DePIN', 'Solana'],
symbol: 'IO-PERP',
baseAssetSymbol: 'IO',
marketIndex: 32,
oracle: new PublicKey('HxM66CFwGwrvfTFFkvvA8N3CnKX6m2obzameYWDaSSdA'),
launchTs: 1718021389000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x82595d1509b770fa52681e260af4dda9752b87316d7c048535d8ead3fa856eb1',
},
{
fullName: 'ZEX',
category: ['DEX', 'Solana'],
symbol: 'ZEX-PERP',
baseAssetSymbol: 'ZEX',
marketIndex: 33,
oracle: new PublicKey('HVwBCaR4GEB1fHrp7xCTzbYoZXL3V8b1aek2swPrmGx3'),
launchTs: 1719415157000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x3d63be09d1b88f6dffe6585d0170670592124fd9fa4e0fe8a09ff18464f05e3a',
},
{
fullName: 'POPCAT',
category: ['Meme', 'Solana'],
symbol: 'POPCAT-PERP',
baseAssetSymbol: 'POPCAT',
marketIndex: 34,
oracle: new PublicKey('H3pn43tkNvsG5z3qzmERguSvKoyHZvvY6VPmNrJqiW5X'),
launchTs: 1720013054000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xb9312a7ee50e189ef045aa3c7842e099b061bd9bdc99ac645956c3b660dc8cce',
},
{
fullName: 'Wen',
category: ['Solana', 'Meme'],
symbol: '1KWEN-PERP',
baseAssetSymbol: '1KWEN',
marketIndex: 35,
oracle: new PublicKey('F47c7aJgYkfKXQ9gzrJaEpsNwUKHprysregTWXrtYLFp'),
launchTs: 1720633344000,
oracleSource: OracleSource.PYTH_1K_PULL,
pythFeedId:
'0x5169491cd7e2a44c98353b779d5eb612e4ac32e073f5cc534303d86307c2f1bc',
},
{
fullName: 'TRUMP-WIN-2024-BET',
category: ['Prediction', 'Election'],
symbol: 'TRUMP-WIN-2024-BET',
baseAssetSymbol: 'TRUMP-WIN-2024',
marketIndex: 36,
oracle: new PublicKey('7YrQUxmxGdbk8pvns9KcL5ojbZSL2eHj62hxRqggtEUR'),
launchTs: 1723996800000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'KAMALA-POPULAR-VOTE-2024-BET',
category: ['Prediction', 'Election'],
symbol: 'KAMALA-POPULAR-VOTE-2024-BET',
baseAssetSymbol: 'KAMALA-POPULAR-VOTE-2024',
marketIndex: 37,
oracle: new PublicKey('AowFw1dCVjS8kngvTCoT3oshiUyL69k7P1uxqXwteWH4'),
launchTs: 1723996800000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'FED-CUT-50-SEPT-2024-BET',
category: ['Prediction', 'Election'],
symbol: 'FED-CUT-50-SEPT-2024-BET',
baseAssetSymbol: 'FED-CUT-50-SEPT-2024',
marketIndex: 38,
oracle: new PublicKey('5QzgqAbEhJ1cPnLX4tSZEXezmW7sz7PPVVg2VanGi8QQ'),
launchTs: 1724250126000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'REPUBLICAN-POPULAR-AND-WIN-BET',
category: ['Prediction', 'Election'],
symbol: 'REPUBLICAN-POPULAR-AND-WIN-BET',
baseAssetSymbol: 'REPUBLICAN-POPULAR-AND-WIN',
marketIndex: 39,
oracle: new PublicKey('BtUUSUc9rZSzBmmKhQq4no65zHQTzMFeVYss7xcMRD53'),
launchTs: 1724250126000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'BREAKPOINT-IGGYERIC-BET',
category: ['Prediction', 'Solana'],
symbol: 'BREAKPOINT-IGGYERIC-BET',
baseAssetSymbol: 'BREAKPOINT-IGGYERIC',
marketIndex: 40,
oracle: new PublicKey('2ftYxoSupperd4ULxy9xyS2Az38wfAe7Lm8FCAPwjjVV'),
launchTs: 1724250126000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'DEMOCRATS-WIN-MICHIGAN-BET',
category: ['Prediction', 'Election'],
symbol: 'DEMOCRATS-WIN-MICHIGAN-BET',
baseAssetSymbol: 'DEMOCRATS-WIN-MICHIGAN',
marketIndex: 41,
oracle: new PublicKey('8HTDLjhb2esGU5mu11v3pq3eWeFqmvKPkQNCnTTwKAyB'),
launchTs: 1725551484000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'TON',
category: ['L1'],
symbol: 'TON-PERP',
baseAssetSymbol: 'TON',
marketIndex: 42,
oracle: new PublicKey('BNjCXrpEqjdBnuRy2SAUgm5Pq8B73wGFwsf6RYFJiLPY'),
launchTs: 1725551484000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x8963217838ab4cf5cadc172203c1f0b763fbaa45f346d8ee50ba994bbcac3026',
},
{
fullName: 'LANDO-F1-SGP-WIN-BET',
category: ['Prediction', 'Sports'],
symbol: 'LANDO-F1-SGP-WIN-BET',
baseAssetSymbol: 'LANDO-F1-SGP-WIN',
marketIndex: 43,
oracle: new PublicKey('DpJz7rjTJLxxnuqrqZTUjMWtnaMFAEfZUv5ATdb9HTh1'),
launchTs: 1726646453000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'MOTHER',
category: ['Solana', 'Meme'],
symbol: 'MOTHER-PERP',
baseAssetSymbol: 'MOTHER',
marketIndex: 44,
oracle: new PublicKey('56ap2coZG7FPWUigVm9XrpQs3xuCwnwQaWtjWZcffEUG'),
launchTs: 1727291859000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x62742a997d01f7524f791fdb2dd43aaf0e567d765ebf8fd0406a994239e874d4',
},
{
fullName: 'MOODENG',
category: ['Solana', 'Meme'],
symbol: 'MOODENG-PERP',
baseAssetSymbol: 'MOODENG',
marketIndex: 45,
oracle: new PublicKey('21gjgEcuDppthwV16J1QpFzje3vmgMp2uSzh7pJsG7ob'),
launchTs: 1727965864000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xffff73128917a90950cd0473fd2551d7cd274fd5a6cc45641881bbcc6ee73417',
},
{
fullName: 'WARWICK-FIGHT-WIN-BET',
category: ['Prediction', 'Sport'],
symbol: 'WARWICK-FIGHT-WIN-BET',
baseAssetSymbol: 'WARWICK-FIGHT-WIN',
marketIndex: 46,
oracle: new PublicKey('Dz5Nvxo1hv7Zfyu11hy8e97twLMRKk6heTWCDGXytj7N'),
launchTs: 1727965864000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'DeBridge',
category: ['Bridge'],
symbol: 'DBR-PERP',
baseAssetSymbol: 'DBR',
marketIndex: 47,
oracle: new PublicKey('53j4mz7cQV7mAZekKbV3n2L4bY7jY6eXdgaTkWDLYxq4'),
launchTs: 1728574493000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xf788488fe2df341b10a498e0a789f03209c0938d9ed04bc521f8224748d6d236',
},
{
fullName: 'WLF-5B-1W',
category: ['Prediction'],
symbol: 'WLF-5B-1W-BET',
baseAssetSymbol: 'WLF-5B-1W',
marketIndex: 48,
oracle: new PublicKey('7LpRfPaWR7cQqN7CMkCmZjEQpWyqso5LGuKCvDXH5ZAr'),
launchTs: 1728574493000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'VRSTPN-WIN-F1-24-DRVRS-CHMP',
category: ['Prediction', 'Sport'],
symbol: 'VRSTPN-WIN-F1-24-DRVRS-CHMP-BET',
baseAssetSymbol: 'VRSTPN-WIN-F1-24-DRVRS-CHMP',
marketIndex: 49,
oracle: new PublicKey('E36rvXEwysWeiToXCpWfHVADd8bzzyR4w83ZSSwxAxqG'),
launchTs: 1729209600000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'LNDO-WIN-F1-24-US-GP',
category: ['Prediction', 'Sport'],
symbol: 'LNDO-WIN-F1-24-US-GP-BET',
baseAssetSymbol: 'LNDO-WIN-F1-24-US-GP',
marketIndex: 50,
oracle: new PublicKey('6AVy1y9SnJECnosQaiK2uY1kcT4ZEBf1F4DMvhxgvhUo'),
launchTs: 1729209600000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: '1KMEW',
category: ['Meme'],
symbol: '1KMEW-PERP',
baseAssetSymbol: '1KMEW',
marketIndex: 51,
oracle: new PublicKey('DKGwCUcwngwmgifGxnme7zVR695LCBGk2pnuksRnbhfD'),
launchTs: 1729702915000,
oracleSource: OracleSource.PYTH_1K_PULL,
pythFeedId:
'0x514aed52ca5294177f20187ae883cec4a018619772ddce41efcc36a6448f5d5d',
},
{
fullName: 'MICHI',
category: ['Meme'],
symbol: 'MICHI-PERP',
baseAssetSymbol: 'MICHI',
marketIndex: 52,
oracle: new PublicKey('GHzvsMDMSiuyZoWhEAuM27MKFdN2Y4fA4wSDuSd6dLMA'),
launchTs: 1730402722000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x63a45218d6b13ffd28ca04748615511bf70eff80a3411c97d96b8ed74a6decab',
},
{
fullName: 'GOAT',
category: ['Meme'],
symbol: 'GOAT-PERP',
baseAssetSymbol: 'GOAT',
marketIndex: 53,
oracle: new PublicKey('5RgXW13Kq1RgCLEsJhhchWt3W4R2XLJnd6KqgZk6dSY7'),
launchTs: 1731443152000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0xf7731dc812590214d3eb4343bfb13d1b4cfa9b1d4e020644b5d5d8e07d60c66c',
},
{
fullName: 'FWOG',
category: ['Meme'],
symbol: 'FWOG-PERP',
baseAssetSymbol: 'FWOG',
marketIndex: 54,
oracle: new PublicKey('5Z7uvkAsHNN6qqkQkwcKcEPYZqiMbFE9E24p7SpvfSrv'),
launchTs: 1731443152000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x656cc2a39dd795bdecb59de810d4f4d1e74c25fe4c42d0bf1c65a38d74df48e9',
},
{
fullName: 'PNUT',
category: ['Meme'],
symbol: 'PNUT-PERP',
baseAssetSymbol: 'PNUT',
marketIndex: 55,
oracle: new PublicKey('5AcetMtdRHxkse2ny44NcRdsysnXu9deW7Yy5Y63qAHE'),
launchTs: 1731443152000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x116da895807f81f6b5c5f01b109376e7f6834dc8b51365ab7cdfa66634340e54',
},
{
fullName: 'RAY',
category: ['DEX'],
symbol: 'RAY-PERP',
baseAssetSymbol: 'RAY',
marketIndex: 56,
oracle: new PublicKey('DPvPBacXhEyA1VXF4E3EYH3h83Bynh5uP3JLeN25TWzm'),
launchTs: 1732721897000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x91568baa8beb53db23eb3fb7f22c6e8bd303d103919e19733f2bb642d3e7987a',
},
{
fullName: 'SUPERBOWL-LIX-LIONS',
category: ['Prediction', 'Sport'],
symbol: 'SUPERBOWL-LIX-LIONS-BET',
baseAssetSymbol: 'SUPERBOWL-LIX-LIONS',
marketIndex: 57,
oracle: new PublicKey('GfTeKKnBxeLSB1Hm24ArjduQM4yqaAgoGgiC99gq5E2P'),
launchTs: 1732721897000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'SUPERBOWL-LIX-CHIEFS',
category: ['Prediction', 'Sport'],
symbol: 'SUPERBOWL-LIX-CHIEFS-BET',
baseAssetSymbol: 'SUPERBOWL-LIX-CHIEFS',
marketIndex: 58,
oracle: new PublicKey('EdB17Nyu4bnEBiSEfFrwvp4VCUvtq9eDJHc6Ujys3Jwd'),
launchTs: 1732721897000,
oracleSource: OracleSource.Prelaunch,
},
{
fullName: 'Hyperliquid',
category: ['DEX'],
symbol: 'HYPE-PERP',
baseAssetSymbol: 'HYPE',
marketIndex: 59,
oracle: new PublicKey('Hn9JHQHKSvtnZ2xTWCgRGVNmav2TPffH7T72T6WoJ1cw'),
launchTs: 1733374800000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x4279e31cc369bbcc2faf022b382b080e32a8e689ff20fbc530d2a603eb6cd98b',
},
{
fullName: 'LiteCoin',
category: ['Payment'],
symbol: 'LTC-PERP',
baseAssetSymbol: 'LTC',
marketIndex: 60,
oracle: new PublicKey('AmjHowvVkVJApCPUiwV9CdHVFn29LiBYZQqtZQ3xMqdg'),
launchTs: 1733374800000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x6e3f3fa8253588df9326580180233eb791e03b443a3ba7a1d892e73874e19a54',
},
{
fullName: 'Magic Eden',
category: ['DEX'],
symbol: 'ME-PERP',
baseAssetSymbol: 'ME',
marketIndex: 61,
oracle: new PublicKey('FLQjrmEPGwbCKRYZ1eYM5FPccHBrCv2cN4GBu3mWfmPH'),
launchTs: 1733839936000,
oracleSource: OracleSource.PYTH_PULL,
pythFeedId:
'0x91519e3e48571e1232a85a938e714da19fe5ce05107f3eebb8a870b2e8020169',
},
];
export const PerpMarkets: { [key in DriftEnv]: PerpMarketConfig[] } = {
devnet: DevnetPerpMarkets,
'mainnet-beta': MainnetPerpMarkets,
};
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/phoenix/phoenixFulfillmentConfigMap.ts
|
import { PublicKey } from '@solana/web3.js';
import { PhoenixV1FulfillmentConfigAccount } from '../types';
import { DriftClient } from '../driftClient';
export class PhoenixFulfillmentConfigMap {
driftClient: DriftClient;
map = new Map<number, PhoenixV1FulfillmentConfigAccount>();
public constructor(driftClient: DriftClient) {
this.driftClient = driftClient;
}
public async add(
marketIndex: number,
phoenixMarketAddress: PublicKey
): Promise<void> {
const account = await this.driftClient.getPhoenixV1FulfillmentConfig(
phoenixMarketAddress
);
this.map.set(marketIndex, account);
}
public get(marketIndex: number): PhoenixV1FulfillmentConfigAccount {
return this.map.get(marketIndex);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/phoenix/phoenixSubscriber.ts
|
import { Connection, PublicKey, SYSVAR_CLOCK_PUBKEY } from '@solana/web3.js';
import { BulkAccountLoader } from '../accounts/bulkAccountLoader';
import {
Client,
deserializeClockData,
toNum,
getMarketUiLadder,
Market,
} from '@ellipsis-labs/phoenix-sdk';
import { PRICE_PRECISION } from '../constants/numericConstants';
import { BN } from '@coral-xyz/anchor';
import { L2Level, L2OrderBookGenerator } from '../dlob/orderBookLevels';
import { fastDecode } from '../decode/phoenix';
export type PhoenixMarketSubscriberConfig = {
connection: Connection;
programId: PublicKey;
marketAddress: PublicKey;
accountSubscription:
| {
// enables use to add web sockets in the future
type: 'polling';
accountLoader: BulkAccountLoader;
}
| {
type: 'websocket';
};
fastDecode?: boolean;
};
export class PhoenixSubscriber implements L2OrderBookGenerator {
connection: Connection;
client: Client;
programId: PublicKey;
marketAddress: PublicKey;
subscriptionType: 'polling' | 'websocket';
accountLoader: BulkAccountLoader | undefined;
market: Market;
marketCallbackId: string | number;
clockCallbackId: string | number;
// fastDecode omits trader data from the markets for faster decoding process
fastDecode: boolean;
subscribed: boolean;
lastSlot: number;
lastUnixTimestamp: number;
public constructor(config: PhoenixMarketSubscriberConfig) {
this.connection = config.connection;
this.programId = config.programId;
this.marketAddress = config.marketAddress;
if (config.accountSubscription.type === 'polling') {
this.subscriptionType = 'polling';
this.accountLoader = config.accountSubscription.accountLoader;
} else {
this.subscriptionType = 'websocket';
}
this.lastSlot = 0;
this.lastUnixTimestamp = 0;
this.fastDecode = config.fastDecode ?? true;
}
public async subscribe(): Promise<void> {
if (this.subscribed) {
return;
}
this.market = await Market.loadFromAddress({
connection: this.connection,
address: this.marketAddress,
});
const clock = deserializeClockData(
(await this.connection.getAccountInfo(SYSVAR_CLOCK_PUBKEY, 'confirmed'))
.data
);
this.lastUnixTimestamp = toNum(clock.unixTimestamp);
if (this.subscriptionType === 'websocket') {
this.marketCallbackId = this.connection.onAccountChange(
this.marketAddress,
(accountInfo, _ctx) => {
try {
if (this.fastDecode) {
this.market.data = fastDecode(accountInfo.data);
} else {
this.market = this.market.reload(accountInfo.data);
}
} catch {
console.error('Failed to reload Phoenix market data');
}
}
);
this.clockCallbackId = this.connection.onAccountChange(
SYSVAR_CLOCK_PUBKEY,
(accountInfo, ctx) => {
try {
this.lastSlot = ctx.slot;
const clock = deserializeClockData(accountInfo.data);
this.lastUnixTimestamp = toNum(clock.unixTimestamp);
} catch {
console.error('Failed to reload clock data');
}
}
);
} else {
this.marketCallbackId = await this.accountLoader.addAccount(
this.marketAddress,
(buffer, slot) => {
try {
this.lastSlot = slot;
if (buffer) {
if (this.fastDecode) {
this.market.data = fastDecode(buffer);
} else {
this.market = this.market.reload(buffer);
}
}
} catch {
console.error('Failed to reload Phoenix market data');
}
}
);
this.clockCallbackId = await this.accountLoader.addAccount(
SYSVAR_CLOCK_PUBKEY,
(buffer, slot) => {
try {
this.lastSlot = slot;
const clock = deserializeClockData(buffer);
this.lastUnixTimestamp = toNum(clock.unixTimestamp);
} catch {
console.error('Failed to reload clock data');
}
}
);
}
this.subscribed = true;
}
public getBestBid(): BN | undefined {
const ladder = getMarketUiLadder(
this.market,
this.lastSlot,
this.lastUnixTimestamp,
1
);
const bestBid = ladder.bids[0];
if (!bestBid) {
return undefined;
}
return new BN(Math.floor(bestBid.price * PRICE_PRECISION.toNumber()));
}
public getBestAsk(): BN | undefined {
const ladder = getMarketUiLadder(
this.market,
this.lastSlot,
this.lastUnixTimestamp,
1
);
const bestAsk = ladder.asks[0];
if (!bestAsk) {
return undefined;
}
return new BN(Math.floor(bestAsk.price * PRICE_PRECISION.toNumber()));
}
public getL2Bids(): Generator<L2Level> {
return this.getL2Levels('bids');
}
public getL2Asks(): Generator<L2Level> {
return this.getL2Levels('asks');
}
*getL2Levels(side: 'bids' | 'asks'): Generator<L2Level> {
const basePrecision = Math.pow(
10,
this.market.data.header.baseParams.decimals
);
const pricePrecision = PRICE_PRECISION.toNumber();
const ladder = getMarketUiLadder(
this.market,
this.lastSlot,
this.lastUnixTimestamp,
20
);
for (let i = 0; i < ladder[side].length; i++) {
const { price, quantity } = ladder[side][i];
try {
const size = new BN(quantity * basePrecision);
const updatedPrice = new BN(price * pricePrecision);
yield {
price: updatedPrice,
size,
sources: {
phoenix: size,
},
};
} catch {
continue;
}
}
}
public async unsubscribe(): Promise<void> {
if (!this.subscribed) {
return;
}
// remove listeners
if (this.subscriptionType === 'websocket') {
await this.connection.removeAccountChangeListener(
this.marketCallbackId as number
);
await this.connection.removeAccountChangeListener(
this.clockCallbackId as number
);
} else {
this.accountLoader.removeAccount(
this.marketAddress,
this.marketCallbackId as string
);
this.accountLoader.removeAccount(
SYSVAR_CLOCK_PUBKEY,
this.clockCallbackId as string
);
}
this.subscribed = false;
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/marinade/types.ts
|
export type MarinadeFinance = {
version: '0.1.0';
name: 'marinade_finance';
instructions: [
{
name: 'initialize';
accounts: [
{
name: 'creatorAuthority';
isMut: false;
isSigner: true;
},
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'reservePda';
isMut: false;
isSigner: false;
},
{
name: 'stakeList';
isMut: true;
isSigner: false;
},
{
name: 'validatorList';
isMut: true;
isSigner: false;
},
{
name: 'msolMint';
isMut: false;
isSigner: false;
},
{
name: 'operationalSolAccount';
isMut: false;
isSigner: false;
},
{
name: 'liqPool';
accounts: [
{
name: 'lpMint';
isMut: false;
isSigner: false;
},
{
name: 'solLegPda';
isMut: false;
isSigner: false;
},
{
name: 'msolLeg';
isMut: false;
isSigner: false;
},
];
},
{
name: 'treasuryMsolAccount';
isMut: false;
isSigner: false;
},
{
name: 'clock';
isMut: false;
isSigner: false;
},
{
name: 'rent';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'data';
type: {
defined: 'InitializeData';
};
},
];
},
{
name: 'changeAuthority';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'adminAuthority';
isMut: false;
isSigner: true;
},
];
args: [
{
name: 'data';
type: {
defined: 'ChangeAuthorityData';
};
},
];
},
{
name: 'addValidator';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'managerAuthority';
isMut: false;
isSigner: true;
},
{
name: 'validatorList';
isMut: true;
isSigner: false;
},
{
name: 'validatorVote';
isMut: false;
isSigner: false;
},
{
name: 'duplicationFlag';
isMut: true;
isSigner: false;
},
{
name: 'rentPayer';
isMut: true;
isSigner: true;
},
{
name: 'clock';
isMut: false;
isSigner: false;
},
{
name: 'rent';
isMut: false;
isSigner: false;
},
{
name: 'systemProgram';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'score';
type: 'u32';
},
];
},
{
name: 'removeValidator';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'managerAuthority';
isMut: false;
isSigner: true;
},
{
name: 'validatorList';
isMut: true;
isSigner: false;
},
{
name: 'duplicationFlag';
isMut: true;
isSigner: false;
},
{
name: 'operationalSolAccount';
isMut: true;
isSigner: false;
},
];
args: [
{
name: 'index';
type: 'u32';
},
{
name: 'validatorVote';
type: 'publicKey';
},
];
},
{
name: 'setValidatorScore';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'managerAuthority';
isMut: false;
isSigner: true;
},
{
name: 'validatorList';
isMut: true;
isSigner: false;
},
];
args: [
{
name: 'index';
type: 'u32';
},
{
name: 'validatorVote';
type: 'publicKey';
},
{
name: 'score';
type: 'u32';
},
];
},
{
name: 'configValidatorSystem';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'managerAuthority';
isMut: false;
isSigner: true;
},
];
args: [
{
name: 'extraRuns';
type: 'u32';
},
];
},
{
name: 'deposit';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'msolMint';
isMut: true;
isSigner: false;
},
{
name: 'liqPoolSolLegPda';
isMut: true;
isSigner: false;
},
{
name: 'liqPoolMsolLeg';
isMut: true;
isSigner: false;
},
{
name: 'liqPoolMsolLegAuthority';
isMut: false;
isSigner: false;
},
{
name: 'reservePda';
isMut: true;
isSigner: false;
},
{
name: 'transferFrom';
isMut: true;
isSigner: true;
},
{
name: 'mintTo';
isMut: true;
isSigner: false;
},
{
name: 'msolMintAuthority';
isMut: false;
isSigner: false;
},
{
name: 'systemProgram';
isMut: false;
isSigner: false;
},
{
name: 'tokenProgram';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'lamports';
type: 'u64';
},
];
},
{
name: 'depositStakeAccount';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'validatorList';
isMut: true;
isSigner: false;
},
{
name: 'stakeList';
isMut: true;
isSigner: false;
},
{
name: 'stakeAccount';
isMut: true;
isSigner: false;
},
{
name: 'stakeAuthority';
isMut: false;
isSigner: true;
},
{
name: 'duplicationFlag';
isMut: true;
isSigner: false;
},
{
name: 'rentPayer';
isMut: true;
isSigner: true;
},
{
name: 'msolMint';
isMut: true;
isSigner: false;
},
{
name: 'mintTo';
isMut: true;
isSigner: false;
},
{
name: 'msolMintAuthority';
isMut: false;
isSigner: false;
},
{
name: 'clock';
isMut: false;
isSigner: false;
},
{
name: 'rent';
isMut: false;
isSigner: false;
},
{
name: 'systemProgram';
isMut: false;
isSigner: false;
},
{
name: 'tokenProgram';
isMut: false;
isSigner: false;
},
{
name: 'stakeProgram';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'validatorIndex';
type: 'u32';
},
];
},
{
name: 'liquidUnstake';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'msolMint';
isMut: true;
isSigner: false;
},
{
name: 'liqPoolSolLegPda';
isMut: true;
isSigner: false;
},
{
name: 'liqPoolMsolLeg';
isMut: true;
isSigner: false;
},
{
name: 'treasuryMsolAccount';
isMut: true;
isSigner: false;
},
{
name: 'getMsolFrom';
isMut: true;
isSigner: false;
},
{
name: 'getMsolFromAuthority';
isMut: false;
isSigner: true;
},
{
name: 'transferSolTo';
isMut: true;
isSigner: false;
},
{
name: 'systemProgram';
isMut: false;
isSigner: false;
},
{
name: 'tokenProgram';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'msolAmount';
type: 'u64';
},
];
},
{
name: 'addLiquidity';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'lpMint';
isMut: true;
isSigner: false;
},
{
name: 'lpMintAuthority';
isMut: false;
isSigner: false;
},
{
name: 'liqPoolMsolLeg';
isMut: false;
isSigner: false;
},
{
name: 'liqPoolSolLegPda';
isMut: true;
isSigner: false;
},
{
name: 'transferFrom';
isMut: true;
isSigner: true;
},
{
name: 'mintTo';
isMut: true;
isSigner: false;
},
{
name: 'systemProgram';
isMut: false;
isSigner: false;
},
{
name: 'tokenProgram';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'lamports';
type: 'u64';
},
];
},
{
name: 'removeLiquidity';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'lpMint';
isMut: true;
isSigner: false;
},
{
name: 'burnFrom';
isMut: true;
isSigner: false;
},
{
name: 'burnFromAuthority';
isMut: false;
isSigner: true;
},
{
name: 'transferSolTo';
isMut: true;
isSigner: false;
},
{
name: 'transferMsolTo';
isMut: true;
isSigner: false;
},
{
name: 'liqPoolSolLegPda';
isMut: true;
isSigner: false;
},
{
name: 'liqPoolMsolLeg';
isMut: true;
isSigner: false;
},
{
name: 'liqPoolMsolLegAuthority';
isMut: false;
isSigner: false;
},
{
name: 'systemProgram';
isMut: false;
isSigner: false;
},
{
name: 'tokenProgram';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'tokens';
type: 'u64';
},
];
},
{
name: 'configLp';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'adminAuthority';
isMut: false;
isSigner: true;
},
];
args: [
{
name: 'params';
type: {
defined: 'ConfigLpParams';
};
},
];
},
{
name: 'configMarinade';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'adminAuthority';
isMut: false;
isSigner: true;
},
];
args: [
{
name: 'params';
type: {
defined: 'ConfigMarinadeParams';
};
},
];
},
{
name: 'orderUnstake';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'msolMint';
isMut: true;
isSigner: false;
},
{
name: 'burnMsolFrom';
isMut: true;
isSigner: false;
},
{
name: 'burnMsolAuthority';
isMut: false;
isSigner: true;
},
{
name: 'newTicketAccount';
isMut: true;
isSigner: false;
},
{
name: 'clock';
isMut: false;
isSigner: false;
},
{
name: 'rent';
isMut: false;
isSigner: false;
},
{
name: 'tokenProgram';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'msolAmount';
type: 'u64';
},
];
},
{
name: 'claim';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'reservePda';
isMut: true;
isSigner: false;
},
{
name: 'ticketAccount';
isMut: true;
isSigner: false;
},
{
name: 'transferSolTo';
isMut: true;
isSigner: false;
},
{
name: 'clock';
isMut: false;
isSigner: false;
},
{
name: 'systemProgram';
isMut: false;
isSigner: false;
},
];
args: [];
},
{
name: 'stakeReserve';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'validatorList';
isMut: true;
isSigner: false;
},
{
name: 'stakeList';
isMut: true;
isSigner: false;
},
{
name: 'validatorVote';
isMut: true;
isSigner: false;
},
{
name: 'reservePda';
isMut: true;
isSigner: false;
},
{
name: 'stakeAccount';
isMut: true;
isSigner: false;
},
{
name: 'stakeDepositAuthority';
isMut: false;
isSigner: false;
},
{
name: 'clock';
isMut: false;
isSigner: false;
},
{
name: 'epochSchedule';
isMut: false;
isSigner: false;
},
{
name: 'rent';
isMut: false;
isSigner: false;
},
{
name: 'stakeHistory';
isMut: false;
isSigner: false;
},
{
name: 'stakeConfig';
isMut: false;
isSigner: false;
},
{
name: 'systemProgram';
isMut: false;
isSigner: false;
},
{
name: 'stakeProgram';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'validatorIndex';
type: 'u32';
},
];
},
{
name: 'updateActive';
accounts: [
{
name: 'common';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'stakeList';
isMut: true;
isSigner: false;
},
{
name: 'stakeAccount';
isMut: true;
isSigner: false;
},
{
name: 'stakeWithdrawAuthority';
isMut: false;
isSigner: false;
},
{
name: 'reservePda';
isMut: true;
isSigner: false;
},
{
name: 'msolMint';
isMut: true;
isSigner: false;
},
{
name: 'msolMintAuthority';
isMut: false;
isSigner: false;
},
{
name: 'treasuryMsolAccount';
isMut: true;
isSigner: false;
},
{
name: 'clock';
isMut: false;
isSigner: false;
},
{
name: 'stakeHistory';
isMut: false;
isSigner: false;
},
{
name: 'stakeProgram';
isMut: false;
isSigner: false;
},
{
name: 'tokenProgram';
isMut: false;
isSigner: false;
},
];
},
{
name: 'validatorList';
isMut: true;
isSigner: false;
},
];
args: [
{
name: 'stakeIndex';
type: 'u32';
},
{
name: 'validatorIndex';
type: 'u32';
},
];
},
{
name: 'updateDeactivated';
accounts: [
{
name: 'common';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'stakeList';
isMut: true;
isSigner: false;
},
{
name: 'stakeAccount';
isMut: true;
isSigner: false;
},
{
name: 'stakeWithdrawAuthority';
isMut: false;
isSigner: false;
},
{
name: 'reservePda';
isMut: true;
isSigner: false;
},
{
name: 'msolMint';
isMut: true;
isSigner: false;
},
{
name: 'msolMintAuthority';
isMut: false;
isSigner: false;
},
{
name: 'treasuryMsolAccount';
isMut: true;
isSigner: false;
},
{
name: 'clock';
isMut: false;
isSigner: false;
},
{
name: 'stakeHistory';
isMut: false;
isSigner: false;
},
{
name: 'stakeProgram';
isMut: false;
isSigner: false;
},
{
name: 'tokenProgram';
isMut: false;
isSigner: false;
},
];
},
{
name: 'operationalSolAccount';
isMut: true;
isSigner: false;
},
{
name: 'systemProgram';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'stakeIndex';
type: 'u32';
},
];
},
{
name: 'deactivateStake';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'reservePda';
isMut: false;
isSigner: false;
},
{
name: 'validatorList';
isMut: true;
isSigner: false;
},
{
name: 'stakeList';
isMut: true;
isSigner: false;
},
{
name: 'stakeAccount';
isMut: true;
isSigner: false;
},
{
name: 'stakeDepositAuthority';
isMut: false;
isSigner: false;
},
{
name: 'splitStakeAccount';
isMut: true;
isSigner: true;
},
{
name: 'splitStakeRentPayer';
isMut: true;
isSigner: true;
},
{
name: 'clock';
isMut: false;
isSigner: false;
},
{
name: 'rent';
isMut: false;
isSigner: false;
},
{
name: 'epochSchedule';
isMut: false;
isSigner: false;
},
{
name: 'stakeHistory';
isMut: false;
isSigner: false;
},
{
name: 'systemProgram';
isMut: false;
isSigner: false;
},
{
name: 'stakeProgram';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'stakeIndex';
type: 'u32';
},
{
name: 'validatorIndex';
type: 'u32';
},
];
},
{
name: 'emergencyUnstake';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'validatorManagerAuthority';
isMut: false;
isSigner: true;
},
{
name: 'validatorList';
isMut: true;
isSigner: false;
},
{
name: 'stakeList';
isMut: true;
isSigner: false;
},
{
name: 'stakeAccount';
isMut: true;
isSigner: false;
},
{
name: 'stakeDepositAuthority';
isMut: false;
isSigner: false;
},
{
name: 'clock';
isMut: false;
isSigner: false;
},
{
name: 'stakeProgram';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'stakeIndex';
type: 'u32';
},
{
name: 'validatorIndex';
type: 'u32';
},
];
},
{
name: 'partialUnstake';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'validatorManagerAuthority';
isMut: false;
isSigner: true;
},
{
name: 'validatorList';
isMut: true;
isSigner: false;
},
{
name: 'stakeList';
isMut: true;
isSigner: false;
},
{
name: 'stakeAccount';
isMut: true;
isSigner: false;
},
{
name: 'stakeDepositAuthority';
isMut: false;
isSigner: false;
},
{
name: 'reservePda';
isMut: false;
isSigner: false;
},
{
name: 'splitStakeAccount';
isMut: true;
isSigner: true;
},
{
name: 'splitStakeRentPayer';
isMut: true;
isSigner: true;
},
{
name: 'clock';
isMut: false;
isSigner: false;
},
{
name: 'rent';
isMut: false;
isSigner: false;
},
{
name: 'stakeHistory';
isMut: false;
isSigner: false;
},
{
name: 'systemProgram';
isMut: false;
isSigner: false;
},
{
name: 'stakeProgram';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'stakeIndex';
type: 'u32';
},
{
name: 'validatorIndex';
type: 'u32';
},
{
name: 'desiredUnstakeAmount';
type: 'u64';
},
];
},
{
name: 'mergeStakes';
accounts: [
{
name: 'state';
isMut: true;
isSigner: false;
},
{
name: 'stakeList';
isMut: true;
isSigner: false;
},
{
name: 'validatorList';
isMut: true;
isSigner: false;
},
{
name: 'destinationStake';
isMut: true;
isSigner: false;
},
{
name: 'sourceStake';
isMut: true;
isSigner: false;
},
{
name: 'stakeDepositAuthority';
isMut: false;
isSigner: false;
},
{
name: 'stakeWithdrawAuthority';
isMut: false;
isSigner: false;
},
{
name: 'operationalSolAccount';
isMut: true;
isSigner: false;
},
{
name: 'clock';
isMut: false;
isSigner: false;
},
{
name: 'stakeHistory';
isMut: false;
isSigner: false;
},
{
name: 'stakeProgram';
isMut: false;
isSigner: false;
},
];
args: [
{
name: 'destinationStakeIndex';
type: 'u32';
},
{
name: 'sourceStakeIndex';
type: 'u32';
},
{
name: 'validatorIndex';
type: 'u32';
},
];
},
];
accounts: [
{
name: 'state';
type: {
kind: 'struct';
fields: [
{
name: 'msolMint';
type: 'publicKey';
},
{
name: 'adminAuthority';
type: 'publicKey';
},
{
name: 'operationalSolAccount';
type: 'publicKey';
},
{
name: 'treasuryMsolAccount';
type: 'publicKey';
},
{
name: 'reserveBumpSeed';
type: 'u8';
},
{
name: 'msolMintAuthorityBumpSeed';
type: 'u8';
},
{
name: 'rentExemptForTokenAcc';
type: 'u64';
},
{
name: 'rewardFee';
type: {
defined: 'Fee';
};
},
{
name: 'stakeSystem';
type: {
defined: 'StakeSystem';
};
},
{
name: 'validatorSystem';
type: {
defined: 'ValidatorSystem';
};
},
{
name: 'liqPool';
type: {
defined: 'LiqPool';
};
},
{
name: 'availableReserveBalance';
type: 'u64';
},
{
name: 'msolSupply';
type: 'u64';
},
{
name: 'msolPrice';
type: 'u64';
},
{
name: 'circulatingTicketCount';
docs: ['count tickets for delayed-unstake'];
type: 'u64';
},
{
name: 'circulatingTicketBalance';
docs: [
'total lamports amount of generated and not claimed yet tickets',
];
type: 'u64';
},
{
name: 'lentFromReserve';
type: 'u64';
},
{
name: 'minDeposit';
type: 'u64';
},
{
name: 'minWithdraw';
type: 'u64';
},
{
name: 'stakingSolCap';
type: 'u64';
},
{
name: 'emergencyCoolingDown';
type: 'u64';
},
];
};
},
{
name: 'ticketAccountData';
type: {
kind: 'struct';
fields: [
{
name: 'stateAddress';
type: 'publicKey';
},
{
name: 'beneficiary';
type: 'publicKey';
},
{
name: 'lamportsAmount';
type: 'u64';
},
{
name: 'createdEpoch';
type: 'u64';
},
];
};
},
];
types: [
{
name: 'LiqPool';
type: {
kind: 'struct';
fields: [
{
name: 'lpMint';
type: 'publicKey';
},
{
name: 'lpMintAuthorityBumpSeed';
type: 'u8';
},
{
name: 'solLegBumpSeed';
type: 'u8';
},
{
name: 'msolLegAuthorityBumpSeed';
type: 'u8';
},
{
name: 'msolLeg';
type: 'publicKey';
},
{
name: 'lpLiquidityTarget';
docs: [
'Liquidity target. If the Liquidity reach this amount, the fee reaches lp_min_discount_fee',
];
type: 'u64';
},
{
name: 'lpMaxFee';
docs: ['Liquidity pool max fee'];
type: {
defined: 'Fee';
};
},
{
name: 'lpMinFee';
docs: ['SOL/mSOL Liquidity pool min fee'];
type: {
defined: 'Fee';
};
},
{
name: 'treasuryCut';
docs: ['Treasury cut'];
type: {
defined: 'Fee';
};
},
{
name: 'lpSupply';
type: 'u64';
},
{
name: 'lentFromSolLeg';
type: 'u64';
},
{
name: 'liquiditySolCap';
type: 'u64';
},
];
};
},
{
name: 'List';
type: {
kind: 'struct';
fields: [
{
name: 'account';
type: 'publicKey';
},
{
name: 'itemSize';
type: 'u32';
},
{
name: 'count';
type: 'u32';
},
{
name: 'newAccount';
type: 'publicKey';
},
{
name: 'copiedCount';
type: 'u32';
},
];
};
},
{
name: 'StakeRecord';
type: {
kind: 'struct';
fields: [
{
name: 'stakeAccount';
type: 'publicKey';
},
{
name: 'lastUpdateDelegatedLamports';
type: 'u64';
},
{
name: 'lastUpdateEpoch';
type: 'u64';
},
{
name: 'isEmergencyUnstaking';
type: 'u8';
},
];
};
},
{
name: 'StakeSystem';
type: {
kind: 'struct';
fields: [
{
name: 'stakeList';
type: {
defined: 'List';
};
},
{
name: 'delayedUnstakeCoolingDown';
type: 'u64';
},
{
name: 'stakeDepositBumpSeed';
type: 'u8';
},
{
name: 'stakeWithdrawBumpSeed';
type: 'u8';
},
{
name: 'slotsForStakeDelta';
docs: [
'set by admin, how much slots before the end of the epoch, stake-delta can start',
];
type: 'u64';
},
{
name: 'lastStakeDeltaEpoch';
docs: [
'Marks the start of stake-delta operations, meaning that if somebody starts a delayed-unstake ticket',
'after this var is set with epoch_num the ticket will have epoch_created = current_epoch+1',
'(the user must wait one more epoch, because their unstake-delta will be execute in this epoch)',
];
type: 'u64';
},
{
name: 'minStake';
type: 'u64';
},
{
name: 'extraStakeDeltaRuns';
docs: [
'can be set by validator-manager-auth to allow a second run of stake-delta to stake late stakers in the last minute of the epoch',
"so we maximize user's rewards",
];
type: 'u32';
},
];
};
},
{
name: 'ValidatorRecord';
type: {
kind: 'struct';
fields: [
{
name: 'validatorAccount';
docs: ['Validator vote pubkey'];
type: 'publicKey';
},
{
name: 'activeBalance';
docs: ['Validator total balance in lamports'];
type: 'u64';
},
{
name: 'score';
type: 'u32';
},
{
name: 'lastStakeDeltaEpoch';
type: 'u64';
},
{
name: 'duplicationFlagBumpSeed';
type: 'u8';
},
];
};
},
{
name: 'ValidatorSystem';
type: {
kind: 'struct';
fields: [
{
name: 'validatorList';
type: {
defined: 'List';
};
},
{
name: 'managerAuthority';
type: 'publicKey';
},
{
name: 'totalValidatorScore';
type: 'u32';
},
{
name: 'totalActiveBalance';
docs: ['sum of all active lamports staked'];
type: 'u64';
},
{
name: 'autoAddValidatorEnabled';
docs: [
'allow & auto-add validator when a user deposits a stake-account of a non-listed validator',
];
type: 'u8';
},
];
};
},
{
name: 'Fee';
type: {
kind: 'struct';
fields: [
{
name: 'basisPoints';
type: 'u32';
},
];
};
},
{
name: 'InitializeData';
type: {
kind: 'struct';
fields: [
{
name: 'adminAuthority';
type: 'publicKey';
},
{
name: 'validatorManagerAuthority';
type: 'publicKey';
},
{
name: 'minStake';
type: 'u64';
},
{
name: 'rewardFee';
type: {
defined: 'Fee';
};
},
{
name: 'liqPool';
type: {
defined: 'LiqPoolInitializeData';
};
},
{
name: 'additionalStakeRecordSpace';
type: 'u32';
},
{
name: 'additionalValidatorRecordSpace';
type: 'u32';
},
{
name: 'slotsForStakeDelta';
type: 'u64';
},
];
};
},
{
name: 'LiqPoolInitializeData';
type: {
kind: 'struct';
fields: [
{
name: 'lpLiquidityTarget';
type: 'u64';
},
{
name: 'lpMaxFee';
type: {
defined: 'Fee';
};
},
{
name: 'lpMinFee';
type: {
defined: 'Fee';
};
},
{
name: 'lpTreasuryCut';
type: {
defined: 'Fee';
};
},
];
};
},
{
name: 'ChangeAuthorityData';
type: {
kind: 'struct';
fields: [
{
name: 'admin';
type: {
option: 'publicKey';
};
},
{
name: 'validatorManager';
type: {
option: 'publicKey';
};
},
{
name: 'operationalSolAccount';
type: {
option: 'publicKey';
};
},
{
name: 'treasuryMsolAccount';
type: {
option: 'publicKey';
};
},
];
};
},
{
name: 'ConfigLpParams';
type: {
kind: 'struct';
fields: [
{
name: 'minFee';
type: {
option: {
defined: 'Fee';
};
};
},
{
name: 'maxFee';
type: {
option: {
defined: 'Fee';
};
};
},
{
name: 'liquidityTarget';
type: {
option: 'u64';
};
},
{
name: 'treasuryCut';
type: {
option: {
defined: 'Fee';
};
};
},
];
};
},
{
name: 'ConfigMarinadeParams';
type: {
kind: 'struct';
fields: [
{
name: 'rewardsFee';
type: {
option: {
defined: 'Fee';
};
};
},
{
name: 'slotsForStakeDelta';
type: {
option: 'u64';
};
},
{
name: 'minStake';
type: {
option: 'u64';
};
},
{
name: 'minDeposit';
type: {
option: 'u64';
};
},
{
name: 'minWithdraw';
type: {
option: 'u64';
};
},
{
name: 'stakingSolCap';
type: {
option: 'u64';
};
},
{
name: 'liquiditySolCap';
type: {
option: 'u64';
};
},
{
name: 'autoAddValidatorEnabled';
type: {
option: 'bool';
};
},
];
};
},
{
name: 'CommonError';
type: {
kind: 'enum';
variants: [
{
name: 'WrongReserveOwner';
},
{
name: 'NonEmptyReserveData';
},
{
name: 'InvalidInitialReserveLamports';
},
{
name: 'ZeroValidatorChunkSize';
},
{
name: 'TooBigValidatorChunkSize';
},
{
name: 'ZeroCreditChunkSize';
},
{
name: 'TooBigCreditChunkSize';
},
{
name: 'TooLowCreditFee';
},
{
name: 'InvalidMintAuthority';
},
{
name: 'MintHasInitialSupply';
},
{
name: 'InvalidOwnerFeeState';
},
{
name: 'InvalidProgramId';
},
{
name: 'UnexpectedAccount';
},
{
name: 'CalculationFailure';
},
{
name: 'AccountWithLockup';
},
{
name: 'NumberTooLow';
},
{
name: 'NumberTooHigh';
},
{
name: 'FeeTooHigh';
},
{
name: 'FeesWrongWayRound';
},
{
name: 'LiquidityTargetTooLow';
},
{
name: 'TicketNotDue';
},
{
name: 'TicketNotReady';
},
{
name: 'WrongBeneficiary';
},
{
name: 'StakeAccountNotUpdatedYet';
},
{
name: 'StakeNotDelegated';
},
{
name: 'StakeAccountIsEmergencyUnstaking';
},
{
name: 'InsufficientLiquidity';
},
{
name: 'InvalidValidator';
},
];
};
},
];
};
export const IDL: MarinadeFinance = {
version: '0.1.0',
name: 'marinade_finance',
instructions: [
{
name: 'initialize',
accounts: [
{
name: 'creatorAuthority',
isMut: false,
isSigner: true,
},
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'reservePda',
isMut: false,
isSigner: false,
},
{
name: 'stakeList',
isMut: true,
isSigner: false,
},
{
name: 'validatorList',
isMut: true,
isSigner: false,
},
{
name: 'msolMint',
isMut: false,
isSigner: false,
},
{
name: 'operationalSolAccount',
isMut: false,
isSigner: false,
},
{
name: 'liqPool',
accounts: [
{
name: 'lpMint',
isMut: false,
isSigner: false,
},
{
name: 'solLegPda',
isMut: false,
isSigner: false,
},
{
name: 'msolLeg',
isMut: false,
isSigner: false,
},
],
},
{
name: 'treasuryMsolAccount',
isMut: false,
isSigner: false,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
{
name: 'rent',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'data',
type: {
defined: 'InitializeData',
},
},
],
},
{
name: 'changeAuthority',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'adminAuthority',
isMut: false,
isSigner: true,
},
],
args: [
{
name: 'data',
type: {
defined: 'ChangeAuthorityData',
},
},
],
},
{
name: 'addValidator',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'managerAuthority',
isMut: false,
isSigner: true,
},
{
name: 'validatorList',
isMut: true,
isSigner: false,
},
{
name: 'validatorVote',
isMut: false,
isSigner: false,
},
{
name: 'duplicationFlag',
isMut: true,
isSigner: false,
},
{
name: 'rentPayer',
isMut: true,
isSigner: true,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
{
name: 'rent',
isMut: false,
isSigner: false,
},
{
name: 'systemProgram',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'score',
type: 'u32',
},
],
},
{
name: 'removeValidator',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'managerAuthority',
isMut: false,
isSigner: true,
},
{
name: 'validatorList',
isMut: true,
isSigner: false,
},
{
name: 'duplicationFlag',
isMut: true,
isSigner: false,
},
{
name: 'operationalSolAccount',
isMut: true,
isSigner: false,
},
],
args: [
{
name: 'index',
type: 'u32',
},
{
name: 'validatorVote',
type: 'publicKey',
},
],
},
{
name: 'setValidatorScore',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'managerAuthority',
isMut: false,
isSigner: true,
},
{
name: 'validatorList',
isMut: true,
isSigner: false,
},
],
args: [
{
name: 'index',
type: 'u32',
},
{
name: 'validatorVote',
type: 'publicKey',
},
{
name: 'score',
type: 'u32',
},
],
},
{
name: 'configValidatorSystem',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'managerAuthority',
isMut: false,
isSigner: true,
},
],
args: [
{
name: 'extraRuns',
type: 'u32',
},
],
},
{
name: 'deposit',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'msolMint',
isMut: true,
isSigner: false,
},
{
name: 'liqPoolSolLegPda',
isMut: true,
isSigner: false,
},
{
name: 'liqPoolMsolLeg',
isMut: true,
isSigner: false,
},
{
name: 'liqPoolMsolLegAuthority',
isMut: false,
isSigner: false,
},
{
name: 'reservePda',
isMut: true,
isSigner: false,
},
{
name: 'transferFrom',
isMut: true,
isSigner: true,
},
{
name: 'mintTo',
isMut: true,
isSigner: false,
},
{
name: 'msolMintAuthority',
isMut: false,
isSigner: false,
},
{
name: 'systemProgram',
isMut: false,
isSigner: false,
},
{
name: 'tokenProgram',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'lamports',
type: 'u64',
},
],
},
{
name: 'depositStakeAccount',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'validatorList',
isMut: true,
isSigner: false,
},
{
name: 'stakeList',
isMut: true,
isSigner: false,
},
{
name: 'stakeAccount',
isMut: true,
isSigner: false,
},
{
name: 'stakeAuthority',
isMut: false,
isSigner: true,
},
{
name: 'duplicationFlag',
isMut: true,
isSigner: false,
},
{
name: 'rentPayer',
isMut: true,
isSigner: true,
},
{
name: 'msolMint',
isMut: true,
isSigner: false,
},
{
name: 'mintTo',
isMut: true,
isSigner: false,
},
{
name: 'msolMintAuthority',
isMut: false,
isSigner: false,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
{
name: 'rent',
isMut: false,
isSigner: false,
},
{
name: 'systemProgram',
isMut: false,
isSigner: false,
},
{
name: 'tokenProgram',
isMut: false,
isSigner: false,
},
{
name: 'stakeProgram',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'validatorIndex',
type: 'u32',
},
],
},
{
name: 'liquidUnstake',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'msolMint',
isMut: true,
isSigner: false,
},
{
name: 'liqPoolSolLegPda',
isMut: true,
isSigner: false,
},
{
name: 'liqPoolMsolLeg',
isMut: true,
isSigner: false,
},
{
name: 'treasuryMsolAccount',
isMut: true,
isSigner: false,
},
{
name: 'getMsolFrom',
isMut: true,
isSigner: false,
},
{
name: 'getMsolFromAuthority',
isMut: false,
isSigner: true,
},
{
name: 'transferSolTo',
isMut: true,
isSigner: false,
},
{
name: 'systemProgram',
isMut: false,
isSigner: false,
},
{
name: 'tokenProgram',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'msolAmount',
type: 'u64',
},
],
},
{
name: 'addLiquidity',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'lpMint',
isMut: true,
isSigner: false,
},
{
name: 'lpMintAuthority',
isMut: false,
isSigner: false,
},
{
name: 'liqPoolMsolLeg',
isMut: false,
isSigner: false,
},
{
name: 'liqPoolSolLegPda',
isMut: true,
isSigner: false,
},
{
name: 'transferFrom',
isMut: true,
isSigner: true,
},
{
name: 'mintTo',
isMut: true,
isSigner: false,
},
{
name: 'systemProgram',
isMut: false,
isSigner: false,
},
{
name: 'tokenProgram',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'lamports',
type: 'u64',
},
],
},
{
name: 'removeLiquidity',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'lpMint',
isMut: true,
isSigner: false,
},
{
name: 'burnFrom',
isMut: true,
isSigner: false,
},
{
name: 'burnFromAuthority',
isMut: false,
isSigner: true,
},
{
name: 'transferSolTo',
isMut: true,
isSigner: false,
},
{
name: 'transferMsolTo',
isMut: true,
isSigner: false,
},
{
name: 'liqPoolSolLegPda',
isMut: true,
isSigner: false,
},
{
name: 'liqPoolMsolLeg',
isMut: true,
isSigner: false,
},
{
name: 'liqPoolMsolLegAuthority',
isMut: false,
isSigner: false,
},
{
name: 'systemProgram',
isMut: false,
isSigner: false,
},
{
name: 'tokenProgram',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'tokens',
type: 'u64',
},
],
},
{
name: 'configLp',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'adminAuthority',
isMut: false,
isSigner: true,
},
],
args: [
{
name: 'params',
type: {
defined: 'ConfigLpParams',
},
},
],
},
{
name: 'configMarinade',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'adminAuthority',
isMut: false,
isSigner: true,
},
],
args: [
{
name: 'params',
type: {
defined: 'ConfigMarinadeParams',
},
},
],
},
{
name: 'orderUnstake',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'msolMint',
isMut: true,
isSigner: false,
},
{
name: 'burnMsolFrom',
isMut: true,
isSigner: false,
},
{
name: 'burnMsolAuthority',
isMut: false,
isSigner: true,
},
{
name: 'newTicketAccount',
isMut: true,
isSigner: false,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
{
name: 'rent',
isMut: false,
isSigner: false,
},
{
name: 'tokenProgram',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'msolAmount',
type: 'u64',
},
],
},
{
name: 'claim',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'reservePda',
isMut: true,
isSigner: false,
},
{
name: 'ticketAccount',
isMut: true,
isSigner: false,
},
{
name: 'transferSolTo',
isMut: true,
isSigner: false,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
{
name: 'systemProgram',
isMut: false,
isSigner: false,
},
],
args: [],
},
{
name: 'stakeReserve',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'validatorList',
isMut: true,
isSigner: false,
},
{
name: 'stakeList',
isMut: true,
isSigner: false,
},
{
name: 'validatorVote',
isMut: true,
isSigner: false,
},
{
name: 'reservePda',
isMut: true,
isSigner: false,
},
{
name: 'stakeAccount',
isMut: true,
isSigner: false,
},
{
name: 'stakeDepositAuthority',
isMut: false,
isSigner: false,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
{
name: 'epochSchedule',
isMut: false,
isSigner: false,
},
{
name: 'rent',
isMut: false,
isSigner: false,
},
{
name: 'stakeHistory',
isMut: false,
isSigner: false,
},
{
name: 'stakeConfig',
isMut: false,
isSigner: false,
},
{
name: 'systemProgram',
isMut: false,
isSigner: false,
},
{
name: 'stakeProgram',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'validatorIndex',
type: 'u32',
},
],
},
{
name: 'updateActive',
accounts: [
{
name: 'common',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'stakeList',
isMut: true,
isSigner: false,
},
{
name: 'stakeAccount',
isMut: true,
isSigner: false,
},
{
name: 'stakeWithdrawAuthority',
isMut: false,
isSigner: false,
},
{
name: 'reservePda',
isMut: true,
isSigner: false,
},
{
name: 'msolMint',
isMut: true,
isSigner: false,
},
{
name: 'msolMintAuthority',
isMut: false,
isSigner: false,
},
{
name: 'treasuryMsolAccount',
isMut: true,
isSigner: false,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
{
name: 'stakeHistory',
isMut: false,
isSigner: false,
},
{
name: 'stakeProgram',
isMut: false,
isSigner: false,
},
{
name: 'tokenProgram',
isMut: false,
isSigner: false,
},
],
},
{
name: 'validatorList',
isMut: true,
isSigner: false,
},
],
args: [
{
name: 'stakeIndex',
type: 'u32',
},
{
name: 'validatorIndex',
type: 'u32',
},
],
},
{
name: 'updateDeactivated',
accounts: [
{
name: 'common',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'stakeList',
isMut: true,
isSigner: false,
},
{
name: 'stakeAccount',
isMut: true,
isSigner: false,
},
{
name: 'stakeWithdrawAuthority',
isMut: false,
isSigner: false,
},
{
name: 'reservePda',
isMut: true,
isSigner: false,
},
{
name: 'msolMint',
isMut: true,
isSigner: false,
},
{
name: 'msolMintAuthority',
isMut: false,
isSigner: false,
},
{
name: 'treasuryMsolAccount',
isMut: true,
isSigner: false,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
{
name: 'stakeHistory',
isMut: false,
isSigner: false,
},
{
name: 'stakeProgram',
isMut: false,
isSigner: false,
},
{
name: 'tokenProgram',
isMut: false,
isSigner: false,
},
],
},
{
name: 'operationalSolAccount',
isMut: true,
isSigner: false,
},
{
name: 'systemProgram',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'stakeIndex',
type: 'u32',
},
],
},
{
name: 'deactivateStake',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'reservePda',
isMut: false,
isSigner: false,
},
{
name: 'validatorList',
isMut: true,
isSigner: false,
},
{
name: 'stakeList',
isMut: true,
isSigner: false,
},
{
name: 'stakeAccount',
isMut: true,
isSigner: false,
},
{
name: 'stakeDepositAuthority',
isMut: false,
isSigner: false,
},
{
name: 'splitStakeAccount',
isMut: true,
isSigner: true,
},
{
name: 'splitStakeRentPayer',
isMut: true,
isSigner: true,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
{
name: 'rent',
isMut: false,
isSigner: false,
},
{
name: 'epochSchedule',
isMut: false,
isSigner: false,
},
{
name: 'stakeHistory',
isMut: false,
isSigner: false,
},
{
name: 'systemProgram',
isMut: false,
isSigner: false,
},
{
name: 'stakeProgram',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'stakeIndex',
type: 'u32',
},
{
name: 'validatorIndex',
type: 'u32',
},
],
},
{
name: 'emergencyUnstake',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'validatorManagerAuthority',
isMut: false,
isSigner: true,
},
{
name: 'validatorList',
isMut: true,
isSigner: false,
},
{
name: 'stakeList',
isMut: true,
isSigner: false,
},
{
name: 'stakeAccount',
isMut: true,
isSigner: false,
},
{
name: 'stakeDepositAuthority',
isMut: false,
isSigner: false,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
{
name: 'stakeProgram',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'stakeIndex',
type: 'u32',
},
{
name: 'validatorIndex',
type: 'u32',
},
],
},
{
name: 'partialUnstake',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'validatorManagerAuthority',
isMut: false,
isSigner: true,
},
{
name: 'validatorList',
isMut: true,
isSigner: false,
},
{
name: 'stakeList',
isMut: true,
isSigner: false,
},
{
name: 'stakeAccount',
isMut: true,
isSigner: false,
},
{
name: 'stakeDepositAuthority',
isMut: false,
isSigner: false,
},
{
name: 'reservePda',
isMut: false,
isSigner: false,
},
{
name: 'splitStakeAccount',
isMut: true,
isSigner: true,
},
{
name: 'splitStakeRentPayer',
isMut: true,
isSigner: true,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
{
name: 'rent',
isMut: false,
isSigner: false,
},
{
name: 'stakeHistory',
isMut: false,
isSigner: false,
},
{
name: 'systemProgram',
isMut: false,
isSigner: false,
},
{
name: 'stakeProgram',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'stakeIndex',
type: 'u32',
},
{
name: 'validatorIndex',
type: 'u32',
},
{
name: 'desiredUnstakeAmount',
type: 'u64',
},
],
},
{
name: 'mergeStakes',
accounts: [
{
name: 'state',
isMut: true,
isSigner: false,
},
{
name: 'stakeList',
isMut: true,
isSigner: false,
},
{
name: 'validatorList',
isMut: true,
isSigner: false,
},
{
name: 'destinationStake',
isMut: true,
isSigner: false,
},
{
name: 'sourceStake',
isMut: true,
isSigner: false,
},
{
name: 'stakeDepositAuthority',
isMut: false,
isSigner: false,
},
{
name: 'stakeWithdrawAuthority',
isMut: false,
isSigner: false,
},
{
name: 'operationalSolAccount',
isMut: true,
isSigner: false,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
{
name: 'stakeHistory',
isMut: false,
isSigner: false,
},
{
name: 'stakeProgram',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'destinationStakeIndex',
type: 'u32',
},
{
name: 'sourceStakeIndex',
type: 'u32',
},
{
name: 'validatorIndex',
type: 'u32',
},
],
},
],
accounts: [
{
name: 'state',
type: {
kind: 'struct',
fields: [
{
name: 'msolMint',
type: 'publicKey',
},
{
name: 'adminAuthority',
type: 'publicKey',
},
{
name: 'operationalSolAccount',
type: 'publicKey',
},
{
name: 'treasuryMsolAccount',
type: 'publicKey',
},
{
name: 'reserveBumpSeed',
type: 'u8',
},
{
name: 'msolMintAuthorityBumpSeed',
type: 'u8',
},
{
name: 'rentExemptForTokenAcc',
type: 'u64',
},
{
name: 'rewardFee',
type: {
defined: 'Fee',
},
},
{
name: 'stakeSystem',
type: {
defined: 'StakeSystem',
},
},
{
name: 'validatorSystem',
type: {
defined: 'ValidatorSystem',
},
},
{
name: 'liqPool',
type: {
defined: 'LiqPool',
},
},
{
name: 'availableReserveBalance',
type: 'u64',
},
{
name: 'msolSupply',
type: 'u64',
},
{
name: 'msolPrice',
type: 'u64',
},
{
name: 'circulatingTicketCount',
docs: ['count tickets for delayed-unstake'],
type: 'u64',
},
{
name: 'circulatingTicketBalance',
docs: [
'total lamports amount of generated and not claimed yet tickets',
],
type: 'u64',
},
{
name: 'lentFromReserve',
type: 'u64',
},
{
name: 'minDeposit',
type: 'u64',
},
{
name: 'minWithdraw',
type: 'u64',
},
{
name: 'stakingSolCap',
type: 'u64',
},
{
name: 'emergencyCoolingDown',
type: 'u64',
},
],
},
},
{
name: 'ticketAccountData',
type: {
kind: 'struct',
fields: [
{
name: 'stateAddress',
type: 'publicKey',
},
{
name: 'beneficiary',
type: 'publicKey',
},
{
name: 'lamportsAmount',
type: 'u64',
},
{
name: 'createdEpoch',
type: 'u64',
},
],
},
},
],
types: [
{
name: 'LiqPool',
type: {
kind: 'struct',
fields: [
{
name: 'lpMint',
type: 'publicKey',
},
{
name: 'lpMintAuthorityBumpSeed',
type: 'u8',
},
{
name: 'solLegBumpSeed',
type: 'u8',
},
{
name: 'msolLegAuthorityBumpSeed',
type: 'u8',
},
{
name: 'msolLeg',
type: 'publicKey',
},
{
name: 'lpLiquidityTarget',
docs: [
'Liquidity target. If the Liquidity reach this amount, the fee reaches lp_min_discount_fee',
],
type: 'u64',
},
{
name: 'lpMaxFee',
docs: ['Liquidity pool max fee'],
type: {
defined: 'Fee',
},
},
{
name: 'lpMinFee',
docs: ['SOL/mSOL Liquidity pool min fee'],
type: {
defined: 'Fee',
},
},
{
name: 'treasuryCut',
docs: ['Treasury cut'],
type: {
defined: 'Fee',
},
},
{
name: 'lpSupply',
type: 'u64',
},
{
name: 'lentFromSolLeg',
type: 'u64',
},
{
name: 'liquiditySolCap',
type: 'u64',
},
],
},
},
{
name: 'List',
type: {
kind: 'struct',
fields: [
{
name: 'account',
type: 'publicKey',
},
{
name: 'itemSize',
type: 'u32',
},
{
name: 'count',
type: 'u32',
},
{
name: 'newAccount',
type: 'publicKey',
},
{
name: 'copiedCount',
type: 'u32',
},
],
},
},
{
name: 'StakeRecord',
type: {
kind: 'struct',
fields: [
{
name: 'stakeAccount',
type: 'publicKey',
},
{
name: 'lastUpdateDelegatedLamports',
type: 'u64',
},
{
name: 'lastUpdateEpoch',
type: 'u64',
},
{
name: 'isEmergencyUnstaking',
type: 'u8',
},
],
},
},
{
name: 'StakeSystem',
type: {
kind: 'struct',
fields: [
{
name: 'stakeList',
type: {
defined: 'List',
},
},
{
name: 'delayedUnstakeCoolingDown',
type: 'u64',
},
{
name: 'stakeDepositBumpSeed',
type: 'u8',
},
{
name: 'stakeWithdrawBumpSeed',
type: 'u8',
},
{
name: 'slotsForStakeDelta',
docs: [
'set by admin, how much slots before the end of the epoch, stake-delta can start',
],
type: 'u64',
},
{
name: 'lastStakeDeltaEpoch',
docs: [
'Marks the start of stake-delta operations, meaning that if somebody starts a delayed-unstake ticket',
'after this var is set with epoch_num the ticket will have epoch_created = current_epoch+1',
'(the user must wait one more epoch, because their unstake-delta will be execute in this epoch)',
],
type: 'u64',
},
{
name: 'minStake',
type: 'u64',
},
{
name: 'extraStakeDeltaRuns',
docs: [
'can be set by validator-manager-auth to allow a second run of stake-delta to stake late stakers in the last minute of the epoch',
"so we maximize user's rewards",
],
type: 'u32',
},
],
},
},
{
name: 'ValidatorRecord',
type: {
kind: 'struct',
fields: [
{
name: 'validatorAccount',
docs: ['Validator vote pubkey'],
type: 'publicKey',
},
{
name: 'activeBalance',
docs: ['Validator total balance in lamports'],
type: 'u64',
},
{
name: 'score',
type: 'u32',
},
{
name: 'lastStakeDeltaEpoch',
type: 'u64',
},
{
name: 'duplicationFlagBumpSeed',
type: 'u8',
},
],
},
},
{
name: 'ValidatorSystem',
type: {
kind: 'struct',
fields: [
{
name: 'validatorList',
type: {
defined: 'List',
},
},
{
name: 'managerAuthority',
type: 'publicKey',
},
{
name: 'totalValidatorScore',
type: 'u32',
},
{
name: 'totalActiveBalance',
docs: ['sum of all active lamports staked'],
type: 'u64',
},
{
name: 'autoAddValidatorEnabled',
docs: [
'allow & auto-add validator when a user deposits a stake-account of a non-listed validator',
],
type: 'u8',
},
],
},
},
{
name: 'Fee',
type: {
kind: 'struct',
fields: [
{
name: 'basisPoints',
type: 'u32',
},
],
},
},
{
name: 'InitializeData',
type: {
kind: 'struct',
fields: [
{
name: 'adminAuthority',
type: 'publicKey',
},
{
name: 'validatorManagerAuthority',
type: 'publicKey',
},
{
name: 'minStake',
type: 'u64',
},
{
name: 'rewardFee',
type: {
defined: 'Fee',
},
},
{
name: 'liqPool',
type: {
defined: 'LiqPoolInitializeData',
},
},
{
name: 'additionalStakeRecordSpace',
type: 'u32',
},
{
name: 'additionalValidatorRecordSpace',
type: 'u32',
},
{
name: 'slotsForStakeDelta',
type: 'u64',
},
],
},
},
{
name: 'LiqPoolInitializeData',
type: {
kind: 'struct',
fields: [
{
name: 'lpLiquidityTarget',
type: 'u64',
},
{
name: 'lpMaxFee',
type: {
defined: 'Fee',
},
},
{
name: 'lpMinFee',
type: {
defined: 'Fee',
},
},
{
name: 'lpTreasuryCut',
type: {
defined: 'Fee',
},
},
],
},
},
{
name: 'ChangeAuthorityData',
type: {
kind: 'struct',
fields: [
{
name: 'admin',
type: {
option: 'publicKey',
},
},
{
name: 'validatorManager',
type: {
option: 'publicKey',
},
},
{
name: 'operationalSolAccount',
type: {
option: 'publicKey',
},
},
{
name: 'treasuryMsolAccount',
type: {
option: 'publicKey',
},
},
],
},
},
{
name: 'ConfigLpParams',
type: {
kind: 'struct',
fields: [
{
name: 'minFee',
type: {
option: {
defined: 'Fee',
},
},
},
{
name: 'maxFee',
type: {
option: {
defined: 'Fee',
},
},
},
{
name: 'liquidityTarget',
type: {
option: 'u64',
},
},
{
name: 'treasuryCut',
type: {
option: {
defined: 'Fee',
},
},
},
],
},
},
{
name: 'ConfigMarinadeParams',
type: {
kind: 'struct',
fields: [
{
name: 'rewardsFee',
type: {
option: {
defined: 'Fee',
},
},
},
{
name: 'slotsForStakeDelta',
type: {
option: 'u64',
},
},
{
name: 'minStake',
type: {
option: 'u64',
},
},
{
name: 'minDeposit',
type: {
option: 'u64',
},
},
{
name: 'minWithdraw',
type: {
option: 'u64',
},
},
{
name: 'stakingSolCap',
type: {
option: 'u64',
},
},
{
name: 'liquiditySolCap',
type: {
option: 'u64',
},
},
{
name: 'autoAddValidatorEnabled',
type: {
option: 'bool',
},
},
],
},
},
{
name: 'CommonError',
type: {
kind: 'enum',
variants: [
{
name: 'WrongReserveOwner',
},
{
name: 'NonEmptyReserveData',
},
{
name: 'InvalidInitialReserveLamports',
},
{
name: 'ZeroValidatorChunkSize',
},
{
name: 'TooBigValidatorChunkSize',
},
{
name: 'ZeroCreditChunkSize',
},
{
name: 'TooBigCreditChunkSize',
},
{
name: 'TooLowCreditFee',
},
{
name: 'InvalidMintAuthority',
},
{
name: 'MintHasInitialSupply',
},
{
name: 'InvalidOwnerFeeState',
},
{
name: 'InvalidProgramId',
},
{
name: 'UnexpectedAccount',
},
{
name: 'CalculationFailure',
},
{
name: 'AccountWithLockup',
},
{
name: 'NumberTooLow',
},
{
name: 'NumberTooHigh',
},
{
name: 'FeeTooHigh',
},
{
name: 'FeesWrongWayRound',
},
{
name: 'LiquidityTargetTooLow',
},
{
name: 'TicketNotDue',
},
{
name: 'TicketNotReady',
},
{
name: 'WrongBeneficiary',
},
{
name: 'StakeAccountNotUpdatedYet',
},
{
name: 'StakeNotDelegated',
},
{
name: 'StakeAccountIsEmergencyUnstaking',
},
{
name: 'InsufficientLiquidity',
},
{
name: 'InvalidValidator',
},
],
},
},
],
};
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/marinade/index.ts
|
import { AnchorProvider, BN, Program } from '@coral-xyz/anchor';
import { MarinadeFinance, IDL } from './types';
import {
PublicKey,
SystemProgram,
TransactionInstruction,
} from '@solana/web3.js';
import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
const marinadeFinanceProgramId = new PublicKey(
'MarBmsSgKXdrN1egZf5sqe1TMai9K1rChYNDJgjq7aD'
);
export function getMarinadeFinanceProgram(
provider: AnchorProvider
): Program<MarinadeFinance> {
return new Program<MarinadeFinance>(IDL, marinadeFinanceProgramId, provider);
}
export function getMarinadeDepositIx({
program,
amount,
mSOLAccount,
transferFrom,
}: {
amount: BN;
mSOLAccount: PublicKey;
transferFrom: PublicKey;
program: Program<MarinadeFinance>;
}): Promise<TransactionInstruction> {
return program.methods
.deposit(amount)
.accountsStrict({
reservePda: new PublicKey('Du3Ysj1wKbxPKkuPPnvzQLQh8oMSVifs3jGZjJWXFmHN'),
state: new PublicKey('8szGkuLTAux9XMgZ2vtY39jVSowEcpBfFfD8hXSEqdGC'),
msolMint: new PublicKey('mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So'),
msolMintAuthority: new PublicKey(
'3JLPCS1qM2zRw3Dp6V4hZnYHd4toMNPkNesXdX9tg6KM'
),
liqPoolMsolLegAuthority: new PublicKey(
'EyaSjUtSgo9aRD1f8LWXwdvkpDTmXAW54yoSHZRF14WL'
),
liqPoolMsolLeg: new PublicKey(
'7GgPYjS5Dza89wV6FpZ23kUJRG5vbQ1GM25ezspYFSoE'
),
liqPoolSolLegPda: new PublicKey(
'UefNb6z6yvArqe4cJHTXCqStRsKmWhGxnZzuHbikP5Q'
),
mintTo: mSOLAccount,
transferFrom,
systemProgram: SystemProgram.programId,
tokenProgram: TOKEN_PROGRAM_ID,
})
.instruction();
}
export async function getMarinadeMSolPrice(
program: Program<MarinadeFinance>
): Promise<number> {
const state = await program.account.state.fetch(
new PublicKey('8szGkuLTAux9XMgZ2vtY39jVSowEcpBfFfD8hXSEqdGC')
);
return state.msolPrice.toNumber() / 0x1_0000_0000;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/marinade
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/marinade/idl/idl.json
|
{
"version": "0.1.0",
"name": "marinade_finance",
"instructions": [
{
"name": "initialize",
"accounts": [
{
"name": "creatorAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "reservePda",
"isMut": false,
"isSigner": false
},
{
"name": "stakeList",
"isMut": true,
"isSigner": false
},
{
"name": "validatorList",
"isMut": true,
"isSigner": false
},
{
"name": "msolMint",
"isMut": false,
"isSigner": false
},
{
"name": "operationalSolAccount",
"isMut": false,
"isSigner": false
},
{
"name": "liqPool",
"accounts": [
{
"name": "lpMint",
"isMut": false,
"isSigner": false
},
{
"name": "solLegPda",
"isMut": false,
"isSigner": false
},
{
"name": "msolLeg",
"isMut": false,
"isSigner": false
}
]
},
{
"name": "treasuryMsolAccount",
"isMut": false,
"isSigner": false
},
{
"name": "clock",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "data",
"type": {
"defined": "InitializeData"
}
}
]
},
{
"name": "changeAuthority",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "adminAuthority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "data",
"type": {
"defined": "ChangeAuthorityData"
}
}
]
},
{
"name": "addValidator",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "managerAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "validatorList",
"isMut": true,
"isSigner": false
},
{
"name": "validatorVote",
"isMut": false,
"isSigner": false
},
{
"name": "duplicationFlag",
"isMut": true,
"isSigner": false
},
{
"name": "rentPayer",
"isMut": true,
"isSigner": true
},
{
"name": "clock",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "score",
"type": "u32"
}
]
},
{
"name": "removeValidator",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "managerAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "validatorList",
"isMut": true,
"isSigner": false
},
{
"name": "duplicationFlag",
"isMut": true,
"isSigner": false
},
{
"name": "operationalSolAccount",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "index",
"type": "u32"
},
{
"name": "validatorVote",
"type": "publicKey"
}
]
},
{
"name": "setValidatorScore",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "managerAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "validatorList",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "index",
"type": "u32"
},
{
"name": "validatorVote",
"type": "publicKey"
},
{
"name": "score",
"type": "u32"
}
]
},
{
"name": "configValidatorSystem",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "managerAuthority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "extraRuns",
"type": "u32"
}
]
},
{
"name": "deposit",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "msolMint",
"isMut": true,
"isSigner": false
},
{
"name": "liqPoolSolLegPda",
"isMut": true,
"isSigner": false
},
{
"name": "liqPoolMsolLeg",
"isMut": true,
"isSigner": false
},
{
"name": "liqPoolMsolLegAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "reservePda",
"isMut": true,
"isSigner": false
},
{
"name": "transferFrom",
"isMut": true,
"isSigner": true
},
{
"name": "mintTo",
"isMut": true,
"isSigner": false
},
{
"name": "msolMintAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "lamports",
"type": "u64"
}
]
},
{
"name": "depositStakeAccount",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "validatorList",
"isMut": true,
"isSigner": false
},
{
"name": "stakeList",
"isMut": true,
"isSigner": false
},
{
"name": "stakeAccount",
"isMut": true,
"isSigner": false
},
{
"name": "stakeAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "duplicationFlag",
"isMut": true,
"isSigner": false
},
{
"name": "rentPayer",
"isMut": true,
"isSigner": true
},
{
"name": "msolMint",
"isMut": true,
"isSigner": false
},
{
"name": "mintTo",
"isMut": true,
"isSigner": false
},
{
"name": "msolMintAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "clock",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "stakeProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "validatorIndex",
"type": "u32"
}
]
},
{
"name": "liquidUnstake",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "msolMint",
"isMut": true,
"isSigner": false
},
{
"name": "liqPoolSolLegPda",
"isMut": true,
"isSigner": false
},
{
"name": "liqPoolMsolLeg",
"isMut": true,
"isSigner": false
},
{
"name": "treasuryMsolAccount",
"isMut": true,
"isSigner": false
},
{
"name": "getMsolFrom",
"isMut": true,
"isSigner": false
},
{
"name": "getMsolFromAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "transferSolTo",
"isMut": true,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "msolAmount",
"type": "u64"
}
]
},
{
"name": "addLiquidity",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "lpMint",
"isMut": true,
"isSigner": false
},
{
"name": "lpMintAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "liqPoolMsolLeg",
"isMut": false,
"isSigner": false
},
{
"name": "liqPoolSolLegPda",
"isMut": true,
"isSigner": false
},
{
"name": "transferFrom",
"isMut": true,
"isSigner": true
},
{
"name": "mintTo",
"isMut": true,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "lamports",
"type": "u64"
}
]
},
{
"name": "removeLiquidity",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "lpMint",
"isMut": true,
"isSigner": false
},
{
"name": "burnFrom",
"isMut": true,
"isSigner": false
},
{
"name": "burnFromAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "transferSolTo",
"isMut": true,
"isSigner": false
},
{
"name": "transferMsolTo",
"isMut": true,
"isSigner": false
},
{
"name": "liqPoolSolLegPda",
"isMut": true,
"isSigner": false
},
{
"name": "liqPoolMsolLeg",
"isMut": true,
"isSigner": false
},
{
"name": "liqPoolMsolLegAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "tokens",
"type": "u64"
}
]
},
{
"name": "configLp",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "adminAuthority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "ConfigLpParams"
}
}
]
},
{
"name": "configMarinade",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "adminAuthority",
"isMut": false,
"isSigner": true
}
],
"args": [
{
"name": "params",
"type": {
"defined": "ConfigMarinadeParams"
}
}
]
},
{
"name": "orderUnstake",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "msolMint",
"isMut": true,
"isSigner": false
},
{
"name": "burnMsolFrom",
"isMut": true,
"isSigner": false
},
{
"name": "burnMsolAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "newTicketAccount",
"isMut": true,
"isSigner": false
},
{
"name": "clock",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "msolAmount",
"type": "u64"
}
]
},
{
"name": "claim",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "reservePda",
"isMut": true,
"isSigner": false
},
{
"name": "ticketAccount",
"isMut": true,
"isSigner": false
},
{
"name": "transferSolTo",
"isMut": true,
"isSigner": false
},
{
"name": "clock",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "stakeReserve",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "validatorList",
"isMut": true,
"isSigner": false
},
{
"name": "stakeList",
"isMut": true,
"isSigner": false
},
{
"name": "validatorVote",
"isMut": true,
"isSigner": false
},
{
"name": "reservePda",
"isMut": true,
"isSigner": false
},
{
"name": "stakeAccount",
"isMut": true,
"isSigner": false
},
{
"name": "stakeDepositAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "clock",
"isMut": false,
"isSigner": false
},
{
"name": "epochSchedule",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "stakeHistory",
"isMut": false,
"isSigner": false
},
{
"name": "stakeConfig",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "stakeProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "validatorIndex",
"type": "u32"
}
]
},
{
"name": "updateActive",
"accounts": [
{
"name": "common",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "stakeList",
"isMut": true,
"isSigner": false
},
{
"name": "stakeAccount",
"isMut": true,
"isSigner": false
},
{
"name": "stakeWithdrawAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "reservePda",
"isMut": true,
"isSigner": false
},
{
"name": "msolMint",
"isMut": true,
"isSigner": false
},
{
"name": "msolMintAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "treasuryMsolAccount",
"isMut": true,
"isSigner": false
},
{
"name": "clock",
"isMut": false,
"isSigner": false
},
{
"name": "stakeHistory",
"isMut": false,
"isSigner": false
},
{
"name": "stakeProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
]
},
{
"name": "validatorList",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "stakeIndex",
"type": "u32"
},
{
"name": "validatorIndex",
"type": "u32"
}
]
},
{
"name": "updateDeactivated",
"accounts": [
{
"name": "common",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "stakeList",
"isMut": true,
"isSigner": false
},
{
"name": "stakeAccount",
"isMut": true,
"isSigner": false
},
{
"name": "stakeWithdrawAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "reservePda",
"isMut": true,
"isSigner": false
},
{
"name": "msolMint",
"isMut": true,
"isSigner": false
},
{
"name": "msolMintAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "treasuryMsolAccount",
"isMut": true,
"isSigner": false
},
{
"name": "clock",
"isMut": false,
"isSigner": false
},
{
"name": "stakeHistory",
"isMut": false,
"isSigner": false
},
{
"name": "stakeProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
]
},
{
"name": "operationalSolAccount",
"isMut": true,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "stakeIndex",
"type": "u32"
}
]
},
{
"name": "deactivateStake",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "reservePda",
"isMut": false,
"isSigner": false
},
{
"name": "validatorList",
"isMut": true,
"isSigner": false
},
{
"name": "stakeList",
"isMut": true,
"isSigner": false
},
{
"name": "stakeAccount",
"isMut": true,
"isSigner": false
},
{
"name": "stakeDepositAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "splitStakeAccount",
"isMut": true,
"isSigner": true
},
{
"name": "splitStakeRentPayer",
"isMut": true,
"isSigner": true
},
{
"name": "clock",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "epochSchedule",
"isMut": false,
"isSigner": false
},
{
"name": "stakeHistory",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "stakeProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "stakeIndex",
"type": "u32"
},
{
"name": "validatorIndex",
"type": "u32"
}
]
},
{
"name": "emergencyUnstake",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "validatorManagerAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "validatorList",
"isMut": true,
"isSigner": false
},
{
"name": "stakeList",
"isMut": true,
"isSigner": false
},
{
"name": "stakeAccount",
"isMut": true,
"isSigner": false
},
{
"name": "stakeDepositAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "clock",
"isMut": false,
"isSigner": false
},
{
"name": "stakeProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "stakeIndex",
"type": "u32"
},
{
"name": "validatorIndex",
"type": "u32"
}
]
},
{
"name": "partialUnstake",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "validatorManagerAuthority",
"isMut": false,
"isSigner": true
},
{
"name": "validatorList",
"isMut": true,
"isSigner": false
},
{
"name": "stakeList",
"isMut": true,
"isSigner": false
},
{
"name": "stakeAccount",
"isMut": true,
"isSigner": false
},
{
"name": "stakeDepositAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "reservePda",
"isMut": false,
"isSigner": false
},
{
"name": "splitStakeAccount",
"isMut": true,
"isSigner": true
},
{
"name": "splitStakeRentPayer",
"isMut": true,
"isSigner": true
},
{
"name": "clock",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "stakeHistory",
"isMut": false,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "stakeProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "stakeIndex",
"type": "u32"
},
{
"name": "validatorIndex",
"type": "u32"
},
{
"name": "desiredUnstakeAmount",
"type": "u64"
}
]
},
{
"name": "mergeStakes",
"accounts": [
{
"name": "state",
"isMut": true,
"isSigner": false
},
{
"name": "stakeList",
"isMut": true,
"isSigner": false
},
{
"name": "validatorList",
"isMut": true,
"isSigner": false
},
{
"name": "destinationStake",
"isMut": true,
"isSigner": false
},
{
"name": "sourceStake",
"isMut": true,
"isSigner": false
},
{
"name": "stakeDepositAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "stakeWithdrawAuthority",
"isMut": false,
"isSigner": false
},
{
"name": "operationalSolAccount",
"isMut": true,
"isSigner": false
},
{
"name": "clock",
"isMut": false,
"isSigner": false
},
{
"name": "stakeHistory",
"isMut": false,
"isSigner": false
},
{
"name": "stakeProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "destinationStakeIndex",
"type": "u32"
},
{
"name": "sourceStakeIndex",
"type": "u32"
},
{
"name": "validatorIndex",
"type": "u32"
}
]
}
],
"accounts": [
{
"name": "State",
"type": {
"kind": "struct",
"fields": [
{
"name": "msolMint",
"type": "publicKey"
},
{
"name": "adminAuthority",
"type": "publicKey"
},
{
"name": "operationalSolAccount",
"type": "publicKey"
},
{
"name": "treasuryMsolAccount",
"type": "publicKey"
},
{
"name": "reserveBumpSeed",
"type": "u8"
},
{
"name": "msolMintAuthorityBumpSeed",
"type": "u8"
},
{
"name": "rentExemptForTokenAcc",
"type": "u64"
},
{
"name": "rewardFee",
"type": {
"defined": "Fee"
}
},
{
"name": "stakeSystem",
"type": {
"defined": "StakeSystem"
}
},
{
"name": "validatorSystem",
"type": {
"defined": "ValidatorSystem"
}
},
{
"name": "liqPool",
"type": {
"defined": "LiqPool"
}
},
{
"name": "availableReserveBalance",
"type": "u64"
},
{
"name": "msolSupply",
"type": "u64"
},
{
"name": "msolPrice",
"type": "u64"
},
{
"name": "circulatingTicketCount",
"docs": ["count tickets for delayed-unstake"],
"type": "u64"
},
{
"name": "circulatingTicketBalance",
"docs": [
"total lamports amount of generated and not claimed yet tickets"
],
"type": "u64"
},
{
"name": "lentFromReserve",
"type": "u64"
},
{
"name": "minDeposit",
"type": "u64"
},
{
"name": "minWithdraw",
"type": "u64"
},
{
"name": "stakingSolCap",
"type": "u64"
},
{
"name": "emergencyCoolingDown",
"type": "u64"
}
]
}
},
{
"name": "TicketAccountData",
"type": {
"kind": "struct",
"fields": [
{
"name": "stateAddress",
"type": "publicKey"
},
{
"name": "beneficiary",
"type": "publicKey"
},
{
"name": "lamportsAmount",
"type": "u64"
},
{
"name": "createdEpoch",
"type": "u64"
}
]
}
}
],
"types": [
{
"name": "LiqPool",
"type": {
"kind": "struct",
"fields": [
{
"name": "lpMint",
"type": "publicKey"
},
{
"name": "lpMintAuthorityBumpSeed",
"type": "u8"
},
{
"name": "solLegBumpSeed",
"type": "u8"
},
{
"name": "msolLegAuthorityBumpSeed",
"type": "u8"
},
{
"name": "msolLeg",
"type": "publicKey"
},
{
"name": "lpLiquidityTarget",
"docs": [
"Liquidity target. If the Liquidity reach this amount, the fee reaches lp_min_discount_fee"
],
"type": "u64"
},
{
"name": "lpMaxFee",
"docs": ["Liquidity pool max fee"],
"type": {
"defined": "Fee"
}
},
{
"name": "lpMinFee",
"docs": ["SOL/mSOL Liquidity pool min fee"],
"type": {
"defined": "Fee"
}
},
{
"name": "treasuryCut",
"docs": ["Treasury cut"],
"type": {
"defined": "Fee"
}
},
{
"name": "lpSupply",
"type": "u64"
},
{
"name": "lentFromSolLeg",
"type": "u64"
},
{
"name": "liquiditySolCap",
"type": "u64"
}
]
}
},
{
"name": "List",
"type": {
"kind": "struct",
"fields": [
{
"name": "account",
"type": "publicKey"
},
{
"name": "itemSize",
"type": "u32"
},
{
"name": "count",
"type": "u32"
},
{
"name": "newAccount",
"type": "publicKey"
},
{
"name": "copiedCount",
"type": "u32"
}
]
}
},
{
"name": "StakeRecord",
"type": {
"kind": "struct",
"fields": [
{
"name": "stakeAccount",
"type": "publicKey"
},
{
"name": "lastUpdateDelegatedLamports",
"type": "u64"
},
{
"name": "lastUpdateEpoch",
"type": "u64"
},
{
"name": "isEmergencyUnstaking",
"type": "u8"
}
]
}
},
{
"name": "StakeSystem",
"type": {
"kind": "struct",
"fields": [
{
"name": "stakeList",
"type": {
"defined": "List"
}
},
{
"name": "delayedUnstakeCoolingDown",
"type": "u64"
},
{
"name": "stakeDepositBumpSeed",
"type": "u8"
},
{
"name": "stakeWithdrawBumpSeed",
"type": "u8"
},
{
"name": "slotsForStakeDelta",
"docs": [
"set by admin, how much slots before the end of the epoch, stake-delta can start"
],
"type": "u64"
},
{
"name": "lastStakeDeltaEpoch",
"docs": [
"Marks the start of stake-delta operations, meaning that if somebody starts a delayed-unstake ticket",
"after this var is set with epoch_num the ticket will have epoch_created = current_epoch+1",
"(the user must wait one more epoch, because their unstake-delta will be execute in this epoch)"
],
"type": "u64"
},
{
"name": "minStake",
"type": "u64"
},
{
"name": "extraStakeDeltaRuns",
"docs": [
"can be set by validator-manager-auth to allow a second run of stake-delta to stake late stakers in the last minute of the epoch",
"so we maximize user's rewards"
],
"type": "u32"
}
]
}
},
{
"name": "ValidatorRecord",
"type": {
"kind": "struct",
"fields": [
{
"name": "validatorAccount",
"docs": ["Validator vote pubkey"],
"type": "publicKey"
},
{
"name": "activeBalance",
"docs": ["Validator total balance in lamports"],
"type": "u64"
},
{
"name": "score",
"type": "u32"
},
{
"name": "lastStakeDeltaEpoch",
"type": "u64"
},
{
"name": "duplicationFlagBumpSeed",
"type": "u8"
}
]
}
},
{
"name": "ValidatorSystem",
"type": {
"kind": "struct",
"fields": [
{
"name": "validatorList",
"type": {
"defined": "List"
}
},
{
"name": "managerAuthority",
"type": "publicKey"
},
{
"name": "totalValidatorScore",
"type": "u32"
},
{
"name": "totalActiveBalance",
"docs": ["sum of all active lamports staked"],
"type": "u64"
},
{
"name": "autoAddValidatorEnabled",
"docs": [
"allow & auto-add validator when a user deposits a stake-account of a non-listed validator"
],
"type": "u8"
}
]
}
},
{
"name": "Fee",
"type": {
"kind": "struct",
"fields": [
{
"name": "basisPoints",
"type": "u32"
}
]
}
},
{
"name": "InitializeData",
"type": {
"kind": "struct",
"fields": [
{
"name": "adminAuthority",
"type": "publicKey"
},
{
"name": "validatorManagerAuthority",
"type": "publicKey"
},
{
"name": "minStake",
"type": "u64"
},
{
"name": "rewardFee",
"type": {
"defined": "Fee"
}
},
{
"name": "liqPool",
"type": {
"defined": "LiqPoolInitializeData"
}
},
{
"name": "additionalStakeRecordSpace",
"type": "u32"
},
{
"name": "additionalValidatorRecordSpace",
"type": "u32"
},
{
"name": "slotsForStakeDelta",
"type": "u64"
}
]
}
},
{
"name": "LiqPoolInitializeData",
"type": {
"kind": "struct",
"fields": [
{
"name": "lpLiquidityTarget",
"type": "u64"
},
{
"name": "lpMaxFee",
"type": {
"defined": "Fee"
}
},
{
"name": "lpMinFee",
"type": {
"defined": "Fee"
}
},
{
"name": "lpTreasuryCut",
"type": {
"defined": "Fee"
}
}
]
}
},
{
"name": "ChangeAuthorityData",
"type": {
"kind": "struct",
"fields": [
{
"name": "admin",
"type": {
"option": "publicKey"
}
},
{
"name": "validatorManager",
"type": {
"option": "publicKey"
}
},
{
"name": "operationalSolAccount",
"type": {
"option": "publicKey"
}
},
{
"name": "treasuryMsolAccount",
"type": {
"option": "publicKey"
}
}
]
}
},
{
"name": "ConfigLpParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "minFee",
"type": {
"option": {
"defined": "Fee"
}
}
},
{
"name": "maxFee",
"type": {
"option": {
"defined": "Fee"
}
}
},
{
"name": "liquidityTarget",
"type": {
"option": "u64"
}
},
{
"name": "treasuryCut",
"type": {
"option": {
"defined": "Fee"
}
}
}
]
}
},
{
"name": "ConfigMarinadeParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "rewardsFee",
"type": {
"option": {
"defined": "Fee"
}
}
},
{
"name": "slotsForStakeDelta",
"type": {
"option": "u64"
}
},
{
"name": "minStake",
"type": {
"option": "u64"
}
},
{
"name": "minDeposit",
"type": {
"option": "u64"
}
},
{
"name": "minWithdraw",
"type": {
"option": "u64"
}
},
{
"name": "stakingSolCap",
"type": {
"option": "u64"
}
},
{
"name": "liquiditySolCap",
"type": {
"option": "u64"
}
},
{
"name": "autoAddValidatorEnabled",
"type": {
"option": "bool"
}
}
]
}
},
{
"name": "CommonError",
"type": {
"kind": "enum",
"variants": [
{
"name": "WrongReserveOwner"
},
{
"name": "NonEmptyReserveData"
},
{
"name": "InvalidInitialReserveLamports"
},
{
"name": "ZeroValidatorChunkSize"
},
{
"name": "TooBigValidatorChunkSize"
},
{
"name": "ZeroCreditChunkSize"
},
{
"name": "TooBigCreditChunkSize"
},
{
"name": "TooLowCreditFee"
},
{
"name": "InvalidMintAuthority"
},
{
"name": "MintHasInitialSupply"
},
{
"name": "InvalidOwnerFeeState"
},
{
"name": "InvalidProgramId"
},
{
"name": "UnexpectedAccount"
},
{
"name": "CalculationFailure"
},
{
"name": "AccountWithLockup"
},
{
"name": "NumberTooLow"
},
{
"name": "NumberTooHigh"
},
{
"name": "FeeTooHigh"
},
{
"name": "FeesWrongWayRound"
},
{
"name": "LiquidityTargetTooLow"
},
{
"name": "TicketNotDue"
},
{
"name": "TicketNotReady"
},
{
"name": "WrongBeneficiary"
},
{
"name": "StakeAccountNotUpdatedYet"
},
{
"name": "StakeNotDelegated"
},
{
"name": "StakeAccountIsEmergencyUnstaking"
},
{
"name": "InsufficientLiquidity"
},
{
"name": "InvalidValidator"
}
]
}
}
]
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/auctionSubscriber/auctionSubscriberGrpc.ts
|
import { AuctionSubscriberConfig, AuctionSubscriberEvents } from './types';
import { DriftClient } from '../driftClient';
import { getUserFilter, getUserWithAuctionFilter } from '../memcmp';
import StrictEventEmitter from 'strict-event-emitter-types';
import { EventEmitter } from 'events';
import { UserAccount } from '../types';
import { ConfirmOptions, Context, PublicKey } from '@solana/web3.js';
import { WebSocketProgramAccountSubscriber } from '../accounts/webSocketProgramAccountSubscriber';
import { GrpcConfigs, ResubOpts } from '../accounts/types';
import { grpcProgramAccountSubscriber } from '../accounts/grpcProgramAccountSubscriber';
export class AuctionSubscriberGrpc {
private driftClient: DriftClient;
private opts: ConfirmOptions;
private resubOpts?: ResubOpts;
private grpcConfigs?: GrpcConfigs;
eventEmitter: StrictEventEmitter<EventEmitter, AuctionSubscriberEvents>;
private subscriber: WebSocketProgramAccountSubscriber<UserAccount>;
constructor({
driftClient,
opts,
grpcConfigs,
resubTimeoutMs,
logResubMessages,
}: AuctionSubscriberConfig) {
this.driftClient = driftClient;
this.opts = opts || this.driftClient.opts;
this.eventEmitter = new EventEmitter();
this.resubOpts = { resubTimeoutMs, logResubMessages };
this.grpcConfigs = grpcConfigs;
}
public async subscribe() {
if (!this.subscriber) {
this.subscriber = new grpcProgramAccountSubscriber<UserAccount>(
this.grpcConfigs,
'AuctionSubscriber',
'User',
this.driftClient.program,
this.driftClient.program.account.user.coder.accounts.decode.bind(
this.driftClient.program.account.user.coder.accounts
),
{
filters: [getUserFilter(), getUserWithAuctionFilter()],
},
this.resubOpts
);
}
await this.subscriber.subscribe(
(accountId: PublicKey, data: UserAccount, context: Context) => {
this.eventEmitter.emit(
'onAccountUpdate',
data,
accountId,
context.slot
);
}
);
}
public async unsubscribe() {
if (!this.subscriber) {
return;
}
this.subscriber.unsubscribe();
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/auctionSubscriber/types.ts
|
import { GrpcConfigs } from '../accounts/types';
import { DriftClient } from '../driftClient';
import { UserAccount } from '../types';
import { ConfirmOptions, PublicKey } from '@solana/web3.js';
export type AuctionSubscriberConfig = {
driftClient: DriftClient;
opts?: ConfirmOptions;
resubTimeoutMs?: number;
logResubMessages?: boolean;
grpcConfigs?: GrpcConfigs;
};
export interface AuctionSubscriberEvents {
onAccountUpdate: (
account: UserAccount,
pubkey: PublicKey,
slot: number
) => void;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/auctionSubscriber/auctionSubscriber.ts
|
import { AuctionSubscriberConfig, AuctionSubscriberEvents } from './types';
import { DriftClient } from '../driftClient';
import { getUserFilter, getUserWithAuctionFilter } from '../memcmp';
import StrictEventEmitter from 'strict-event-emitter-types';
import { EventEmitter } from 'events';
import { UserAccount } from '../types';
import { ConfirmOptions, Context, PublicKey } from '@solana/web3.js';
import { WebSocketProgramAccountSubscriber } from '../accounts/webSocketProgramAccountSubscriber';
import { ResubOpts } from '../accounts/types';
export class AuctionSubscriber {
private driftClient: DriftClient;
private opts: ConfirmOptions;
private resubOpts?: ResubOpts;
eventEmitter: StrictEventEmitter<EventEmitter, AuctionSubscriberEvents>;
private subscriber: WebSocketProgramAccountSubscriber<UserAccount>;
constructor({
driftClient,
opts,
resubTimeoutMs,
logResubMessages,
}: AuctionSubscriberConfig) {
this.driftClient = driftClient;
this.opts = opts || this.driftClient.opts;
this.eventEmitter = new EventEmitter();
this.resubOpts = { resubTimeoutMs, logResubMessages };
}
public async subscribe() {
if (!this.subscriber) {
this.subscriber = new WebSocketProgramAccountSubscriber<UserAccount>(
'AuctionSubscriber',
'User',
this.driftClient.program,
this.driftClient.program.account.user.coder.accounts.decode.bind(
this.driftClient.program.account.user.coder.accounts
),
{
filters: [getUserFilter(), getUserWithAuctionFilter()],
commitment: this.opts.commitment,
},
this.resubOpts
);
}
await this.subscriber.subscribe(
(accountId: PublicKey, data: UserAccount, context: Context) => {
this.eventEmitter.emit(
'onAccountUpdate',
data,
accountId,
context.slot
);
}
);
}
public async unsubscribe() {
if (!this.subscriber) {
return;
}
this.subscriber.unsubscribe();
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/auctionSubscriber/index.ts
|
export * from './types';
export * from './auctionSubscriber';
export * from './auctionSubscriberGrpc';
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/jupiter/jupiterClient.ts
|
import {
AddressLookupTableAccount,
Connection,
PublicKey,
TransactionInstruction,
TransactionMessage,
VersionedTransaction,
} from '@solana/web3.js';
import fetch from 'node-fetch';
import { BN } from '@coral-xyz/anchor';
export type SwapMode = 'ExactIn' | 'ExactOut';
export interface MarketInfo {
id: string;
inAmount: number;
inputMint: string;
label: string;
lpFee: Fee;
notEnoughLiquidity: boolean;
outAmount: number;
outputMint: string;
platformFee: Fee;
priceImpactPct: number;
}
export interface Fee {
amount: number;
mint: string;
pct: number;
}
export interface Route {
amount: number;
inAmount: number;
marketInfos: MarketInfo[];
otherAmountThreshold: number;
outAmount: number;
priceImpactPct: number;
slippageBps: number;
swapMode: SwapMode;
}
/**
*
* @export
* @interface RoutePlanStep
*/
export interface RoutePlanStep {
/**
*
* @type {SwapInfo}
* @memberof RoutePlanStep
*/
swapInfo: SwapInfo;
/**
*
* @type {number}
* @memberof RoutePlanStep
*/
percent: number;
}
export interface SwapInfo {
/**
*
* @type {string}
* @memberof SwapInfo
*/
ammKey: string;
/**
*
* @type {string}
* @memberof SwapInfo
*/
label?: string;
/**
*
* @type {string}
* @memberof SwapInfo
*/
inputMint: string;
/**
*
* @type {string}
* @memberof SwapInfo
*/
outputMint: string;
/**
*
* @type {string}
* @memberof SwapInfo
*/
inAmount: string;
/**
*
* @type {string}
* @memberof SwapInfo
*/
outAmount: string;
/**
*
* @type {string}
* @memberof SwapInfo
*/
feeAmount: string;
/**
*
* @type {string}
* @memberof SwapInfo
*/
feeMint: string;
}
/**
*
* @export
* @interface PlatformFee
*/
export interface PlatformFee {
/**
*
* @type {string}
* @memberof PlatformFee
*/
amount?: string;
/**
*
* @type {number}
* @memberof PlatformFee
*/
feeBps?: number;
}
/**
*
* @export
* @interface QuoteResponse
*/
export interface QuoteResponse {
/**
*
* @type {string}
* @memberof QuoteResponse
*/
inputMint: string;
/**
*
* @type {string}
* @memberof QuoteResponse
*/
inAmount: string;
/**
*
* @type {string}
* @memberof QuoteResponse
*/
outputMint: string;
/**
*
* @type {string}
* @memberof QuoteResponse
*/
outAmount: string;
/**
*
* @type {string}
* @memberof QuoteResponse
*/
otherAmountThreshold: string;
/**
*
* @type {SwapMode}
* @memberof QuoteResponse
*/
swapMode: SwapMode;
/**
*
* @type {number}
* @memberof QuoteResponse
*/
slippageBps: number;
/**
*
* @type {PlatformFee}
* @memberof QuoteResponse
*/
platformFee?: PlatformFee;
/**
*
* @type {string}
* @memberof QuoteResponse
*/
priceImpactPct: string;
/**
*
* @type {Array<RoutePlanStep>}
* @memberof QuoteResponse
*/
routePlan: Array<RoutePlanStep>;
/**
*
* @type {number}
* @memberof QuoteResponse
*/
contextSlot?: number;
/**
*
* @type {number}
* @memberof QuoteResponse
*/
timeTaken?: number;
/**
*
* @type {string}
* @memberof QuoteResponse
*/
error?: string;
/**
*
* @type {string}
* @memberof QuoteResponse
*/
errorCode?: string;
}
export class JupiterClient {
url: string;
connection: Connection;
lookupTableCahce = new Map<string, AddressLookupTableAccount>();
constructor({ connection, url }: { connection: Connection; url?: string }) {
this.connection = connection;
this.url = url ?? 'https://quote-api.jup.ag';
}
/**
* ** @deprecated - use getQuote
* Get routes for a swap
* @param inputMint the mint of the input token
* @param outputMint the mint of the output token
* @param amount the amount of the input token
* @param slippageBps the slippage tolerance in basis points
* @param swapMode the swap mode (ExactIn or ExactOut)
* @param onlyDirectRoutes whether to only return direct routes
*/
public async getRoutes({
inputMint,
outputMint,
amount,
slippageBps = 50,
swapMode = 'ExactIn',
onlyDirectRoutes = false,
}: {
inputMint: PublicKey;
outputMint: PublicKey;
amount: BN;
slippageBps?: number;
swapMode?: SwapMode;
onlyDirectRoutes?: boolean;
}): Promise<Route[]> {
const params = new URLSearchParams({
inputMint: inputMint.toString(),
outputMint: outputMint.toString(),
amount: amount.toString(),
slippageBps: slippageBps.toString(),
swapMode,
onlyDirectRoutes: onlyDirectRoutes.toString(),
}).toString();
const apiVersionParam =
this.url === 'https://quote-api.jup.ag' ? '/v4' : '';
const { data: routes } = await (
await fetch(`${this.url}${apiVersionParam}/quote?${params}`)
).json();
return routes;
}
/**
* Get routes for a swap
* @param inputMint the mint of the input token
* @param outputMint the mint of the output token
* @param amount the amount of the input token
* @param slippageBps the slippage tolerance in basis points
* @param swapMode the swap mode (ExactIn or ExactOut)
* @param onlyDirectRoutes whether to only return direct routes
*/
public async getQuote({
inputMint,
outputMint,
amount,
maxAccounts = 50, // 50 is an estimated amount with buffer
slippageBps = 50,
swapMode = 'ExactIn',
onlyDirectRoutes = false,
excludeDexes,
}: {
inputMint: PublicKey;
outputMint: PublicKey;
amount: BN;
maxAccounts?: number;
slippageBps?: number;
swapMode?: SwapMode;
onlyDirectRoutes?: boolean;
excludeDexes?: string[];
}): Promise<QuoteResponse> {
const params = new URLSearchParams({
inputMint: inputMint.toString(),
outputMint: outputMint.toString(),
amount: amount.toString(),
slippageBps: slippageBps.toString(),
swapMode,
onlyDirectRoutes: onlyDirectRoutes.toString(),
maxAccounts: maxAccounts.toString(),
...(excludeDexes && { excludeDexes: excludeDexes.join(',') }),
});
if (swapMode === 'ExactOut') {
params.delete('maxAccounts');
}
const apiVersionParam =
this.url === 'https://quote-api.jup.ag' ? '/v6' : '';
const quote = await (
await fetch(`${this.url}${apiVersionParam}/quote?${params.toString()}`)
).json();
return quote as QuoteResponse;
}
/**
* Get a swap transaction for quote
* @param quoteResponse quote to perform swap
* @param userPublicKey the signer's wallet public key
* @param slippageBps the slippage tolerance in basis points
*/
public async getSwap({
quote,
userPublicKey,
slippageBps = 50,
}: {
quote: QuoteResponse;
userPublicKey: PublicKey;
slippageBps?: number;
}): Promise<VersionedTransaction> {
if (!quote) {
throw new Error('Jupiter swap quote not provided. Please try again.');
}
const apiVersionParam =
this.url === 'https://quote-api.jup.ag' ? '/v6' : '';
const resp = await (
await fetch(`${this.url}${apiVersionParam}/swap`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
quoteResponse: quote,
userPublicKey,
slippageBps,
}),
})
).json();
if (!('swapTransaction' in resp)) {
throw new Error(
`swapTransaction not found, error from Jupiter: ${resp.error} ${
', ' + resp.message ?? ''
}`
);
}
const { swapTransaction } = resp;
try {
const swapTransactionBuf = Buffer.from(swapTransaction, 'base64');
return VersionedTransaction.deserialize(swapTransactionBuf);
} catch (err) {
throw new Error(
'Something went wrong with creating the Jupiter swap transaction. Please try again.'
);
}
}
/**
* ** @deprecated - use getSwap
* Get a swap transaction for a route
* @param route the route to perform swap
* @param userPublicKey the signer's wallet public key
* @param slippageBps the slippage tolerance in basis points
*/
public async getSwapTransaction({
route,
userPublicKey,
slippageBps = 50,
}: {
route: Route;
userPublicKey: PublicKey;
slippageBps?: number;
}): Promise<VersionedTransaction> {
const apiVersionParam =
this.url === 'https://quote-api.jup.ag' ? '/v4' : '';
const resp = await (
await fetch(`${this.url}${apiVersionParam}/swap`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
route,
userPublicKey,
slippageBps,
}),
})
).json();
const { swapTransaction } = resp;
const swapTransactionBuf = Buffer.from(swapTransaction, 'base64');
return VersionedTransaction.deserialize(swapTransactionBuf);
}
/**
* Get the transaction message and lookup tables for a transaction
* @param transaction
*/
public async getTransactionMessageAndLookupTables({
transaction,
}: {
transaction: VersionedTransaction;
}): Promise<{
transactionMessage: TransactionMessage;
lookupTables: AddressLookupTableAccount[];
}> {
const message = transaction.message;
const lookupTables = (
await Promise.all(
message.addressTableLookups.map(async (lookup) => {
return await this.getLookupTable(lookup.accountKey);
})
)
).filter((lookup) => lookup);
const transactionMessage = TransactionMessage.decompile(message, {
addressLookupTableAccounts: lookupTables,
});
return {
transactionMessage,
lookupTables,
};
}
async getLookupTable(
accountKey: PublicKey
): Promise<AddressLookupTableAccount> {
if (this.lookupTableCahce.has(accountKey.toString())) {
return this.lookupTableCahce.get(accountKey.toString());
}
return (await this.connection.getAddressLookupTable(accountKey)).value;
}
/**
* Get the jupiter instructions from transaction by filtering out instructions to compute budget and associated token programs
* @param transactionMessage the transaction message
* @param inputMint the input mint
* @param outputMint the output mint
*/
public getJupiterInstructions({
transactionMessage,
inputMint,
outputMint,
}: {
transactionMessage: TransactionMessage;
inputMint: PublicKey;
outputMint: PublicKey;
}): TransactionInstruction[] {
return transactionMessage.instructions.filter((instruction) => {
if (
instruction.programId.toString() ===
'ComputeBudget111111111111111111111111111111'
) {
return false;
}
if (
instruction.programId.toString() ===
'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'
) {
return false;
}
if (
instruction.programId.toString() === '11111111111111111111111111111111'
) {
return false;
}
if (
instruction.programId.toString() ===
'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'
) {
const mint = instruction.keys[3].pubkey;
if (mint.equals(inputMint) || mint.equals(outputMint)) {
return false;
}
}
return true;
});
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/assert/assert.ts
|
export function assert(condition: boolean, error?: string): void {
if (!condition) {
throw new Error(error || 'Unspecified AssertionError');
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/state.ts
|
import { StateAccount } from '../types';
import { BN, LAMPORTS_PRECISION, PERCENTAGE_PRECISION, ZERO } from '../';
export function calculateInitUserFee(stateAccount: StateAccount): BN {
const maxInitFee = new BN(stateAccount.maxInitializeUserFee)
.mul(LAMPORTS_PRECISION)
.divn(100);
const targetUtilization = PERCENTAGE_PRECISION.muln(8).divn(10);
const accountSpaceUtilization = stateAccount.numberOfSubAccounts
.addn(1)
.mul(PERCENTAGE_PRECISION)
.div(getMaxNumberOfSubAccounts(stateAccount));
if (accountSpaceUtilization.gt(targetUtilization)) {
return maxInitFee
.mul(accountSpaceUtilization.sub(targetUtilization))
.div(PERCENTAGE_PRECISION.sub(targetUtilization));
} else {
return ZERO;
}
}
export function getMaxNumberOfSubAccounts(stateAccount: StateAccount): BN {
if (stateAccount.maxNumberOfSubAccounts <= 5) {
return new BN(stateAccount.maxNumberOfSubAccounts);
}
return new BN(stateAccount.maxNumberOfSubAccounts).muln(100);
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/tiers.ts
|
import { isVariant, PerpMarketAccount, SpotMarketAccount } from '../types';
export function getPerpMarketTierNumber(perpMarket: PerpMarketAccount): number {
if (isVariant(perpMarket.contractTier, 'a')) {
return 0;
} else if (isVariant(perpMarket.contractTier, 'b')) {
return 1;
} else if (isVariant(perpMarket.contractTier, 'c')) {
return 2;
} else if (isVariant(perpMarket.contractTier, 'speculative')) {
return 3;
} else if (isVariant(perpMarket.contractTier, 'highlySpeculative')) {
return 4;
} else {
return 5;
}
}
export function getSpotMarketTierNumber(spotMarket: SpotMarketAccount): number {
if (isVariant(spotMarket.assetTier, 'collateral')) {
return 0;
} else if (isVariant(spotMarket.assetTier, 'protected')) {
return 1;
} else if (isVariant(spotMarket.assetTier, 'cross')) {
return 2;
} else if (isVariant(spotMarket.assetTier, 'isolated')) {
return 3;
} else if (isVariant(spotMarket.assetTier, 'unlisted')) {
return 4;
} else {
return 5;
}
}
export function perpTierIsAsSafeAs(
perpTier: number,
otherPerpTier: number,
otherSpotTier: number
): boolean {
const asSafeAsPerp = perpTier <= otherPerpTier;
const asSafeAsSpot =
otherSpotTier === 4 || (otherSpotTier >= 2 && perpTier <= 2);
return asSafeAsSpot && asSafeAsPerp;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/repeg.ts
|
import { BN } from '@coral-xyz/anchor';
import { assert } from '../assert/assert';
import {
PRICE_PRECISION,
AMM_RESERVE_PRECISION,
PEG_PRECISION,
AMM_TO_QUOTE_PRECISION_RATIO,
PRICE_DIV_PEG,
QUOTE_PRECISION,
ZERO,
ONE,
PERCENTAGE_PRECISION,
} from '../constants/numericConstants';
import { AMM } from '../types';
/**
* Helper function calculating adjust k cost
* @param amm
* @param numerator
* @param denomenator
* @returns cost : Precision QUOTE_ASSET_PRECISION
*/
export function calculateAdjustKCost(
amm: AMM,
numerator: BN,
denomenator: BN
): BN {
// const k = market.amm.sqrtK.mul(market.amm.sqrtK);
const x = amm.baseAssetReserve;
const y = amm.quoteAssetReserve;
const d = amm.baseAssetAmountWithAmm;
const Q = amm.pegMultiplier;
const quoteScale = y.mul(d).mul(Q); //.div(AMM_RESERVE_PRECISION);
const p = numerator.mul(PRICE_PRECISION).div(denomenator);
const cost = quoteScale
.mul(PERCENTAGE_PRECISION)
.mul(PERCENTAGE_PRECISION)
.div(x.add(d))
.sub(
quoteScale
.mul(p)
.mul(PERCENTAGE_PRECISION)
.mul(PERCENTAGE_PRECISION)
.div(PRICE_PRECISION)
.div(x.mul(p).div(PRICE_PRECISION).add(d))
)
.div(PERCENTAGE_PRECISION)
.div(PERCENTAGE_PRECISION)
.div(AMM_TO_QUOTE_PRECISION_RATIO)
.div(PEG_PRECISION);
return cost.mul(new BN(-1));
}
// /**
// * Helper function calculating adjust k cost
// * @param amm
// * @param numerator
// * @param denomenator
// * @returns cost : Precision QUOTE_ASSET_PRECISION
// */
// export function calculateAdjustKCost2(
// amm: AMM,
// numerator: BN,
// denomenator: BN
// ): BN {
// // const k = market.amm.sqrtK.mul(market.amm.sqrtK);
// const directionToClose = amm.baseAssetAmountWithAmm.gt(ZERO)
// ? PositionDirection.SHORT
// : PositionDirection.LONG;
// const [newQuoteAssetReserve, _newBaseAssetReserve] =
// calculateAmmReservesAfterSwap(
// amm,
// 'base',
// amm.baseAssetAmountWithAmm.abs(),
// getSwapDirection('base', directionToClose)
// );
// }
/**
* Helper function calculating adjust pegMultiplier (repeg) cost
*
* @param amm
* @param newPeg
* @returns cost : Precision QUOTE_ASSET_PRECISION
*/
export function calculateRepegCost(amm: AMM, newPeg: BN): BN {
const dqar = amm.quoteAssetReserve.sub(amm.terminalQuoteAssetReserve);
const cost = dqar
.mul(newPeg.sub(amm.pegMultiplier))
.div(AMM_TO_QUOTE_PRECISION_RATIO)
.div(PEG_PRECISION);
return cost;
}
export function calculateBudgetedKBN(
x: BN,
y: BN,
budget: BN,
Q: BN,
d: BN
): [BN, BN] {
assert(Q.gt(new BN(0)));
const C = budget.mul(new BN(-1));
let dSign = new BN(1);
if (d.lt(new BN(0))) {
dSign = new BN(-1);
}
const pegged_y_d_d = y
.mul(d)
.mul(d)
.mul(Q)
.div(AMM_RESERVE_PRECISION)
.div(AMM_RESERVE_PRECISION)
.div(PEG_PRECISION);
const numer1 = pegged_y_d_d;
const numer2 = C.mul(d)
.div(QUOTE_PRECISION)
.mul(x.add(d))
.div(AMM_RESERVE_PRECISION)
.mul(dSign);
const denom1 = C.mul(x)
.mul(x.add(d))
.div(AMM_RESERVE_PRECISION)
.div(QUOTE_PRECISION);
const denom2 = pegged_y_d_d;
// protocol is spending to increase k
if (C.lt(ZERO)) {
// thus denom1 is negative and solution is unstable
if (denom1.abs().gt(denom2.abs())) {
console.log('denom1 > denom2', denom1.toString(), denom2.toString());
console.log('budget cost exceeds stable K solution');
return [new BN(10000), new BN(1)];
}
}
const numerator = numer1.sub(numer2).div(AMM_TO_QUOTE_PRECISION_RATIO);
const denominator = denom1.add(denom2).div(AMM_TO_QUOTE_PRECISION_RATIO);
return [numerator, denominator];
}
export function calculateBudgetedK(amm: AMM, cost: BN): [BN, BN] {
// wolframalpha.com
// (1/(x+d) - p/(x*p+d))*y*d*Q = C solve for p
// p = (d(y*d*Q - C(x+d))) / (C*x(x+d) + y*d*d*Q)
// numer
// = y*d*d*Q - Cxd - Cdd
// = y/x*Q*d*d - Cd - Cd/x
// = mark - C/d - C/(x)
// = mark/C - 1/d - 1/x
// denom
// = C*x*x + C*x*d + y*d*d*Q
// = x/d**2 + 1 / d + mark/C
// todo: assumes k = x * y
// otherwise use: (y(1-p) + (kp^2/(x*p+d)) - k/(x+d)) * Q = C solve for p
const x = amm.baseAssetReserve;
const y = amm.quoteAssetReserve;
const d = amm.baseAssetAmountWithAmm;
const Q = amm.pegMultiplier;
const [numerator, denominator] = calculateBudgetedKBN(x, y, cost, Q, d);
return [numerator, denominator];
}
export function calculateBudgetedPeg(
amm: AMM,
budget: BN,
targetPrice: BN
): BN {
let perPegCost = amm.quoteAssetReserve
.sub(amm.terminalQuoteAssetReserve)
.div(AMM_RESERVE_PRECISION.div(PRICE_PRECISION));
if (perPegCost.gt(ZERO)) {
perPegCost = perPegCost.add(ONE);
} else if (perPegCost.lt(ZERO)) {
perPegCost = perPegCost.sub(ONE);
}
const targetPeg = targetPrice
.mul(amm.baseAssetReserve)
.div(amm.quoteAssetReserve)
.div(PRICE_DIV_PEG);
const pegChangeDirection = targetPeg.sub(amm.pegMultiplier);
const useTargetPeg =
(perPegCost.lt(ZERO) && pegChangeDirection.gt(ZERO)) ||
(perPegCost.gt(ZERO) && pegChangeDirection.lt(ZERO));
if (perPegCost.eq(ZERO) || useTargetPeg) {
return targetPeg;
}
const budgetDeltaPeg = budget.mul(PEG_PRECISION).div(perPegCost);
const newPeg = BN.max(ONE, amm.pegMultiplier.add(budgetDeltaPeg));
return newPeg;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/auction.ts
|
import { isOneOfVariant, isVariant, Order, PositionDirection } from '../types';
import { BN, getVariant, ONE, ZERO } from '../.';
export function isAuctionComplete(order: Order, slot: number): boolean {
if (order.auctionDuration === 0) {
return true;
}
return new BN(slot).sub(order.slot).gt(new BN(order.auctionDuration));
}
export function isFallbackAvailableLiquiditySource(
order: Order,
minAuctionDuration: number,
slot: number
): boolean {
if (minAuctionDuration === 0) {
return true;
}
return new BN(slot).sub(order.slot).gt(new BN(minAuctionDuration));
}
export function getAuctionPrice(
order: Order,
slot: number,
oraclePrice: BN
): BN {
if (
isOneOfVariant(order.orderType, ['market', 'triggerMarket', 'triggerLimit'])
) {
return getAuctionPriceForFixedAuction(order, slot);
} else if (isVariant(order.orderType, 'limit')) {
if (order.oraclePriceOffset !== 0) {
return getAuctionPriceForOracleOffsetAuction(order, slot, oraclePrice);
} else {
return getAuctionPriceForFixedAuction(order, slot);
}
} else if (isVariant(order.orderType, 'oracle')) {
return getAuctionPriceForOracleOffsetAuction(order, slot, oraclePrice);
} else {
throw Error(
`Cant get auction price for order type ${getVariant(order.orderType)}`
);
}
}
export function getAuctionPriceForFixedAuction(order: Order, slot: number): BN {
const slotsElapsed = new BN(slot).sub(order.slot);
const deltaDenominator = new BN(order.auctionDuration);
const deltaNumerator = BN.min(slotsElapsed, deltaDenominator);
if (deltaDenominator.eq(ZERO)) {
return order.auctionEndPrice;
}
let priceDelta;
if (isVariant(order.direction, 'long')) {
priceDelta = order.auctionEndPrice
.sub(order.auctionStartPrice)
.mul(deltaNumerator)
.div(deltaDenominator);
} else {
priceDelta = order.auctionStartPrice
.sub(order.auctionEndPrice)
.mul(deltaNumerator)
.div(deltaDenominator);
}
let price;
if (isVariant(order.direction, 'long')) {
price = order.auctionStartPrice.add(priceDelta);
} else {
price = order.auctionStartPrice.sub(priceDelta);
}
return price;
}
export function getAuctionPriceForOracleOffsetAuction(
order: Order,
slot: number,
oraclePrice: BN
): BN {
const slotsElapsed = new BN(slot).sub(order.slot);
const deltaDenominator = new BN(order.auctionDuration);
const deltaNumerator = BN.min(slotsElapsed, deltaDenominator);
if (deltaDenominator.eq(ZERO)) {
return BN.max(oraclePrice.add(order.auctionEndPrice), ONE);
}
let priceOffsetDelta;
if (isVariant(order.direction, 'long')) {
priceOffsetDelta = order.auctionEndPrice
.sub(order.auctionStartPrice)
.mul(deltaNumerator)
.div(deltaDenominator);
} else {
priceOffsetDelta = order.auctionStartPrice
.sub(order.auctionEndPrice)
.mul(deltaNumerator)
.div(deltaDenominator);
}
let priceOffset;
if (isVariant(order.direction, 'long')) {
priceOffset = order.auctionStartPrice.add(priceOffsetDelta);
} else {
priceOffset = order.auctionStartPrice.sub(priceOffsetDelta);
}
return BN.max(oraclePrice.add(priceOffset), ONE);
}
export function deriveOracleAuctionParams({
direction,
oraclePrice,
auctionStartPrice,
auctionEndPrice,
limitPrice,
auctionPriceCaps,
}: {
direction: PositionDirection;
oraclePrice: BN;
auctionStartPrice: BN;
auctionEndPrice: BN;
limitPrice: BN;
auctionPriceCaps?: {
min: BN;
max: BN;
};
}): { auctionStartPrice: BN; auctionEndPrice: BN; oraclePriceOffset: number } {
let oraclePriceOffset;
if (limitPrice.eq(ZERO) || oraclePrice.eq(ZERO)) {
oraclePriceOffset = ZERO;
} else {
oraclePriceOffset = limitPrice.sub(oraclePrice);
}
if (oraclePriceOffset.eq(ZERO)) {
oraclePriceOffset = isVariant(direction, 'long')
? auctionEndPrice.sub(oraclePrice).add(ONE)
: auctionEndPrice.sub(oraclePrice).sub(ONE);
}
let oraclePriceOffsetNum;
try {
oraclePriceOffsetNum = oraclePriceOffset.toNumber();
} catch (e) {
oraclePriceOffsetNum = 0;
}
if (auctionPriceCaps) {
auctionStartPrice = BN.min(
BN.max(auctionStartPrice, auctionPriceCaps.min),
auctionPriceCaps.max
);
auctionEndPrice = BN.min(
BN.max(auctionEndPrice, auctionPriceCaps.min),
auctionPriceCaps.max
);
}
return {
auctionStartPrice: auctionStartPrice.sub(oraclePrice),
auctionEndPrice: auctionEndPrice.sub(oraclePrice),
oraclePriceOffset: oraclePriceOffsetNum,
};
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/spotBalance.ts
|
import {
SpotMarketAccount,
SpotBalanceType,
isVariant,
MarginCategory,
} from '../types';
import { BN } from '@coral-xyz/anchor';
import {
SPOT_MARKET_UTILIZATION_PRECISION,
ONE,
TEN,
ZERO,
SPOT_MARKET_RATE_PRECISION,
SPOT_MARKET_WEIGHT_PRECISION,
ONE_YEAR,
AMM_RESERVE_PRECISION,
} from '../constants/numericConstants';
import {
calculateSizeDiscountAssetWeight,
calculateSizePremiumLiabilityWeight,
} from './margin';
import { OraclePriceData } from '../oracles/types';
import { PERCENTAGE_PRECISION } from '../constants/numericConstants';
import { divCeil } from './utils';
import { StrictOraclePrice } from '../oracles/strictOraclePrice';
/**
* Calculates the balance of a given token amount including any accumulated interest. This
* is the same as `SpotPosition.scaledBalance`.
*
* @param {BN} tokenAmount - the amount of tokens
* @param {SpotMarketAccount} spotMarket - the spot market account
* @param {SpotBalanceType} balanceType - the balance type ('deposit' or 'borrow')
* @return {BN} the calculated balance, scaled by `SPOT_MARKET_BALANCE_PRECISION`
*/
export function getBalance(
tokenAmount: BN,
spotMarket: SpotMarketAccount,
balanceType: SpotBalanceType
): BN {
const precisionIncrease = TEN.pow(new BN(19 - spotMarket.decimals));
const cumulativeInterest = isVariant(balanceType, 'deposit')
? spotMarket.cumulativeDepositInterest
: spotMarket.cumulativeBorrowInterest;
let balance = tokenAmount.mul(precisionIncrease).div(cumulativeInterest);
if (!balance.eq(ZERO) && isVariant(balanceType, 'borrow')) {
balance = balance.add(ONE);
}
return balance;
}
/**
* Calculates the spot token amount including any accumulated interest.
*
* @param {BN} balanceAmount - The balance amount, typically from `SpotPosition.scaledBalance`
* @param {SpotMarketAccount} spotMarket - The spot market account details
* @param {SpotBalanceType} balanceType - The balance type to be used for calculation
* @returns {BN} The calculated token amount, scaled by `SpotMarketConfig.precision`
*/
export function getTokenAmount(
balanceAmount: BN,
spotMarket: SpotMarketAccount,
balanceType: SpotBalanceType
): BN {
const precisionDecrease = TEN.pow(new BN(19 - spotMarket.decimals));
if (isVariant(balanceType, 'deposit')) {
return balanceAmount
.mul(spotMarket.cumulativeDepositInterest)
.div(precisionDecrease);
} else {
return divCeil(
balanceAmount.mul(spotMarket.cumulativeBorrowInterest),
precisionDecrease
);
}
}
/**
* Returns the signed (positive for deposit,negative for borrow) token amount based on the balance type.
*
* @param {BN} tokenAmount - The token amount to convert (from `getTokenAmount`)
* @param {SpotBalanceType} balanceType - The balance type to determine the sign of the token amount.
* @returns {BN} - The signed token amount, scaled by `SpotMarketConfig.precision`
*/
export function getSignedTokenAmount(
tokenAmount: BN,
balanceType: SpotBalanceType
): BN {
if (isVariant(balanceType, 'deposit')) {
return tokenAmount;
} else {
return tokenAmount.abs().neg();
}
}
/**
* Calculates the value of a given token amount using the worst of the provided oracle price and its TWAP.
*
* @param {BN} tokenAmount - The amount of tokens to calculate the value for (from `getTokenAmount`)
* @param {number} spotDecimals - The number of decimals in the token.
* @param {StrictOraclePrice} strictOraclePrice - Contains oracle price and 5min twap.
* @return {BN} The calculated value of the given token amount, scaled by `PRICE_PRECISION`
*/
export function getStrictTokenValue(
tokenAmount: BN,
spotDecimals: number,
strictOraclePrice: StrictOraclePrice
): BN {
if (tokenAmount.eq(ZERO)) {
return ZERO;
}
let price;
if (tokenAmount.gte(ZERO)) {
price = strictOraclePrice.min();
} else {
price = strictOraclePrice.max();
}
const precisionDecrease = TEN.pow(new BN(spotDecimals));
return tokenAmount.mul(price).div(precisionDecrease);
}
/**
* Calculates the value of a given token amount in relation to an oracle price data
*
* @param {BN} tokenAmount - The amount of tokens to calculate the value for (from `getTokenAmount`)
* @param {number} spotDecimals - The number of decimal places of the token.
* @param {OraclePriceData} oraclePriceData - The oracle price data (typically a token/USD oracle).
* @return {BN} The value of the token based on the oracle, scaled by `PRICE_PRECISION`
*/
export function getTokenValue(
tokenAmount: BN,
spotDecimals: number,
oraclePriceData: Pick<OraclePriceData, 'price'>
): BN {
if (tokenAmount.eq(ZERO)) {
return ZERO;
}
const precisionDecrease = TEN.pow(new BN(spotDecimals));
return tokenAmount.mul(oraclePriceData.price).div(precisionDecrease);
}
export function calculateAssetWeight(
balanceAmount: BN,
oraclePrice: BN,
spotMarket: SpotMarketAccount,
marginCategory: MarginCategory
): BN {
const sizePrecision = TEN.pow(new BN(spotMarket.decimals));
let sizeInAmmReservePrecision;
if (sizePrecision.gt(AMM_RESERVE_PRECISION)) {
sizeInAmmReservePrecision = balanceAmount.div(
sizePrecision.div(AMM_RESERVE_PRECISION)
);
} else {
sizeInAmmReservePrecision = balanceAmount
.mul(AMM_RESERVE_PRECISION)
.div(sizePrecision);
}
let assetWeight;
switch (marginCategory) {
case 'Initial':
assetWeight = calculateSizeDiscountAssetWeight(
sizeInAmmReservePrecision,
new BN(spotMarket.imfFactor),
calculateScaledInitialAssetWeight(spotMarket, oraclePrice)
);
break;
case 'Maintenance':
assetWeight = calculateSizeDiscountAssetWeight(
sizeInAmmReservePrecision,
new BN(spotMarket.imfFactor),
new BN(spotMarket.maintenanceAssetWeight)
);
break;
default:
assetWeight = calculateScaledInitialAssetWeight(spotMarket, oraclePrice);
break;
}
return assetWeight;
}
export function calculateScaledInitialAssetWeight(
spotMarket: SpotMarketAccount,
oraclePrice: BN
): BN {
if (spotMarket.scaleInitialAssetWeightStart.eq(ZERO)) {
return new BN(spotMarket.initialAssetWeight);
}
const deposits = getTokenAmount(
spotMarket.depositBalance,
spotMarket,
SpotBalanceType.DEPOSIT
);
const depositsValue = getTokenValue(deposits, spotMarket.decimals, {
price: oraclePrice,
});
if (depositsValue.lt(spotMarket.scaleInitialAssetWeightStart)) {
return new BN(spotMarket.initialAssetWeight);
} else {
return new BN(spotMarket.initialAssetWeight)
.mul(spotMarket.scaleInitialAssetWeightStart)
.div(depositsValue);
}
}
export function calculateLiabilityWeight(
size: BN,
spotMarket: SpotMarketAccount,
marginCategory: MarginCategory
): BN {
const sizePrecision = TEN.pow(new BN(spotMarket.decimals));
let sizeInAmmReservePrecision;
if (sizePrecision.gt(AMM_RESERVE_PRECISION)) {
sizeInAmmReservePrecision = size.div(
sizePrecision.div(AMM_RESERVE_PRECISION)
);
} else {
sizeInAmmReservePrecision = size
.mul(AMM_RESERVE_PRECISION)
.div(sizePrecision);
}
let liabilityWeight;
switch (marginCategory) {
case 'Initial':
liabilityWeight = calculateSizePremiumLiabilityWeight(
sizeInAmmReservePrecision,
new BN(spotMarket.imfFactor),
new BN(spotMarket.initialLiabilityWeight),
SPOT_MARKET_WEIGHT_PRECISION
);
break;
case 'Maintenance':
liabilityWeight = calculateSizePremiumLiabilityWeight(
sizeInAmmReservePrecision,
new BN(spotMarket.imfFactor),
new BN(spotMarket.maintenanceLiabilityWeight),
SPOT_MARKET_WEIGHT_PRECISION
);
break;
default:
liabilityWeight = new BN(spotMarket.initialLiabilityWeight);
break;
}
return liabilityWeight;
}
export function calculateUtilization(
bank: SpotMarketAccount,
delta = ZERO
): BN {
let tokenDepositAmount = getTokenAmount(
bank.depositBalance,
bank,
SpotBalanceType.DEPOSIT
);
let tokenBorrowAmount = getTokenAmount(
bank.borrowBalance,
bank,
SpotBalanceType.BORROW
);
if (delta.gt(ZERO)) {
tokenDepositAmount = tokenDepositAmount.add(delta);
} else if (delta.lt(ZERO)) {
tokenBorrowAmount = tokenBorrowAmount.add(delta.abs());
}
let utilization: BN;
if (tokenBorrowAmount.eq(ZERO) && tokenDepositAmount.eq(ZERO)) {
utilization = ZERO;
} else if (tokenDepositAmount.eq(ZERO)) {
utilization = SPOT_MARKET_UTILIZATION_PRECISION;
} else {
utilization = tokenBorrowAmount
.mul(SPOT_MARKET_UTILIZATION_PRECISION)
.div(tokenDepositAmount);
}
return utilization;
}
/**
* calculates max borrow amount where rate would stay below targetBorrowRate
* @param spotMarketAccount
* @param targetBorrowRate
* @returns : Precision: TOKEN DECIMALS
*/
export function calculateSpotMarketBorrowCapacity(
spotMarketAccount: SpotMarketAccount,
targetBorrowRate: BN
): { totalCapacity: BN; remainingCapacity: BN } {
const currentBorrowRate = calculateBorrowRate(spotMarketAccount);
const tokenDepositAmount = getTokenAmount(
spotMarketAccount.depositBalance,
spotMarketAccount,
SpotBalanceType.DEPOSIT
);
const tokenBorrowAmount = getTokenAmount(
spotMarketAccount.borrowBalance,
spotMarketAccount,
SpotBalanceType.BORROW
);
let targetUtilization;
// target utilization past mid point
if (targetBorrowRate.gte(new BN(spotMarketAccount.optimalBorrowRate))) {
const borrowRateSlope = new BN(
spotMarketAccount.maxBorrowRate - spotMarketAccount.optimalBorrowRate
)
.mul(SPOT_MARKET_UTILIZATION_PRECISION)
.div(
SPOT_MARKET_UTILIZATION_PRECISION.sub(
new BN(spotMarketAccount.optimalUtilization)
)
);
const surplusTargetUtilization = targetBorrowRate
.sub(new BN(spotMarketAccount.optimalBorrowRate))
.mul(SPOT_MARKET_UTILIZATION_PRECISION)
.div(borrowRateSlope);
targetUtilization = surplusTargetUtilization.add(
new BN(spotMarketAccount.optimalUtilization)
);
} else {
const borrowRateSlope = new BN(spotMarketAccount.optimalBorrowRate)
.mul(SPOT_MARKET_UTILIZATION_PRECISION)
.div(new BN(spotMarketAccount.optimalUtilization));
targetUtilization = targetBorrowRate
.mul(SPOT_MARKET_UTILIZATION_PRECISION)
.div(borrowRateSlope);
}
const totalCapacity = tokenDepositAmount
.mul(targetUtilization)
.div(SPOT_MARKET_UTILIZATION_PRECISION);
let remainingCapacity;
if (currentBorrowRate.gte(targetBorrowRate)) {
remainingCapacity = ZERO;
} else {
remainingCapacity = BN.max(ZERO, totalCapacity.sub(tokenBorrowAmount));
}
if (spotMarketAccount.maxTokenBorrowsFraction > 0) {
const maxTokenBorrows = spotMarketAccount.maxTokenDeposits
.mul(new BN(spotMarketAccount.maxTokenBorrowsFraction))
.divn(10000);
remainingCapacity = BN.min(
remainingCapacity,
BN.max(ZERO, maxTokenBorrows.sub(tokenBorrowAmount))
);
}
return { totalCapacity, remainingCapacity };
}
export function calculateInterestRate(
bank: SpotMarketAccount,
delta = ZERO,
currentUtilization: BN = null
): BN {
const utilization = currentUtilization || calculateUtilization(bank, delta);
let interestRate: BN;
if (utilization.gt(new BN(bank.optimalUtilization))) {
const surplusUtilization = utilization.sub(new BN(bank.optimalUtilization));
const borrowRateSlope = new BN(bank.maxBorrowRate - bank.optimalBorrowRate)
.mul(SPOT_MARKET_UTILIZATION_PRECISION)
.div(
SPOT_MARKET_UTILIZATION_PRECISION.sub(new BN(bank.optimalUtilization))
);
interestRate = new BN(bank.optimalBorrowRate).add(
surplusUtilization
.mul(borrowRateSlope)
.div(SPOT_MARKET_UTILIZATION_PRECISION)
);
} else {
const borrowRateSlope = new BN(bank.optimalBorrowRate)
.mul(SPOT_MARKET_UTILIZATION_PRECISION)
.div(new BN(bank.optimalUtilization));
interestRate = utilization
.mul(borrowRateSlope)
.div(SPOT_MARKET_UTILIZATION_PRECISION);
}
return BN.max(
interestRate,
new BN(bank.minBorrowRate).mul(PERCENTAGE_PRECISION.divn(200))
);
}
export function calculateDepositRate(
bank: SpotMarketAccount,
delta = ZERO,
currentUtilization: BN = null
): BN {
// positive delta => adding to deposit
// negative delta => adding to borrow
const utilization = currentUtilization || calculateUtilization(bank, delta);
const borrowRate = calculateBorrowRate(bank, delta, utilization);
const depositRate = borrowRate
.mul(PERCENTAGE_PRECISION.sub(new BN(bank.insuranceFund.totalFactor)))
.mul(utilization)
.div(SPOT_MARKET_UTILIZATION_PRECISION)
.div(PERCENTAGE_PRECISION);
return depositRate;
}
export function calculateBorrowRate(
bank: SpotMarketAccount,
delta = ZERO,
currentUtilization: BN = null
): BN {
return calculateInterestRate(bank, delta, currentUtilization);
}
export function calculateInterestAccumulated(
bank: SpotMarketAccount,
now: BN
): { borrowInterest: BN; depositInterest: BN } {
const interestRate = calculateInterestRate(bank);
const timeSinceLastUpdate = now.sub(bank.lastInterestTs);
const modifiedBorrowRate = interestRate.mul(timeSinceLastUpdate);
const utilization = calculateUtilization(bank);
const modifiedDepositRate = modifiedBorrowRate
.mul(utilization)
.div(SPOT_MARKET_UTILIZATION_PRECISION);
const borrowInterest = bank.cumulativeBorrowInterest
.mul(modifiedBorrowRate)
.div(ONE_YEAR)
.div(SPOT_MARKET_RATE_PRECISION)
.add(ONE);
const depositInterest = bank.cumulativeDepositInterest
.mul(modifiedDepositRate)
.div(ONE_YEAR)
.div(SPOT_MARKET_RATE_PRECISION);
return { borrowInterest, depositInterest };
}
export function calculateTokenUtilizationLimits(
depositTokenAmount: BN,
borrowTokenAmount: BN,
spotMarket: SpotMarketAccount
): {
minDepositTokensForUtilization: BN;
maxBorrowTokensForUtilization: BN;
} {
// Calculates the allowable minimum deposit and maximum borrow amounts for immediate withdrawal based on market utilization.
// First, it determines a maximum withdrawal utilization from the market's target and historic utilization.
// Then, it deduces corresponding deposit/borrow amounts.
// Note: For deposit sizes below the guard threshold, withdrawals aren't blocked.
const maxWithdrawUtilization = BN.max(
new BN(spotMarket.optimalUtilization),
spotMarket.utilizationTwap.add(
SPOT_MARKET_UTILIZATION_PRECISION.sub(spotMarket.utilizationTwap).div(
new BN(2)
)
)
);
let minDepositTokensForUtilization = borrowTokenAmount
.mul(SPOT_MARKET_UTILIZATION_PRECISION)
.div(maxWithdrawUtilization);
// don't block withdraws for deposit sizes below guard threshold
minDepositTokensForUtilization = BN.min(
minDepositTokensForUtilization,
depositTokenAmount.sub(spotMarket.withdrawGuardThreshold)
);
let maxBorrowTokensForUtilization = maxWithdrawUtilization
.mul(depositTokenAmount)
.div(SPOT_MARKET_UTILIZATION_PRECISION);
maxBorrowTokensForUtilization = BN.max(
spotMarket.withdrawGuardThreshold,
maxBorrowTokensForUtilization
);
return {
minDepositTokensForUtilization,
maxBorrowTokensForUtilization,
};
}
export function calculateWithdrawLimit(
spotMarket: SpotMarketAccount,
now: BN
): {
borrowLimit: BN;
withdrawLimit: BN;
minDepositAmount: BN;
maxBorrowAmount: BN;
currentDepositAmount;
currentBorrowAmount;
} {
const marketDepositTokenAmount = getTokenAmount(
spotMarket.depositBalance,
spotMarket,
SpotBalanceType.DEPOSIT
);
const marketBorrowTokenAmount = getTokenAmount(
spotMarket.borrowBalance,
spotMarket,
SpotBalanceType.BORROW
);
const twentyFourHours = new BN(60 * 60 * 24);
const sinceLast = now.sub(spotMarket.lastTwapTs);
const sinceStart = BN.max(ZERO, twentyFourHours.sub(sinceLast));
const borrowTokenTwapLive = spotMarket.borrowTokenTwap
.mul(sinceStart)
.add(marketBorrowTokenAmount.mul(sinceLast))
.div(sinceLast.add(sinceStart));
const depositTokenTwapLive = spotMarket.depositTokenTwap
.mul(sinceStart)
.add(marketDepositTokenAmount.mul(sinceLast))
.div(sinceLast.add(sinceStart));
const lesserDepositAmount = BN.min(
marketDepositTokenAmount,
depositTokenTwapLive
);
const maxBorrowTokensTwap = BN.max(
spotMarket.withdrawGuardThreshold,
BN.min(
BN.max(
marketDepositTokenAmount.div(new BN(6)),
borrowTokenTwapLive.add(lesserDepositAmount.div(new BN(10)))
),
lesserDepositAmount.sub(lesserDepositAmount.div(new BN(5)))
)
); // between ~15-80% utilization with friction on twap
const minDepositTokensTwap = depositTokenTwapLive.sub(
BN.max(
depositTokenTwapLive.div(new BN(4)),
BN.min(spotMarket.withdrawGuardThreshold, depositTokenTwapLive)
)
);
const { minDepositTokensForUtilization, maxBorrowTokensForUtilization } =
calculateTokenUtilizationLimits(
marketDepositTokenAmount,
marketBorrowTokenAmount,
spotMarket
);
const minDepositTokens = BN.max(
minDepositTokensForUtilization,
minDepositTokensTwap
);
let maxBorrowTokens = BN.min(
maxBorrowTokensForUtilization,
maxBorrowTokensTwap
);
const withdrawLimit = BN.max(
marketDepositTokenAmount.sub(minDepositTokens),
ZERO
);
let borrowLimit = maxBorrowTokens.sub(marketBorrowTokenAmount);
borrowLimit = BN.min(
borrowLimit,
marketDepositTokenAmount.sub(marketBorrowTokenAmount)
);
if (spotMarket.maxTokenBorrowsFraction > 0) {
const maxTokenBorrowsByFraction = spotMarket.maxTokenDeposits
.mul(new BN(spotMarket.maxTokenBorrowsFraction))
.divn(10000);
const trueMaxBorrowTokensAvailable = maxTokenBorrowsByFraction.sub(
marketBorrowTokenAmount
);
maxBorrowTokens = BN.min(maxBorrowTokens, trueMaxBorrowTokensAvailable);
borrowLimit = BN.min(borrowLimit, maxBorrowTokens);
}
if (withdrawLimit.eq(ZERO)) {
borrowLimit = ZERO;
}
return {
borrowLimit,
withdrawLimit,
maxBorrowAmount: maxBorrowTokens,
minDepositAmount: minDepositTokens,
currentDepositAmount: marketDepositTokenAmount,
currentBorrowAmount: marketBorrowTokenAmount,
};
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/spotPosition.ts
|
import { MarginCategory, SpotMarketAccount, SpotPosition } from '../types';
import {
QUOTE_SPOT_MARKET_INDEX,
SPOT_MARKET_WEIGHT_PRECISION,
ZERO,
} from '../constants/numericConstants';
import { BN } from '@coral-xyz/anchor';
import {
calculateAssetWeight,
calculateLiabilityWeight,
getSignedTokenAmount,
getStrictTokenValue,
getTokenAmount,
getTokenValue,
} from './spotBalance';
import { StrictOraclePrice } from '../oracles/strictOraclePrice';
export function isSpotPositionAvailable(position: SpotPosition): boolean {
return position.scaledBalance.eq(ZERO) && position.openOrders === 0;
}
export type OrderFillSimulation = {
tokenAmount: BN;
ordersValue: BN;
tokenValue: BN;
weight: BN;
weightedTokenValue: BN;
freeCollateralContribution;
};
export function getWorstCaseTokenAmounts(
spotPosition: SpotPosition,
spotMarketAccount: SpotMarketAccount,
strictOraclePrice: StrictOraclePrice,
marginCategory: MarginCategory,
customMarginRatio?: number
): OrderFillSimulation {
const tokenAmount = getSignedTokenAmount(
getTokenAmount(
spotPosition.scaledBalance,
spotMarketAccount,
spotPosition.balanceType
),
spotPosition.balanceType
);
const tokenValue = getStrictTokenValue(
tokenAmount,
spotMarketAccount.decimals,
strictOraclePrice
);
if (spotPosition.openBids.eq(ZERO) && spotPosition.openAsks.eq(ZERO)) {
const { weight, weightedTokenValue } = calculateWeightedTokenValue(
tokenAmount,
tokenValue,
strictOraclePrice.current,
spotMarketAccount,
marginCategory,
customMarginRatio
);
return {
tokenAmount,
ordersValue: ZERO,
tokenValue,
weight,
weightedTokenValue,
freeCollateralContribution: weightedTokenValue,
};
}
const bidsSimulation = simulateOrderFill(
tokenAmount,
tokenValue,
spotPosition.openBids,
strictOraclePrice,
spotMarketAccount,
marginCategory,
customMarginRatio
);
const asksSimulation = simulateOrderFill(
tokenAmount,
tokenValue,
spotPosition.openAsks,
strictOraclePrice,
spotMarketAccount,
marginCategory,
customMarginRatio
);
if (
asksSimulation.freeCollateralContribution.lt(
bidsSimulation.freeCollateralContribution
)
) {
return asksSimulation;
} else {
return bidsSimulation;
}
}
export function calculateWeightedTokenValue(
tokenAmount: BN,
tokenValue: BN,
oraclePrice: BN,
spotMarket: SpotMarketAccount,
marginCategory: MarginCategory,
customMarginRatio?: number
): { weight: BN; weightedTokenValue: BN } {
let weight: BN;
if (tokenValue.gte(ZERO)) {
weight = calculateAssetWeight(
tokenAmount,
oraclePrice,
spotMarket,
marginCategory
);
} else {
weight = calculateLiabilityWeight(
tokenAmount.abs(),
spotMarket,
marginCategory
);
}
if (
marginCategory === 'Initial' &&
customMarginRatio &&
spotMarket.marketIndex !== QUOTE_SPOT_MARKET_INDEX
) {
const userCustomAssetWeight = tokenValue.gte(ZERO)
? BN.max(ZERO, SPOT_MARKET_WEIGHT_PRECISION.subn(customMarginRatio))
: SPOT_MARKET_WEIGHT_PRECISION.addn(customMarginRatio);
weight = tokenValue.gte(ZERO)
? BN.min(weight, userCustomAssetWeight)
: BN.max(weight, userCustomAssetWeight);
}
return {
weight: weight,
weightedTokenValue: tokenValue
.mul(weight)
.div(SPOT_MARKET_WEIGHT_PRECISION),
};
}
export function simulateOrderFill(
tokenAmount: BN,
tokenValue: BN,
openOrders: BN,
strictOraclePrice: StrictOraclePrice,
spotMarket: SpotMarketAccount,
marginCategory: MarginCategory,
customMarginRatio?: number
): OrderFillSimulation {
const ordersValue = getTokenValue(openOrders.neg(), spotMarket.decimals, {
price: strictOraclePrice.max(),
});
const tokenAmountAfterFill = tokenAmount.add(openOrders);
const tokenValueAfterFill = tokenValue.add(ordersValue.neg());
const { weight, weightedTokenValue: weightedTokenValueAfterFill } =
calculateWeightedTokenValue(
tokenAmountAfterFill,
tokenValueAfterFill,
strictOraclePrice.current,
spotMarket,
marginCategory,
customMarginRatio
);
const freeCollateralContribution =
weightedTokenValueAfterFill.add(ordersValue);
return {
tokenAmount: tokenAmountAfterFill,
ordersValue: ordersValue,
tokenValue: tokenValueAfterFill,
weight,
weightedTokenValue: weightedTokenValueAfterFill,
freeCollateralContribution,
};
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/position.ts
|
import { BN, SpotMarketAccount } from '../';
import {
AMM_RESERVE_PRECISION,
AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO,
AMM_TO_QUOTE_PRECISION_RATIO,
FUNDING_RATE_BUFFER_PRECISION,
PRICE_PRECISION,
ONE,
ZERO,
} from '../constants/numericConstants';
import { OraclePriceData } from '../oracles/types';
import { PerpMarketAccount, PositionDirection, PerpPosition } from '../types';
import {
calculateUpdatedAMM,
calculateUpdatedAMMSpreadReserves,
calculateAmmReservesAfterSwap,
getSwapDirection,
} from './amm';
import { calculateBaseAssetValueWithOracle } from './margin';
import { calculateNetUserPnlImbalance } from './market';
/**
* calculateBaseAssetValue
* = market value of closing entire position
* @param market
* @param userPosition
* @param oraclePriceData
* @returns Base Asset Value. : Precision QUOTE_PRECISION
*/
export function calculateBaseAssetValue(
market: PerpMarketAccount,
userPosition: PerpPosition,
oraclePriceData: OraclePriceData,
useSpread = true,
skipUpdate = false
): BN {
if (userPosition.baseAssetAmount.eq(ZERO)) {
return ZERO;
}
const directionToClose = findDirectionToClose(userPosition);
let prepegAmm: Parameters<typeof calculateAmmReservesAfterSwap>[0];
if (!skipUpdate) {
if (market.amm.baseSpread > 0 && useSpread) {
const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } =
calculateUpdatedAMMSpreadReserves(
market.amm,
directionToClose,
oraclePriceData
);
prepegAmm = {
baseAssetReserve,
quoteAssetReserve,
sqrtK: sqrtK,
pegMultiplier: newPeg,
};
} else {
prepegAmm = calculateUpdatedAMM(market.amm, oraclePriceData);
}
} else {
prepegAmm = market.amm;
}
const [newQuoteAssetReserve, _] = calculateAmmReservesAfterSwap(
prepegAmm,
'base',
userPosition.baseAssetAmount.abs(),
getSwapDirection('base', directionToClose)
);
switch (directionToClose) {
case PositionDirection.SHORT:
return prepegAmm.quoteAssetReserve
.sub(newQuoteAssetReserve)
.mul(prepegAmm.pegMultiplier)
.div(AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
case PositionDirection.LONG:
return newQuoteAssetReserve
.sub(prepegAmm.quoteAssetReserve)
.mul(prepegAmm.pegMultiplier)
.div(AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
.add(ONE);
}
}
/**
* calculatePositionPNL
* = BaseAssetAmount * (Avg Exit Price - Avg Entry Price)
* @param market
* @param PerpPosition
* @param withFunding (adds unrealized funding payment pnl to result)
* @param oraclePriceData
* @returns BaseAssetAmount : Precision QUOTE_PRECISION
*/
export function calculatePositionPNL(
market: PerpMarketAccount,
perpPosition: PerpPosition,
withFunding = false,
oraclePriceData: OraclePriceData
): BN {
if (perpPosition.baseAssetAmount.eq(ZERO)) {
return perpPosition.quoteAssetAmount;
}
const baseAssetValue = calculateBaseAssetValueWithOracle(
market,
perpPosition,
oraclePriceData
);
const baseAssetValueSign = perpPosition.baseAssetAmount.isNeg()
? new BN(-1)
: new BN(1);
let pnl = baseAssetValue
.mul(baseAssetValueSign)
.add(perpPosition.quoteAssetAmount);
if (withFunding) {
const fundingRatePnL = calculateUnsettledFundingPnl(market, perpPosition);
pnl = pnl.add(fundingRatePnL);
}
return pnl;
}
export function calculateClaimablePnl(
market: PerpMarketAccount,
spotMarket: SpotMarketAccount,
perpPosition: PerpPosition,
oraclePriceData: OraclePriceData
): BN {
const unrealizedPnl = calculatePositionPNL(
market,
perpPosition,
true,
oraclePriceData
);
let unsettledPnl = unrealizedPnl;
if (unrealizedPnl.gt(ZERO)) {
const excessPnlPool = BN.max(
ZERO,
calculateNetUserPnlImbalance(market, spotMarket, oraclePriceData).mul(
new BN(-1)
)
);
const maxPositivePnl = BN.max(
perpPosition.quoteAssetAmount.sub(perpPosition.quoteEntryAmount),
ZERO
).add(excessPnlPool);
unsettledPnl = BN.min(maxPositivePnl, unrealizedPnl);
}
return unsettledPnl;
}
/**
* Returns total fees and funding pnl for a position
*
* @param market
* @param PerpPosition
* @param includeUnsettled include unsettled funding in return value (default: true)
* @returns — // QUOTE_PRECISION
*/
export function calculateFeesAndFundingPnl(
market: PerpMarketAccount,
perpPosition: PerpPosition,
includeUnsettled = true
): BN {
const settledFundingAndFeesPnl = perpPosition.quoteBreakEvenAmount.sub(
perpPosition.quoteEntryAmount
);
if (!includeUnsettled) {
return settledFundingAndFeesPnl;
}
const unsettledFundingPnl = calculateUnsettledFundingPnl(
market,
perpPosition
);
return settledFundingAndFeesPnl.add(unsettledFundingPnl);
}
/**
* Returns unsettled funding pnl for the position
*
* To calculate all fees and funding pnl including settled, use calculateFeesAndFundingPnl
*
* @param market
* @param PerpPosition
* @returns // QUOTE_PRECISION
*/
export function calculateUnsettledFundingPnl(
market: PerpMarketAccount,
perpPosition: PerpPosition
): BN {
if (perpPosition.baseAssetAmount.eq(ZERO)) {
return ZERO;
}
let ammCumulativeFundingRate: BN;
if (perpPosition.baseAssetAmount.gt(ZERO)) {
ammCumulativeFundingRate = market.amm.cumulativeFundingRateLong;
} else {
ammCumulativeFundingRate = market.amm.cumulativeFundingRateShort;
}
const perPositionFundingRate = ammCumulativeFundingRate
.sub(perpPosition.lastCumulativeFundingRate)
.mul(perpPosition.baseAssetAmount)
.div(AMM_RESERVE_PRECISION)
.div(FUNDING_RATE_BUFFER_PRECISION)
.mul(new BN(-1));
return perPositionFundingRate;
}
/**
* @deprecated use calculateUnsettledFundingPnl or calculateFeesAndFundingPnl instead
*/
export function calculatePositionFundingPNL(
market: PerpMarketAccount,
perpPosition: PerpPosition
): BN {
return calculateUnsettledFundingPnl(market, perpPosition);
}
export function positionIsAvailable(position: PerpPosition): boolean {
return (
position.baseAssetAmount.eq(ZERO) &&
position.openOrders === 0 &&
position.quoteAssetAmount.eq(ZERO) &&
position.lpShares.eq(ZERO)
);
}
/**
*
* @param userPosition
* @returns Precision: PRICE_PRECISION (10^6)
*/
export function calculateBreakEvenPrice(userPosition: PerpPosition): BN {
if (userPosition.baseAssetAmount.eq(ZERO)) {
return ZERO;
}
return userPosition.quoteBreakEvenAmount
.mul(PRICE_PRECISION)
.mul(AMM_TO_QUOTE_PRECISION_RATIO)
.div(userPosition.baseAssetAmount)
.abs();
}
/**
*
* @param userPosition
* @returns Precision: PRICE_PRECISION (10^6)
*/
export function calculateEntryPrice(userPosition: PerpPosition): BN {
if (userPosition.baseAssetAmount.eq(ZERO)) {
return ZERO;
}
return userPosition.quoteEntryAmount
.mul(PRICE_PRECISION)
.mul(AMM_TO_QUOTE_PRECISION_RATIO)
.div(userPosition.baseAssetAmount)
.abs();
}
/**
*
* @param userPosition
* @returns Precision: PRICE_PRECISION (10^10)
*/
export function calculateCostBasis(
userPosition: PerpPosition,
includeSettledPnl = false
): BN {
if (userPosition.baseAssetAmount.eq(ZERO)) {
return ZERO;
}
return userPosition.quoteAssetAmount
.add(includeSettledPnl ? userPosition.settledPnl : ZERO)
.mul(PRICE_PRECISION)
.mul(AMM_TO_QUOTE_PRECISION_RATIO)
.div(userPosition.baseAssetAmount)
.abs();
}
export function findDirectionToClose(
userPosition: PerpPosition
): PositionDirection {
return userPosition.baseAssetAmount.gt(ZERO)
? PositionDirection.SHORT
: PositionDirection.LONG;
}
export function positionCurrentDirection(
userPosition: PerpPosition
): PositionDirection {
return userPosition.baseAssetAmount.gte(ZERO)
? PositionDirection.LONG
: PositionDirection.SHORT;
}
export function isEmptyPosition(userPosition: PerpPosition): boolean {
return userPosition.baseAssetAmount.eq(ZERO) && userPosition.openOrders === 0;
}
export function hasOpenOrders(position: PerpPosition): boolean {
return (
position.openOrders != 0 ||
!position.openBids.eq(ZERO) ||
!position.openAsks.eq(ZERO)
);
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/superStake.ts
|
import {
AddressLookupTableAccount,
LAMPORTS_PER_SOL,
PublicKey,
TransactionInstruction,
} from '@solana/web3.js';
import { JupiterClient, QuoteResponse } from '../jupiter/jupiterClient';
import { DriftClient } from '../driftClient';
import { getMarinadeFinanceProgram, getMarinadeMSolPrice } from '../marinade';
import { BN } from '@coral-xyz/anchor';
import { User } from '../user';
import { DepositRecord, isVariant } from '../types';
import { LAMPORTS_PRECISION, ZERO } from '../constants/numericConstants';
import fetch from 'node-fetch';
import { checkSameDate } from './utils';
export type BSOL_STATS_API_RESPONSE = {
success: boolean;
stats?: {
conversion: {
bsol_to_sol: number;
sol_to_bsol: number;
};
apy: {
base: number;
blze: number;
total: number;
lending: number;
liquidity: number;
};
};
};
export type BSOL_EMISSIONS_API_RESPONSE = {
success: boolean;
emissions?: {
lend: number;
};
};
export async function fetchBSolMetrics() {
return await fetch('https://stake.solblaze.org/api/v1/stats');
}
export async function fetchBSolDriftEmissions() {
return await fetch('https://stake.solblaze.org/api/v1/drift_emissions');
}
export async function findBestSuperStakeIxs({
marketIndex,
amount,
jupiterClient,
driftClient,
userAccountPublicKey,
price,
forceMarinade,
onlyDirectRoutes,
jupiterQuote,
}: {
marketIndex: number;
amount: BN;
jupiterClient: JupiterClient;
driftClient: DriftClient;
price?: number;
userAccountPublicKey?: PublicKey;
forceMarinade?: boolean;
onlyDirectRoutes?: boolean;
jupiterQuote?: QuoteResponse;
}): Promise<{
ixs: TransactionInstruction[];
lookupTables: AddressLookupTableAccount[];
method: 'jupiter' | 'marinade';
price?: number;
}> {
if (marketIndex === 2) {
return findBestMSolSuperStakeIxs({
amount,
jupiterClient,
driftClient,
userAccountPublicKey,
price,
forceMarinade,
onlyDirectRoutes,
jupiterQuote,
});
} else if (marketIndex === 6) {
return findBestJitoSolSuperStakeIxs({
amount,
jupiterClient,
driftClient,
userAccountPublicKey,
onlyDirectRoutes,
jupiterQuote,
});
} else if (marketIndex === 8) {
return findBestLstSuperStakeIxs({
amount,
lstMint: driftClient.getSpotMarketAccount(8).mint,
lstMarketIndex: 8,
jupiterClient,
driftClient,
userAccountPublicKey,
onlyDirectRoutes,
jupiterQuote,
});
} else {
throw new Error(`Unsupported superstake market index: ${marketIndex}`);
}
}
export async function findBestMSolSuperStakeIxs({
amount,
jupiterClient,
driftClient,
userAccountPublicKey,
price,
forceMarinade,
onlyDirectRoutes,
jupiterQuote,
}: {
amount: BN;
jupiterClient: JupiterClient;
driftClient: DriftClient;
price?: number;
userAccountPublicKey?: PublicKey;
forceMarinade?: boolean;
onlyDirectRoutes?: boolean;
jupiterQuote?: QuoteResponse;
}): Promise<{
ixs: TransactionInstruction[];
lookupTables: AddressLookupTableAccount[];
method: 'jupiter' | 'marinade';
price: number;
}> {
if (!price) {
const marinadeProgram = getMarinadeFinanceProgram(driftClient.provider);
price = await getMarinadeMSolPrice(marinadeProgram);
}
const solSpotMarketAccount = driftClient.getSpotMarketAccount(1);
const mSolSpotMarketAccount = driftClient.getSpotMarketAccount(2);
let jupiterPrice: number;
let quote = jupiterQuote;
if (!jupiterQuote) {
try {
const fetchedQuote = await jupiterClient.getQuote({
inputMint: solSpotMarketAccount.mint,
outputMint: mSolSpotMarketAccount.mint,
amount,
slippageBps: 1000,
onlyDirectRoutes,
});
jupiterPrice = +quote.outAmount / +quote.inAmount;
quote = fetchedQuote;
} catch (e) {
console.error('Error getting jupiter price', e);
}
}
if (!jupiterPrice || price <= jupiterPrice || forceMarinade) {
const ixs = await driftClient.getStakeForMSOLIx({
amount,
userAccountPublicKey,
});
return {
method: 'marinade',
ixs,
lookupTables: [],
price: price,
};
} else {
const { ixs, lookupTables } = await driftClient.getJupiterSwapIxV6({
inMarketIndex: 1,
outMarketIndex: 2,
jupiterClient,
amount,
userAccountPublicKey,
onlyDirectRoutes,
quote,
});
return {
method: 'jupiter',
ixs,
lookupTables,
price: jupiterPrice,
};
}
}
export async function findBestJitoSolSuperStakeIxs({
amount,
jupiterClient,
driftClient,
userAccountPublicKey,
onlyDirectRoutes,
jupiterQuote,
}: {
amount: BN;
jupiterClient: JupiterClient;
driftClient: DriftClient;
userAccountPublicKey?: PublicKey;
onlyDirectRoutes?: boolean;
jupiterQuote?: QuoteResponse;
}): Promise<{
ixs: TransactionInstruction[];
lookupTables: AddressLookupTableAccount[];
method: 'jupiter' | 'marinade';
price?: number;
}> {
return await findBestLstSuperStakeIxs({
amount,
jupiterClient,
driftClient,
userAccountPublicKey,
onlyDirectRoutes,
lstMint: driftClient.getSpotMarketAccount(6).mint,
lstMarketIndex: 6,
jupiterQuote,
});
}
/**
* Finds best Jupiter Swap instructions for a generic lstMint
*
* Without doing any extra steps like checking if you can get a better rate by staking directly with that LST platform
*/
export async function findBestLstSuperStakeIxs({
amount,
jupiterClient,
driftClient,
userAccountPublicKey,
onlyDirectRoutes,
lstMarketIndex,
jupiterQuote,
}: {
amount: BN;
lstMint: PublicKey;
lstMarketIndex: number;
jupiterClient: JupiterClient;
driftClient: DriftClient;
userAccountPublicKey?: PublicKey;
onlyDirectRoutes?: boolean;
jupiterQuote?: QuoteResponse;
}): Promise<{
ixs: TransactionInstruction[];
lookupTables: AddressLookupTableAccount[];
method: 'jupiter' | 'marinade';
}> {
const { ixs, lookupTables } = await driftClient.getJupiterSwapIxV6({
inMarketIndex: 1,
outMarketIndex: lstMarketIndex,
jupiterClient,
amount,
userAccountPublicKey,
onlyDirectRoutes,
quote: jupiterQuote,
});
return {
method: 'jupiter',
ixs,
lookupTables,
// price: jupiterPrice,
};
}
export type JITO_SOL_METRICS_ENDPOINT_RESPONSE = {
tvl: {
// TVL in SOL, BN
data: number;
date: string;
}[];
supply: {
// jitoSOL supply
data: number;
date: string;
}[];
apy: {
data: number;
date: string;
}[];
};
/**
* Removes hours, minutes, seconds from a date, and returns the ISO string value (with milliseconds trimmed from the output (required by Jito API))
* @param inDate
* @returns
*/
const getNormalizedDateString = (inDate: Date) => {
const date = new Date(inDate.getTime());
date.setUTCHours(0, 0, 0, 0);
return date.toISOString().slice(0, 19) + 'Z';
};
const get30DAgo = () => {
const date = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
return date;
};
export async function fetchJitoSolMetrics() {
const res = await fetch(
'https://kobe.mainnet.jito.network/api/v1/stake_pool_stats',
{
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
bucket_type: 'Daily',
range_filter: {
start: getNormalizedDateString(get30DAgo()),
end: getNormalizedDateString(new Date()),
},
sort_by: {
order: 'Asc',
field: 'BlockTime',
},
}),
method: 'POST',
}
);
const data: JITO_SOL_METRICS_ENDPOINT_RESPONSE = await res.json();
return data;
}
export type MSOL_METRICS_ENDPOINT_RESPONSE = {
total_active_balance: number;
available_reserve_balance: number;
emergency_cooling_down: number;
tvl_sol: number;
msol_directed_stake_sol: number;
msol_directed_stake_msol: number;
mnde_total_supply: number;
mnde_circulating_supply: number;
validators_count: number;
stake_accounts: number;
staking_sol_cap: number;
m_sol_price: number;
avg_staking_apy: number;
msol_price_apy_14d: number;
msol_price_apy_30d: number;
msol_price_apy_90d: number;
msol_price_apy_365d: number;
reserve_pda: number;
treasury_m_sol_amount: number;
m_sol_mint_supply: number;
m_sol_supply_state: number;
liq_pool_sol: number;
liq_pool_m_sol: number;
liq_pool_value: number;
liq_pool_token_supply: number;
liq_pool_token_price: number;
liq_pool_target: number;
liq_pool_min_fee: number;
liq_pool_max_fee: number;
liq_pool_current_fee: number;
liq_pool_treasury_cut: number;
liq_pool_cap: number;
total_cooling_down: number;
last_stake_delta_epoch: number;
circulating_ticket_count: number;
circulating_ticket_balance: number;
reward_fee_bp: number;
lido_staking: number;
lido_st_sol_price: number;
lido_stsol_price_apy_14d: number;
lido_stsol_price_apy_30d: number;
lido_stsol_price_apy_90d: number;
lido_stsol_price_apy_365d: number;
stake_delta: number;
bot_balance: number;
treasury_farm_claim_mnde_balance: number;
last_3_epochs_avg_duration_hs: number;
mnde_votes_validators: number;
};
export const fetchMSolMetrics = async () => {
const res = await fetch('https://api2.marinade.finance/metrics_json');
const data: MSOL_METRICS_ENDPOINT_RESPONSE = await res.json();
return data;
};
const getJitoSolHistoricalPriceMap = async (timestamps: number[]) => {
try {
const data = await fetchJitoSolMetrics();
const jitoSolHistoricalPriceMap = new Map<number, number>();
const jitoSolHistoricalPriceInSol = [];
for (let i = 0; i < data.supply.length; i++) {
const priceInSol = data.tvl[i].data / 10 ** 9 / data.supply[i].data;
jitoSolHistoricalPriceInSol.push({
price: priceInSol,
ts: data.tvl[i].date,
});
}
for (const timestamp of timestamps) {
const date = new Date(timestamp * 1000);
const dateString = date.toISOString();
const price = jitoSolHistoricalPriceInSol.find((p) =>
checkSameDate(p.ts, dateString)
);
if (price) {
jitoSolHistoricalPriceMap.set(timestamp, price.price);
}
}
return jitoSolHistoricalPriceMap;
} catch (err) {
console.error(err);
return undefined;
}
};
export async function calculateSolEarned({
marketIndex,
user,
depositRecords,
}: {
marketIndex: number;
user: User;
depositRecords: DepositRecord[];
}): Promise<BN> {
const now = Date.now() / 1000;
const timestamps: number[] = [
now,
...depositRecords
.filter((r) => r.marketIndex === marketIndex)
.map((r) => r.ts.toNumber()),
];
let lstRatios = new Map<number, number>();
const getMsolPrice = async (timestamp) => {
const date = new Date(timestamp * 1000); // Convert Unix timestamp to milliseconds
const swaggerApiDateTime = date.toISOString(); // Format date as swagger API date-time
const url = `https://api.marinade.finance/msol/price_sol?time=${swaggerApiDateTime}`;
const response = await fetch(url);
if (response.status === 200) {
const data = await response.json();
lstRatios.set(timestamp, data);
}
};
const getBSolPrice = async (timestamps: number[]) => {
// Currently there's only one bSOL price, no timestamped data
// So just use the same price for every timestamp for now
const response = await fetchBSolMetrics();
if (response.status === 200) {
const data = (await response.json()) as BSOL_STATS_API_RESPONSE;
const bSolRatio = data?.stats?.conversion?.bsol_to_sol;
if (bSolRatio) {
timestamps.forEach((timestamp) => lstRatios.set(timestamp, bSolRatio));
}
}
};
// This block kind of assumes the record are all from the same market
// Otherwise the following code that checks the record.marketIndex would break
if (marketIndex === 2) {
await Promise.all(timestamps.map(getMsolPrice));
} else if (marketIndex === 6) {
lstRatios = await getJitoSolHistoricalPriceMap(timestamps);
} else if (marketIndex === 8) {
await getBSolPrice(timestamps);
}
let solEarned = ZERO;
for (const record of depositRecords) {
if (record.marketIndex === 1) {
if (isVariant(record.direction, 'deposit')) {
solEarned = solEarned.sub(record.amount);
} else {
solEarned = solEarned.add(record.amount);
}
} else if (
record.marketIndex === 2 ||
record.marketIndex === 6 ||
record.marketIndex === 8
) {
const lstRatio = lstRatios.get(record.ts.toNumber());
const lstRatioBN = new BN(lstRatio * LAMPORTS_PER_SOL);
const solAmount = record.amount.mul(lstRatioBN).div(LAMPORTS_PRECISION);
if (isVariant(record.direction, 'deposit')) {
solEarned = solEarned.sub(solAmount);
} else {
solEarned = solEarned.add(solAmount);
}
}
}
const currentLstTokenAmount = await user.getTokenAmount(marketIndex);
const currentLstRatio = lstRatios.get(now);
const currentLstRatioBN = new BN(currentLstRatio * LAMPORTS_PER_SOL);
solEarned = solEarned.add(
currentLstTokenAmount.mul(currentLstRatioBN).div(LAMPORTS_PRECISION)
);
const currentSOLTokenAmount = await user.getTokenAmount(1);
solEarned = solEarned.add(currentSOLTokenAmount);
return solEarned;
}
// calculate estimated liquidation price (in LST/SOL) based on target amounts
export function calculateEstimatedSuperStakeLiquidationPrice(
lstDepositAmount: number,
lstMaintenanceAssetWeight: number,
solBorrowAmount: number,
solMaintenanceLiabilityWeight: number,
lstPriceRatio: number
): number {
const liquidationDivergence =
(solMaintenanceLiabilityWeight * solBorrowAmount) /
(lstMaintenanceAssetWeight * lstDepositAmount * lstPriceRatio);
const liquidationPrice = lstPriceRatio * liquidationDivergence;
return liquidationPrice;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/utils.ts
|
import { BN, ONE, ZERO } from '../';
export function clampBN(x: BN, min: BN, max: BN): BN {
return BN.max(min, BN.min(x, max));
}
export const squareRootBN = (n: BN): BN => {
if (n.lt(new BN(0))) {
throw new Error('Sqrt only works on non-negtiave inputs');
}
if (n.lt(new BN(2))) {
return n;
}
const smallCand = squareRootBN(n.shrn(2)).shln(1);
const largeCand = smallCand.add(new BN(1));
if (largeCand.mul(largeCand).gt(n)) {
return smallCand;
} else {
return largeCand;
}
};
export const divCeil = (a: BN, b: BN): BN => {
const quotient = a.div(b);
const remainder = a.mod(b);
if (remainder.gt(ZERO)) {
return quotient.add(ONE);
} else {
return quotient;
}
};
export const sigNum = (x: BN): BN => {
return x.isNeg() ? new BN(-1) : new BN(1);
};
/**
* calculates the time remaining until the next update based on a rounded, "on-the-hour" update schedule
* this schedule is used for Perpetual Funding Rate and Revenue -> Insurance Updates
* @param now: current blockchain unix timestamp
* @param lastUpdateTs: the unix timestamp of the last update
* @param updatePeriod: desired interval between updates (in seconds)
* @returns: timeRemainingUntilUpdate (in seconds)
*/
export function timeRemainingUntilUpdate(
now: BN,
lastUpdateTs: BN,
updatePeriod: BN
): BN {
const timeSinceLastUpdate = now.sub(lastUpdateTs);
// round next update time to be available on the hour
let nextUpdateWait = updatePeriod;
if (updatePeriod.gt(new BN(1))) {
const lastUpdateDelay = lastUpdateTs.umod(updatePeriod);
if (!lastUpdateDelay.isZero()) {
const maxDelayForNextPeriod = updatePeriod.div(new BN(3));
const twoFundingPeriods = updatePeriod.mul(new BN(2));
if (lastUpdateDelay.gt(maxDelayForNextPeriod)) {
// too late for on the hour next period, delay to following period
nextUpdateWait = twoFundingPeriods.sub(lastUpdateDelay);
} else {
// allow update on the hour
nextUpdateWait = updatePeriod.sub(lastUpdateDelay);
}
if (nextUpdateWait.gt(twoFundingPeriods)) {
nextUpdateWait = nextUpdateWait.sub(updatePeriod);
}
}
}
const timeRemainingUntilUpdate = nextUpdateWait
.sub(timeSinceLastUpdate)
.isNeg()
? ZERO
: nextUpdateWait.sub(timeSinceLastUpdate);
return timeRemainingUntilUpdate;
}
export const checkSameDate = (dateString1: string, dateString2: string) => {
const date1 = new Date(dateString1);
const date2 = new Date(dateString2);
const isSameDate =
date1.getDate() === date2.getDate() &&
date1.getMonth() === date2.getMonth() &&
date1.getFullYear() === date2.getFullYear();
return isSameDate;
};
export function isBNSafe(number: number): boolean {
return number <= 0x1fffffffffffff;
}
/**
* Converts a number to BN makes sure the number is safe to convert to BN (that it does not overflow number after multiplying by precision)
* @param number the number to convert to BN
* @param precision the BN precision to use (i.e. QUOTE_PRECISION and BASE_PRECISION from drift sdk)
*/
export function numberToSafeBN(number: number, precision: BN): BN {
// check if number has decimals
const candidate = number * precision.toNumber();
if (isBNSafe(candidate)) {
return new BN(candidate);
} else {
if (number % 1 === 0) {
return new BN(number.toString()).mul(precision);
} else {
return new BN(number).mul(precision);
}
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/exchangeStatus.ts
|
import {
DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT,
PERCENTAGE_PRECISION,
ONE,
} from '../constants/numericConstants';
import {
ExchangeStatus,
PerpMarketAccount,
PerpOperation,
SpotMarketAccount,
SpotOperation,
StateAccount,
isVariant,
InsuranceFundOperation,
} from '../types';
import { BN } from '@coral-xyz/anchor';
export function exchangePaused(state: StateAccount): boolean {
return state.exchangeStatus !== ExchangeStatus.ACTIVE;
}
export function fillPaused(
state: StateAccount,
market: PerpMarketAccount | SpotMarketAccount
): boolean {
if (
(state.exchangeStatus & ExchangeStatus.FILL_PAUSED) ===
ExchangeStatus.FILL_PAUSED
) {
return true;
}
if (market.hasOwnProperty('amm')) {
return isOperationPaused(market.pausedOperations, PerpOperation.FILL);
} else {
return isOperationPaused(market.pausedOperations, SpotOperation.FILL);
}
}
export function ammPaused(
state: StateAccount,
market: PerpMarketAccount | SpotMarketAccount
): boolean {
if (
(state.exchangeStatus & ExchangeStatus.AMM_PAUSED) ===
ExchangeStatus.AMM_PAUSED
) {
return true;
}
if (market.hasOwnProperty('amm')) {
const operationPaused = isOperationPaused(
market.pausedOperations,
PerpOperation.AMM_FILL
);
if (operationPaused) {
return true;
}
if (isAmmDrawdownPause(market as PerpMarketAccount)) {
return true;
}
}
return false;
}
export function isOperationPaused(
pausedOperations: number,
operation: PerpOperation | SpotOperation | InsuranceFundOperation
): boolean {
return (pausedOperations & operation) > 0;
}
export function isAmmDrawdownPause(market: PerpMarketAccount): boolean {
let quoteDrawdownLimitBreached: boolean;
if (
isVariant(market.contractTier, 'a') ||
isVariant(market.contractTier, 'b')
) {
quoteDrawdownLimitBreached = market.amm.netRevenueSinceLastFunding.lte(
DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT.muln(400)
);
} else {
quoteDrawdownLimitBreached = market.amm.netRevenueSinceLastFunding.lte(
DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT.muln(200)
);
}
if (quoteDrawdownLimitBreached) {
const percentDrawdown = market.amm.netRevenueSinceLastFunding
.mul(PERCENTAGE_PRECISION)
.div(BN.max(market.amm.totalFeeMinusDistributions, ONE));
let percentDrawdownLimitBreached: boolean;
if (isVariant(market.contractTier, 'a')) {
percentDrawdownLimitBreached = percentDrawdown.lte(
PERCENTAGE_PRECISION.divn(50).neg()
);
} else if (isVariant(market.contractTier, 'b')) {
percentDrawdownLimitBreached = percentDrawdown.lte(
PERCENTAGE_PRECISION.divn(33).neg()
);
} else if (isVariant(market.contractTier, 'c')) {
percentDrawdownLimitBreached = percentDrawdown.lte(
PERCENTAGE_PRECISION.divn(25).neg()
);
} else {
percentDrawdownLimitBreached = percentDrawdown.lte(
PERCENTAGE_PRECISION.divn(20).neg()
);
}
if (percentDrawdownLimitBreached) {
return true;
}
}
return false;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/margin.ts
|
import { squareRootBN } from './utils';
import {
SPOT_MARKET_WEIGHT_PRECISION,
SPOT_MARKET_IMF_PRECISION,
ZERO,
BID_ASK_SPREAD_PRECISION,
AMM_RESERVE_PRECISION,
MAX_PREDICTION_PRICE,
BASE_PRECISION,
MARGIN_PRECISION,
PRICE_PRECISION,
QUOTE_PRECISION,
} from '../constants/numericConstants';
import { BN } from '@coral-xyz/anchor';
import { OraclePriceData } from '../oracles/types';
import {
calculateMarketMarginRatio,
calculateScaledInitialAssetWeight,
DriftClient,
PerpMarketAccount,
PerpPosition,
} from '..';
import { isVariant } from '../types';
import { assert } from '../assert/assert';
export function calculateSizePremiumLiabilityWeight(
size: BN, // AMM_RESERVE_PRECISION
imfFactor: BN,
liabilityWeight: BN,
precision: BN
): BN {
if (imfFactor.eq(ZERO)) {
return liabilityWeight;
}
const sizeSqrt = squareRootBN(size.abs().mul(new BN(10)).add(new BN(1))); //1e9 -> 1e10 -> 1e5
const liabilityWeightNumerator = liabilityWeight.sub(
liabilityWeight.div(new BN(5))
);
const denom = new BN(100_000).mul(SPOT_MARKET_IMF_PRECISION).div(precision);
assert(denom.gt(ZERO));
const sizePremiumLiabilityWeight = liabilityWeightNumerator.add(
sizeSqrt // 1e5
.mul(imfFactor)
.div(denom) // 1e5
);
const maxLiabilityWeight = BN.max(
liabilityWeight,
sizePremiumLiabilityWeight
);
return maxLiabilityWeight;
}
export function calculateSizeDiscountAssetWeight(
size: BN, // AMM_RESERVE_PRECISION
imfFactor: BN,
assetWeight: BN
): BN {
if (imfFactor.eq(ZERO)) {
return assetWeight;
}
const sizeSqrt = squareRootBN(size.abs().mul(new BN(10)).add(new BN(1))); //1e9 -> 1e10 -> 1e5
const imfNumerator = SPOT_MARKET_IMF_PRECISION.add(
SPOT_MARKET_IMF_PRECISION.div(new BN(10))
);
const sizeDiscountAssetWeight = imfNumerator
.mul(SPOT_MARKET_WEIGHT_PRECISION)
.div(
SPOT_MARKET_IMF_PRECISION.add(
sizeSqrt // 1e5
.mul(imfFactor)
.div(new BN(100_000)) // 1e5
)
);
const minAssetWeight = BN.min(assetWeight, sizeDiscountAssetWeight);
return minAssetWeight;
}
export function calculateOraclePriceForPerpMargin(
perpPosition: PerpPosition,
market: PerpMarketAccount,
oraclePriceData: OraclePriceData
): BN {
const oraclePriceOffset = BN.min(
new BN(market.amm.maxSpread)
.mul(oraclePriceData.price)
.div(BID_ASK_SPREAD_PRECISION),
oraclePriceData.confidence.add(
new BN(market.amm.baseSpread)
.mul(oraclePriceData.price)
.div(BID_ASK_SPREAD_PRECISION)
)
);
let marginPrice: BN;
if (perpPosition.baseAssetAmount.gt(ZERO)) {
marginPrice = oraclePriceData.price.sub(oraclePriceOffset);
} else {
marginPrice = oraclePriceData.price.add(oraclePriceOffset);
}
return marginPrice;
}
/**
* This is _not_ the same as liability value as for prediction markets, the liability for the short in prediction market is (1 - oracle price) * base
* See {@link calculatePerpLiabilityValue} to get the liabiltiy value
* @param market
* @param perpPosition
* @param oraclePriceData
* @param includeOpenOrders
*/
export function calculateBaseAssetValueWithOracle(
market: PerpMarketAccount,
perpPosition: PerpPosition,
oraclePriceData: OraclePriceData,
includeOpenOrders = false
): BN {
let price = oraclePriceData.price;
if (isVariant(market.status, 'settlement')) {
price = market.expiryPrice;
}
const baseAssetAmount = includeOpenOrders
? calculateWorstCaseBaseAssetAmount(
perpPosition,
market,
oraclePriceData.price
)
: perpPosition.baseAssetAmount;
return baseAssetAmount.abs().mul(price).div(AMM_RESERVE_PRECISION);
}
export function calculateWorstCaseBaseAssetAmount(
perpPosition: PerpPosition,
perpMarket: PerpMarketAccount,
oraclePrice: BN
): BN {
return calculateWorstCasePerpLiabilityValue(
perpPosition,
perpMarket,
oraclePrice
).worstCaseBaseAssetAmount;
}
export function calculateWorstCasePerpLiabilityValue(
perpPosition: PerpPosition,
perpMarket: PerpMarketAccount,
oraclePrice: BN
): { worstCaseBaseAssetAmount: BN; worstCaseLiabilityValue: BN } {
const allBids = perpPosition.baseAssetAmount.add(perpPosition.openBids);
const allAsks = perpPosition.baseAssetAmount.add(perpPosition.openAsks);
const isPredictionMarket = isVariant(perpMarket.contractType, 'prediction');
const allBidsLiabilityValue = calculatePerpLiabilityValue(
allBids,
oraclePrice,
isPredictionMarket
);
const allAsksLiabilityValue = calculatePerpLiabilityValue(
allAsks,
oraclePrice,
isPredictionMarket
);
if (allAsksLiabilityValue.gte(allBidsLiabilityValue)) {
return {
worstCaseBaseAssetAmount: allAsks,
worstCaseLiabilityValue: allAsksLiabilityValue,
};
} else {
return {
worstCaseBaseAssetAmount: allBids,
worstCaseLiabilityValue: allBidsLiabilityValue,
};
}
}
export function calculatePerpLiabilityValue(
baseAssetAmount: BN,
price: BN,
isPredictionMarket: boolean
): BN {
if (isPredictionMarket) {
if (baseAssetAmount.gt(ZERO)) {
return baseAssetAmount.mul(price).div(BASE_PRECISION);
} else {
return baseAssetAmount
.abs()
.mul(MAX_PREDICTION_PRICE.sub(price))
.div(BASE_PRECISION);
}
} else {
return baseAssetAmount.abs().mul(price).div(BASE_PRECISION);
}
}
/**
* Calculates the margin required to open a trade, in quote amount. Only accounts for the trade size as a scalar value, does not account for the trade direction or current open positions and whether the trade would _actually_ be risk-increasing and use any extra collateral.
* @param targetMarketIndex
* @param baseSize
* @returns
*/
export function calculateMarginUSDCRequiredForTrade(
driftClient: DriftClient,
targetMarketIndex: number,
baseSize: BN,
userMaxMarginRatio?: number,
userHighLeverageMode?: boolean,
entryPrice?: BN
): BN {
const targetMarket = driftClient.getPerpMarketAccount(targetMarketIndex);
const price =
entryPrice ??
driftClient.getOracleDataForPerpMarket(targetMarket.marketIndex).price;
const perpLiabilityValue = calculatePerpLiabilityValue(
baseSize,
price,
isVariant(targetMarket.contractType, 'prediction')
);
const marginRequired = new BN(
calculateMarketMarginRatio(
targetMarket,
baseSize.abs(),
'Initial',
userMaxMarginRatio,
userHighLeverageMode
)
)
.mul(perpLiabilityValue)
.div(MARGIN_PRECISION);
return marginRequired;
}
/**
* Similar to calculatetMarginUSDCRequiredForTrade, but calculates how much of a given collateral is required to cover the margin requirements for a given trade. Basically does the same thing as getMarginUSDCRequiredForTrade but also accounts for asset weight of the selected collateral.
*
* Returns collateral required in the precision of the target collateral market.
*/
export function calculateCollateralDepositRequiredForTrade(
driftClient: DriftClient,
targetMarketIndex: number,
baseSize: BN,
collateralIndex: number,
userMaxMarginRatio?: number,
userHighLeverageMode?: boolean,
estEntryPrice?: BN
): BN {
const marginRequiredUsdc = calculateMarginUSDCRequiredForTrade(
driftClient,
targetMarketIndex,
baseSize,
userMaxMarginRatio,
userHighLeverageMode,
estEntryPrice
);
const collateralMarket = driftClient.getSpotMarketAccount(collateralIndex);
const collateralOracleData =
driftClient.getOracleDataForSpotMarket(collateralIndex);
const scaledAssetWeight = calculateScaledInitialAssetWeight(
collateralMarket,
collateralOracleData.price
);
// Base amount required to deposit = (marginRequiredUsdc / priceOfAsset) / assetWeight .. (E.g. $100 required / $10000 price / 0.5 weight)
const baseAmountRequired = driftClient
.convertToSpotPrecision(collateralIndex, marginRequiredUsdc)
.mul(PRICE_PRECISION) // adjust for division by oracle price
.mul(SPOT_MARKET_WEIGHT_PRECISION) // adjust for division by scaled asset weight
.div(collateralOracleData.price)
.div(scaledAssetWeight)
.div(QUOTE_PRECISION); // adjust for marginRequiredUsdc value's QUOTE_PRECISION
// TODO : Round by step size?
return baseAmountRequired;
}
export function calculateCollateralValueOfDeposit(
driftClient: DriftClient,
collateralIndex: number,
baseSize: BN
): BN {
const collateralMarket = driftClient.getSpotMarketAccount(collateralIndex);
const collateralOracleData =
driftClient.getOracleDataForSpotMarket(collateralIndex);
const scaledAssetWeight = calculateScaledInitialAssetWeight(
collateralMarket,
collateralOracleData.price
);
// CollateralBaseValue = oracle price * collateral base amount (and shift to QUOTE_PRECISION)
const collateralBaseValue = collateralOracleData.price
.mul(baseSize)
.mul(QUOTE_PRECISION)
.div(PRICE_PRECISION)
.div(new BN(10).pow(new BN(collateralMarket.decimals)));
const depositCollateralValue = collateralBaseValue
.mul(scaledAssetWeight)
.div(SPOT_MARKET_WEIGHT_PRECISION);
return depositCollateralValue;
}
export function calculateLiquidationPrice(
freeCollateral: BN,
freeCollateralDelta: BN,
oraclePrice: BN
): BN {
const liqPriceDelta = freeCollateral
.mul(QUOTE_PRECISION)
.div(freeCollateralDelta);
const liqPrice = oraclePrice.sub(liqPriceDelta);
if (liqPrice.lt(ZERO)) {
return new BN(-1);
}
return liqPrice;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/orders.ts
|
import { User } from '../user';
import {
isOneOfVariant,
isVariant,
PerpMarketAccount,
AMM,
Order,
PositionDirection,
} from '../types';
import { ZERO, TWO, ONE } from '../constants/numericConstants';
import { BN } from '@coral-xyz/anchor';
import { OraclePriceData } from '../oracles/types';
import {
getAuctionPrice,
isAuctionComplete,
isFallbackAvailableLiquiditySource,
} from './auction';
import {
calculateMaxBaseAssetAmountFillable,
calculateMaxBaseAssetAmountToTrade,
calculateUpdatedAMM,
} from './amm';
export function isOrderRiskIncreasing(user: User, order: Order): boolean {
if (isVariant(order.status, 'init')) {
return false;
}
const position =
user.getPerpPosition(order.marketIndex) ||
user.getEmptyPosition(order.marketIndex);
// if no position exists, it's risk increasing
if (position.baseAssetAmount.eq(ZERO)) {
return true;
}
// if position is long and order is long
if (position.baseAssetAmount.gt(ZERO) && isVariant(order.direction, 'long')) {
return true;
}
// if position is short and order is short
if (
position.baseAssetAmount.lt(ZERO) &&
isVariant(order.direction, 'short')
) {
return true;
}
const baseAssetAmountToFill = order.baseAssetAmount.sub(
order.baseAssetAmountFilled
);
// if order will flip position
if (baseAssetAmountToFill.gt(position.baseAssetAmount.abs().mul(TWO))) {
return true;
}
return false;
}
export function isOrderRiskIncreasingInSameDirection(
user: User,
order: Order
): boolean {
if (isVariant(order.status, 'init')) {
return false;
}
const position =
user.getPerpPosition(order.marketIndex) ||
user.getEmptyPosition(order.marketIndex);
// if no position exists, it's risk increasing
if (position.baseAssetAmount.eq(ZERO)) {
return true;
}
// if position is long and order is long
if (position.baseAssetAmount.gt(ZERO) && isVariant(order.direction, 'long')) {
return true;
}
// if position is short and order is short
if (
position.baseAssetAmount.lt(ZERO) &&
isVariant(order.direction, 'short')
) {
return true;
}
return false;
}
export function isOrderReduceOnly(user: User, order: Order): boolean {
if (isVariant(order.status, 'init')) {
return false;
}
const position =
user.getPerpPosition(order.marketIndex) ||
user.getEmptyPosition(order.marketIndex);
// if position is long and order is long
if (
position.baseAssetAmount.gte(ZERO) &&
isVariant(order.direction, 'long')
) {
return false;
}
// if position is short and order is short
if (
position.baseAssetAmount.lte(ZERO) &&
isVariant(order.direction, 'short')
) {
return false;
}
return true;
}
export function standardizeBaseAssetAmount(
baseAssetAmount: BN,
stepSize: BN
): BN {
const remainder = baseAssetAmount.mod(stepSize);
return baseAssetAmount.sub(remainder);
}
export function standardizePrice(
price: BN,
tickSize: BN,
direction: PositionDirection
): BN {
if (price.eq(ZERO)) {
console.log('price is zero');
return price;
}
const remainder = price.mod(tickSize);
if (remainder.eq(ZERO)) {
return price;
}
if (isVariant(direction, 'long')) {
return price.sub(remainder);
} else {
return price.add(tickSize).sub(remainder);
}
}
export function getLimitPrice(
order: Order,
oraclePriceData: OraclePriceData,
slot: number,
fallbackPrice?: BN
): BN | undefined {
let limitPrice;
if (hasAuctionPrice(order, slot)) {
limitPrice = getAuctionPrice(order, slot, oraclePriceData.price);
} else if (order.oraclePriceOffset !== 0) {
limitPrice = BN.max(
oraclePriceData.price.add(new BN(order.oraclePriceOffset)),
ONE
);
} else if (order.price.eq(ZERO)) {
limitPrice = fallbackPrice;
} else {
limitPrice = order.price;
}
return limitPrice;
}
export function hasLimitPrice(order: Order, slot: number): boolean {
return (
order.price.gt(ZERO) ||
order.oraclePriceOffset != 0 ||
!isAuctionComplete(order, slot)
);
}
export function hasAuctionPrice(order: Order, slot: number): boolean {
return (
!isAuctionComplete(order, slot) &&
(!order.auctionStartPrice.eq(ZERO) || !order.auctionEndPrice.eq(ZERO))
);
}
export function isFillableByVAMM(
order: Order,
market: PerpMarketAccount,
oraclePriceData: OraclePriceData,
slot: number,
ts: number,
minAuctionDuration: number
): boolean {
return (
(isFallbackAvailableLiquiditySource(order, minAuctionDuration, slot) &&
calculateBaseAssetAmountForAmmToFulfill(
order,
market,
oraclePriceData,
slot
).gte(market.amm.minOrderSize)) ||
isOrderExpired(order, ts)
);
}
export function calculateBaseAssetAmountForAmmToFulfill(
order: Order,
market: PerpMarketAccount,
oraclePriceData: OraclePriceData,
slot: number
): BN {
if (mustBeTriggered(order) && !isTriggered(order)) {
return ZERO;
}
const limitPrice = getLimitPrice(order, oraclePriceData, slot);
let baseAssetAmount;
const updatedAMM = calculateUpdatedAMM(market.amm, oraclePriceData);
if (limitPrice !== undefined) {
baseAssetAmount = calculateBaseAssetAmountToFillUpToLimitPrice(
order,
updatedAMM,
limitPrice,
oraclePriceData
);
} else {
baseAssetAmount = order.baseAssetAmount.sub(order.baseAssetAmountFilled);
}
const maxBaseAssetAmount = calculateMaxBaseAssetAmountFillable(
updatedAMM,
order.direction
);
return BN.min(maxBaseAssetAmount, baseAssetAmount);
}
export function calculateBaseAssetAmountToFillUpToLimitPrice(
order: Order,
amm: AMM,
limitPrice: BN,
oraclePriceData: OraclePriceData
): BN {
const adjustedLimitPrice = isVariant(order.direction, 'long')
? limitPrice.sub(amm.orderTickSize)
: limitPrice.add(amm.orderTickSize);
const [maxAmountToTrade, direction] = calculateMaxBaseAssetAmountToTrade(
amm,
adjustedLimitPrice,
order.direction,
oraclePriceData
);
const baseAssetAmount = standardizeBaseAssetAmount(
maxAmountToTrade,
amm.orderStepSize
);
// Check that directions are the same
const sameDirection = isSameDirection(direction, order.direction);
if (!sameDirection) {
return ZERO;
}
const baseAssetAmountUnfilled = order.baseAssetAmount.sub(
order.baseAssetAmountFilled
);
return baseAssetAmount.gt(baseAssetAmountUnfilled)
? baseAssetAmountUnfilled
: baseAssetAmount;
}
function isSameDirection(
firstDirection: PositionDirection,
secondDirection: PositionDirection
): boolean {
return (
(isVariant(firstDirection, 'long') && isVariant(secondDirection, 'long')) ||
(isVariant(firstDirection, 'short') && isVariant(secondDirection, 'short'))
);
}
export function isOrderExpired(
order: Order,
ts: number,
enforceBuffer = false,
bufferSeconds = 15
): boolean {
if (
mustBeTriggered(order) ||
!isVariant(order.status, 'open') ||
order.maxTs.eq(ZERO)
) {
return false;
}
let maxTs;
if (enforceBuffer && isLimitOrder(order)) {
maxTs = order.maxTs.addn(bufferSeconds);
} else {
maxTs = order.maxTs;
}
return new BN(ts).gt(maxTs);
}
export function isMarketOrder(order: Order): boolean {
return isOneOfVariant(order.orderType, ['market', 'triggerMarket', 'oracle']);
}
export function isLimitOrder(order: Order): boolean {
return isOneOfVariant(order.orderType, ['limit', 'triggerLimit']);
}
export function mustBeTriggered(order: Order): boolean {
return isOneOfVariant(order.orderType, ['triggerMarket', 'triggerLimit']);
}
export function isTriggered(order: Order): boolean {
return isOneOfVariant(order.triggerCondition, [
'triggeredAbove',
'triggeredBelow',
]);
}
export function isRestingLimitOrder(order: Order, slot: number): boolean {
if (!isLimitOrder(order)) {
return false;
}
return order.postOnly || isAuctionComplete(order, slot);
}
export function isTakingOrder(order: Order, slot: number): boolean {
return isMarketOrder(order) || !isRestingLimitOrder(order, slot);
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/bankruptcy.ts
|
import { ZERO, hasOpenOrders, isVariant } from '..';
import { User } from '../user';
export function isUserBankrupt(user: User): boolean {
const userAccount = user.getUserAccount();
let hasLiability = false;
for (const position of userAccount.spotPositions) {
if (position.scaledBalance.gt(ZERO)) {
if (isVariant(position.balanceType, 'deposit')) {
return false;
}
if (isVariant(position.balanceType, 'borrow')) {
hasLiability = true;
}
}
}
for (const position of userAccount.perpPositions) {
if (
!position.baseAssetAmount.eq(ZERO) ||
position.quoteAssetAmount.gt(ZERO) ||
hasOpenOrders(position) ||
position.lpShares.gt(ZERO)
) {
return false;
}
if (position.quoteAssetAmount.lt(ZERO)) {
hasLiability = true;
}
}
return hasLiability;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/conversion.ts
|
import { BN } from '../';
import { PRICE_PRECISION } from '../constants/numericConstants';
export const convertToNumber = (
bigNumber: BN,
precision: BN = PRICE_PRECISION
) => {
if (!bigNumber) return 0;
return (
bigNumber.div(precision).toNumber() +
bigNumber.mod(precision).toNumber() / precision.toNumber()
);
};
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/insurance.ts
|
import { PERCENTAGE_PRECISION, ZERO } from '../constants/numericConstants';
import { BN, SpotMarketAccount, SpotBalanceType } from '../index';
import { getTokenAmount } from '../math/spotBalance';
export function nextRevenuePoolSettleApr(
spotMarket: SpotMarketAccount,
vaultBalance: BN, // vault token amount
amount?: BN // delta token amount
): number {
const MAX_APR = new BN(10).mul(PERCENTAGE_PRECISION); // 1000% APR
// Conmputing the APR:
const revenuePoolBN = getTokenAmount(
spotMarket.revenuePool.scaledBalance,
spotMarket,
SpotBalanceType.DEPOSIT
);
const payoutRatio = 0.1;
const ratioForStakers =
spotMarket.insuranceFund.totalFactor > 0 &&
spotMarket.insuranceFund.userFactor > 0 &&
spotMarket.insuranceFund.revenueSettlePeriod.gt(ZERO)
? spotMarket.insuranceFund.userFactor /
spotMarket.insuranceFund.totalFactor
: 0;
// Settle periods from on-chain data:
const revSettlePeriod =
spotMarket.insuranceFund.revenueSettlePeriod.toNumber() * 1000;
const settlesPerYear = 31536000000 / revSettlePeriod;
const projectedAnnualRev = revenuePoolBN
.muln(settlesPerYear)
.muln(payoutRatio);
const uncappedApr = vaultBalance.add(amount).eq(ZERO)
? 0
: projectedAnnualRev.muln(1000).div(vaultBalance.add(amount)).toNumber() *
100 *
1000;
const cappedApr = Math.min(uncappedApr, MAX_APR.toNumber());
const nextApr = cappedApr * ratioForStakers;
return nextApr;
}
export function stakeAmountToShares(
amount: BN,
totalIfShares: BN,
insuranceFundVaultBalance: BN
): BN {
let nShares: BN;
if (insuranceFundVaultBalance.gt(ZERO)) {
nShares = amount.mul(totalIfShares).div(insuranceFundVaultBalance);
} else {
nShares = amount;
}
return nShares;
}
export function unstakeSharesToAmount(
nShares: BN,
totalIfShares: BN,
insuranceFundVaultBalance: BN
): BN {
let amount: BN;
if (totalIfShares.gt(ZERO)) {
amount = BN.max(
ZERO,
nShares.mul(insuranceFundVaultBalance).div(totalIfShares)
);
} else {
amount = ZERO;
}
return amount;
}
export function unstakeSharesToAmountWithOpenRequest(
nShares: BN,
withdrawRequestShares: BN,
withdrawRequestAmount: BN,
totalIfShares: BN,
insuranceFundVaultBalance: BN
): BN {
let stakedAmount: BN;
if (totalIfShares.gt(ZERO)) {
stakedAmount = BN.max(
ZERO,
nShares
.sub(withdrawRequestShares)
.mul(insuranceFundVaultBalance)
.div(totalIfShares)
);
} else {
stakedAmount = ZERO;
}
const withdrawAmount = BN.min(
withdrawRequestAmount,
withdrawRequestShares.mul(insuranceFundVaultBalance).div(totalIfShares)
);
const amount = withdrawAmount.add(stakedAmount);
return amount;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/amm.ts
|
import { BN } from '@coral-xyz/anchor';
import {
AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO,
PRICE_PRECISION,
PEG_PRECISION,
ZERO,
BID_ASK_SPREAD_PRECISION,
ONE,
AMM_TO_QUOTE_PRECISION_RATIO,
QUOTE_PRECISION,
MARGIN_PRECISION,
PRICE_DIV_PEG,
PERCENTAGE_PRECISION,
DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT,
FUNDING_RATE_BUFFER_PRECISION,
TWO,
} from '../constants/numericConstants';
import {
AMM,
PositionDirection,
SwapDirection,
PerpMarketAccount,
isVariant,
} from '../types';
import { assert } from '../assert/assert';
import { squareRootBN, sigNum, clampBN, standardizeBaseAssetAmount } from '..';
import { OraclePriceData } from '../oracles/types';
import {
calculateRepegCost,
calculateAdjustKCost,
calculateBudgetedPeg,
} from './repeg';
import { calculateLiveOracleStd, getNewOracleConfPct } from './oracles';
export function calculatePegFromTargetPrice(
targetPrice: BN,
baseAssetReserve: BN,
quoteAssetReserve: BN
): BN {
return BN.max(
targetPrice
.mul(baseAssetReserve)
.div(quoteAssetReserve)
.add(PRICE_DIV_PEG.div(new BN(2)))
.div(PRICE_DIV_PEG),
ONE
);
}
export function calculateOptimalPegAndBudget(
amm: AMM,
oraclePriceData: OraclePriceData
): [BN, BN, BN, boolean] {
const reservePriceBefore = calculatePrice(
amm.baseAssetReserve,
amm.quoteAssetReserve,
amm.pegMultiplier
);
const targetPrice = oraclePriceData.price;
const newPeg = calculatePegFromTargetPrice(
targetPrice,
amm.baseAssetReserve,
amm.quoteAssetReserve
);
const prePegCost = calculateRepegCost(amm, newPeg);
const totalFeeLB = amm.totalExchangeFee.div(new BN(2));
const budget = BN.max(ZERO, amm.totalFeeMinusDistributions.sub(totalFeeLB));
let checkLowerBound = true;
if (budget.lt(prePegCost)) {
const halfMaxPriceSpread = new BN(amm.maxSpread)
.div(new BN(2))
.mul(targetPrice)
.div(BID_ASK_SPREAD_PRECISION);
let newTargetPrice: BN;
let newOptimalPeg: BN;
let newBudget: BN;
const targetPriceGap = reservePriceBefore.sub(targetPrice);
if (targetPriceGap.abs().gt(halfMaxPriceSpread)) {
const markAdj = targetPriceGap.abs().sub(halfMaxPriceSpread);
if (targetPriceGap.lt(new BN(0))) {
newTargetPrice = reservePriceBefore.add(markAdj);
} else {
newTargetPrice = reservePriceBefore.sub(markAdj);
}
newOptimalPeg = calculatePegFromTargetPrice(
newTargetPrice,
amm.baseAssetReserve,
amm.quoteAssetReserve
);
newBudget = calculateRepegCost(amm, newOptimalPeg);
checkLowerBound = false;
return [newTargetPrice, newOptimalPeg, newBudget, false];
} else if (
amm.totalFeeMinusDistributions.lt(amm.totalExchangeFee.div(new BN(2)))
) {
checkLowerBound = false;
}
}
return [targetPrice, newPeg, budget, checkLowerBound];
}
export function calculateNewAmm(
amm: AMM,
oraclePriceData: OraclePriceData
): [BN, BN, BN, BN] {
let pKNumer = new BN(1);
let pKDenom = new BN(1);
const [targetPrice, _newPeg, budget, _checkLowerBound] =
calculateOptimalPegAndBudget(amm, oraclePriceData);
let prePegCost = calculateRepegCost(amm, _newPeg);
let newPeg = _newPeg;
if (prePegCost.gte(budget) && prePegCost.gt(ZERO)) {
[pKNumer, pKDenom] = [new BN(999), new BN(1000)];
const deficitMadeup = calculateAdjustKCost(amm, pKNumer, pKDenom);
assert(deficitMadeup.lte(new BN(0)));
prePegCost = budget.add(deficitMadeup.abs());
const newAmm = Object.assign({}, amm);
newAmm.baseAssetReserve = newAmm.baseAssetReserve.mul(pKNumer).div(pKDenom);
newAmm.sqrtK = newAmm.sqrtK.mul(pKNumer).div(pKDenom);
const invariant = newAmm.sqrtK.mul(newAmm.sqrtK);
newAmm.quoteAssetReserve = invariant.div(newAmm.baseAssetReserve);
const directionToClose = amm.baseAssetAmountWithAmm.gt(ZERO)
? PositionDirection.SHORT
: PositionDirection.LONG;
const [newQuoteAssetReserve, _newBaseAssetReserve] =
calculateAmmReservesAfterSwap(
newAmm,
'base',
amm.baseAssetAmountWithAmm.abs(),
getSwapDirection('base', directionToClose)
);
newAmm.terminalQuoteAssetReserve = newQuoteAssetReserve;
newPeg = calculateBudgetedPeg(newAmm, prePegCost, targetPrice);
prePegCost = calculateRepegCost(newAmm, newPeg);
}
return [prePegCost, pKNumer, pKDenom, newPeg];
}
export function calculateUpdatedAMM(
amm: AMM,
oraclePriceData: OraclePriceData
): AMM {
if (amm.curveUpdateIntensity == 0 || oraclePriceData === undefined) {
return amm;
}
const newAmm = Object.assign({}, amm);
const [prepegCost, pKNumer, pKDenom, newPeg] = calculateNewAmm(
amm,
oraclePriceData
);
newAmm.baseAssetReserve = newAmm.baseAssetReserve.mul(pKNumer).div(pKDenom);
newAmm.sqrtK = newAmm.sqrtK.mul(pKNumer).div(pKDenom);
const invariant = newAmm.sqrtK.mul(newAmm.sqrtK);
newAmm.quoteAssetReserve = invariant.div(newAmm.baseAssetReserve);
newAmm.pegMultiplier = newPeg;
const directionToClose = amm.baseAssetAmountWithAmm.gt(ZERO)
? PositionDirection.SHORT
: PositionDirection.LONG;
const [newQuoteAssetReserve, _newBaseAssetReserve] =
calculateAmmReservesAfterSwap(
newAmm,
'base',
amm.baseAssetAmountWithAmm.abs(),
getSwapDirection('base', directionToClose)
);
newAmm.terminalQuoteAssetReserve = newQuoteAssetReserve;
newAmm.totalFeeMinusDistributions =
newAmm.totalFeeMinusDistributions.sub(prepegCost);
newAmm.netRevenueSinceLastFunding =
newAmm.netRevenueSinceLastFunding.sub(prepegCost);
return newAmm;
}
export function calculateUpdatedAMMSpreadReserves(
amm: AMM,
direction: PositionDirection,
oraclePriceData: OraclePriceData,
isPrediction = false
): { baseAssetReserve: BN; quoteAssetReserve: BN; sqrtK: BN; newPeg: BN } {
const newAmm = calculateUpdatedAMM(amm, oraclePriceData);
const [shortReserves, longReserves] = calculateSpreadReserves(
newAmm,
oraclePriceData,
undefined,
isPrediction
);
const dirReserves = isVariant(direction, 'long')
? longReserves
: shortReserves;
const result = {
baseAssetReserve: dirReserves.baseAssetReserve,
quoteAssetReserve: dirReserves.quoteAssetReserve,
sqrtK: newAmm.sqrtK,
newPeg: newAmm.pegMultiplier,
};
return result;
}
export function calculateBidAskPrice(
amm: AMM,
oraclePriceData: OraclePriceData,
withUpdate = true,
isPrediction = false
): [BN, BN] {
let newAmm: AMM;
if (withUpdate) {
newAmm = calculateUpdatedAMM(amm, oraclePriceData);
} else {
newAmm = amm;
}
const [bidReserves, askReserves] = calculateSpreadReserves(
newAmm,
oraclePriceData,
undefined,
isPrediction
);
const askPrice = calculatePrice(
askReserves.baseAssetReserve,
askReserves.quoteAssetReserve,
newAmm.pegMultiplier
);
const bidPrice = calculatePrice(
bidReserves.baseAssetReserve,
bidReserves.quoteAssetReserve,
newAmm.pegMultiplier
);
return [bidPrice, askPrice];
}
/**
* Calculates a price given an arbitrary base and quote amount (they must have the same precision)
*
* @param baseAssetReserves
* @param quoteAssetReserves
* @param pegMultiplier
* @returns price : Precision PRICE_PRECISION
*/
export function calculatePrice(
baseAssetReserves: BN,
quoteAssetReserves: BN,
pegMultiplier: BN
): BN {
if (baseAssetReserves.abs().lte(ZERO)) {
return new BN(0);
}
return quoteAssetReserves
.mul(PRICE_PRECISION)
.mul(pegMultiplier)
.div(PEG_PRECISION)
.div(baseAssetReserves);
}
export type AssetType = 'quote' | 'base';
/**
* Calculates what the amm reserves would be after swapping a quote or base asset amount.
*
* @param amm
* @param inputAssetType
* @param swapAmount
* @param swapDirection
* @returns quoteAssetReserve and baseAssetReserve after swap. : Precision AMM_RESERVE_PRECISION
*/
export function calculateAmmReservesAfterSwap(
amm: Pick<
AMM,
'pegMultiplier' | 'quoteAssetReserve' | 'sqrtK' | 'baseAssetReserve'
>,
inputAssetType: AssetType,
swapAmount: BN,
swapDirection: SwapDirection
): [BN, BN] {
assert(swapAmount.gte(ZERO), 'swapAmount must be greater than 0');
let newQuoteAssetReserve;
let newBaseAssetReserve;
if (inputAssetType === 'quote') {
swapAmount = swapAmount
.mul(AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
.div(amm.pegMultiplier);
[newQuoteAssetReserve, newBaseAssetReserve] = calculateSwapOutput(
amm.quoteAssetReserve,
swapAmount,
swapDirection,
amm.sqrtK.mul(amm.sqrtK)
);
} else {
[newBaseAssetReserve, newQuoteAssetReserve] = calculateSwapOutput(
amm.baseAssetReserve,
swapAmount,
swapDirection,
amm.sqrtK.mul(amm.sqrtK)
);
}
return [newQuoteAssetReserve, newBaseAssetReserve];
}
export function calculateMarketOpenBidAsk(
baseAssetReserve: BN,
minBaseAssetReserve: BN,
maxBaseAssetReserve: BN,
stepSize?: BN
): [BN, BN] {
// open orders
let openAsks;
if (minBaseAssetReserve.lt(baseAssetReserve)) {
openAsks = baseAssetReserve.sub(minBaseAssetReserve).mul(new BN(-1));
if (stepSize && openAsks.abs().div(TWO).lt(stepSize)) {
openAsks = ZERO;
}
} else {
openAsks = ZERO;
}
let openBids;
if (maxBaseAssetReserve.gt(baseAssetReserve)) {
openBids = maxBaseAssetReserve.sub(baseAssetReserve);
if (stepSize && openBids.div(TWO).lt(stepSize)) {
openBids = ZERO;
}
} else {
openBids = ZERO;
}
return [openBids, openAsks];
}
export function calculateInventoryLiquidityRatio(
baseAssetAmountWithAmm: BN,
baseAssetReserve: BN,
minBaseAssetReserve: BN,
maxBaseAssetReserve: BN
): BN {
// inventory skew
const [openBids, openAsks] = calculateMarketOpenBidAsk(
baseAssetReserve,
minBaseAssetReserve,
maxBaseAssetReserve
);
const minSideLiquidity = BN.min(openBids.abs(), openAsks.abs());
const inventoryScaleBN = BN.min(
baseAssetAmountWithAmm
.mul(PERCENTAGE_PRECISION)
.div(BN.max(minSideLiquidity, ONE))
.abs(),
PERCENTAGE_PRECISION
);
return inventoryScaleBN;
}
export function calculateInventoryScale(
baseAssetAmountWithAmm: BN,
baseAssetReserve: BN,
minBaseAssetReserve: BN,
maxBaseAssetReserve: BN,
directionalSpread: number,
maxSpread: number
): number {
if (baseAssetAmountWithAmm.eq(ZERO)) {
return 1;
}
const MAX_BID_ASK_INVENTORY_SKEW_FACTOR = BID_ASK_SPREAD_PRECISION.mul(
new BN(10)
);
const inventoryScaleBN = calculateInventoryLiquidityRatio(
baseAssetAmountWithAmm,
baseAssetReserve,
minBaseAssetReserve,
maxBaseAssetReserve
);
const inventoryScaleMaxBN = BN.max(
MAX_BID_ASK_INVENTORY_SKEW_FACTOR,
new BN(maxSpread)
.mul(BID_ASK_SPREAD_PRECISION)
.div(new BN(Math.max(directionalSpread, 1)))
);
const inventoryScaleCapped =
BN.min(
inventoryScaleMaxBN,
BID_ASK_SPREAD_PRECISION.add(
inventoryScaleMaxBN.mul(inventoryScaleBN).div(PERCENTAGE_PRECISION)
)
).toNumber() / BID_ASK_SPREAD_PRECISION.toNumber();
return inventoryScaleCapped;
}
export function calculateReferencePriceOffset(
reservePrice: BN,
last24hAvgFundingRate: BN,
liquidityFraction: BN,
oracleTwapFast: BN,
markTwapFast: BN,
oracleTwapSlow: BN,
markTwapSlow: BN,
maxOffsetPct: number
): BN {
if (last24hAvgFundingRate.eq(ZERO)) {
return ZERO;
}
const maxOffsetInPrice = new BN(maxOffsetPct)
.mul(reservePrice)
.div(PERCENTAGE_PRECISION);
// Calculate quote denominated market premium
const markPremiumMinute = clampBN(
markTwapFast.sub(oracleTwapFast),
maxOffsetInPrice.mul(new BN(-1)),
maxOffsetInPrice
);
const markPremiumHour = clampBN(
markTwapSlow.sub(oracleTwapSlow),
maxOffsetInPrice.mul(new BN(-1)),
maxOffsetInPrice
);
// Convert last24hAvgFundingRate to quote denominated premium
const markPremiumDay = clampBN(
last24hAvgFundingRate.div(FUNDING_RATE_BUFFER_PRECISION).mul(new BN(24)),
maxOffsetInPrice.mul(new BN(-1)),
maxOffsetInPrice
);
// Take average clamped premium as the price-based offset
const markPremiumAvg = markPremiumMinute
.add(markPremiumHour)
.add(markPremiumDay)
.div(new BN(3));
const markPremiumAvgPct = markPremiumAvg
.mul(PRICE_PRECISION)
.div(reservePrice);
const inventoryPct = clampBN(
liquidityFraction.mul(new BN(maxOffsetPct)).div(PERCENTAGE_PRECISION),
maxOffsetInPrice.mul(new BN(-1)),
maxOffsetInPrice
);
// Only apply when inventory is consistent with recent and 24h market premium
let offsetPct = markPremiumAvgPct.add(inventoryPct);
if (!sigNum(inventoryPct).eq(sigNum(markPremiumAvgPct))) {
offsetPct = ZERO;
}
const clampedOffsetPct = clampBN(
offsetPct,
new BN(-maxOffsetPct),
new BN(maxOffsetPct)
);
return clampedOffsetPct;
}
export function calculateEffectiveLeverage(
baseSpread: number,
quoteAssetReserve: BN,
terminalQuoteAssetReserve: BN,
pegMultiplier: BN,
netBaseAssetAmount: BN,
reservePrice: BN,
totalFeeMinusDistributions: BN
): number {
// vAMM skew
const netBaseAssetValue = quoteAssetReserve
.sub(terminalQuoteAssetReserve)
.mul(pegMultiplier)
.div(AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
const localBaseAssetValue = netBaseAssetAmount
.mul(reservePrice)
.div(AMM_TO_QUOTE_PRECISION_RATIO.mul(PRICE_PRECISION));
const effectiveGap = Math.max(
0,
localBaseAssetValue.sub(netBaseAssetValue).toNumber()
);
const effectiveLeverage =
effectiveGap / (Math.max(0, totalFeeMinusDistributions.toNumber()) + 1) +
1 / QUOTE_PRECISION.toNumber();
return effectiveLeverage;
}
export function calculateMaxSpread(marginRatioInitial: number): number {
const maxTargetSpread: number = new BN(marginRatioInitial)
.mul(BID_ASK_SPREAD_PRECISION.div(MARGIN_PRECISION))
.toNumber();
return maxTargetSpread;
}
export function calculateVolSpreadBN(
lastOracleConfPct: BN,
reservePrice: BN,
markStd: BN,
oracleStd: BN,
longIntensity: BN,
shortIntensity: BN,
volume24H: BN
): [BN, BN] {
const marketAvgStdPct = markStd
.add(oracleStd)
.mul(PERCENTAGE_PRECISION)
.div(reservePrice)
.div(new BN(2));
const volSpread = BN.max(lastOracleConfPct, marketAvgStdPct.div(new BN(2)));
const clampMin = PERCENTAGE_PRECISION.div(new BN(100));
const clampMax = PERCENTAGE_PRECISION.mul(new BN(16)).div(new BN(10));
const longVolSpreadFactor = clampBN(
longIntensity.mul(PERCENTAGE_PRECISION).div(BN.max(ONE, volume24H)),
clampMin,
clampMax
);
const shortVolSpreadFactor = clampBN(
shortIntensity.mul(PERCENTAGE_PRECISION).div(BN.max(ONE, volume24H)),
clampMin,
clampMax
);
// only consider confidence interval at full value when above 25 bps
let confComponent = lastOracleConfPct;
if (lastOracleConfPct.lte(PRICE_PRECISION.div(new BN(400)))) {
confComponent = lastOracleConfPct.div(new BN(10));
}
const longVolSpread = BN.max(
confComponent,
volSpread.mul(longVolSpreadFactor).div(PERCENTAGE_PRECISION)
);
const shortVolSpread = BN.max(
confComponent,
volSpread.mul(shortVolSpreadFactor).div(PERCENTAGE_PRECISION)
);
return [longVolSpread, shortVolSpread];
}
export function calculateSpreadBN(
baseSpread: number,
lastOracleReservePriceSpreadPct: BN,
lastOracleConfPct: BN,
maxSpread: number,
quoteAssetReserve: BN,
terminalQuoteAssetReserve: BN,
pegMultiplier: BN,
baseAssetAmountWithAmm: BN,
reservePrice: BN,
totalFeeMinusDistributions: BN,
netRevenueSinceLastFunding: BN,
baseAssetReserve: BN,
minBaseAssetReserve: BN,
maxBaseAssetReserve: BN,
markStd: BN,
oracleStd: BN,
longIntensity: BN,
shortIntensity: BN,
volume24H: BN,
returnTerms = false
) {
assert(Number.isInteger(baseSpread));
assert(Number.isInteger(maxSpread));
const spreadTerms = {
longVolSpread: 0,
shortVolSpread: 0,
longSpreadwPS: 0,
shortSpreadwPS: 0,
maxTargetSpread: 0,
inventorySpreadScale: 0,
longSpreadwInvScale: 0,
shortSpreadwInvScale: 0,
effectiveLeverage: 0,
effectiveLeverageCapped: 0,
longSpreadwEL: 0,
shortSpreadwEL: 0,
revenueRetreatAmount: 0,
halfRevenueRetreatAmount: 0,
longSpreadwRevRetreat: 0,
shortSpreadwRevRetreat: 0,
longSpreadwOffsetShrink: 0,
shortSpreadwOffsetShrink: 0,
totalSpread: 0,
longSpread: 0,
shortSpread: 0,
};
const [longVolSpread, shortVolSpread] = calculateVolSpreadBN(
lastOracleConfPct,
reservePrice,
markStd,
oracleStd,
longIntensity,
shortIntensity,
volume24H
);
spreadTerms.longVolSpread = longVolSpread.toNumber();
spreadTerms.shortVolSpread = shortVolSpread.toNumber();
let longSpread = Math.max(baseSpread / 2, longVolSpread.toNumber());
let shortSpread = Math.max(baseSpread / 2, shortVolSpread.toNumber());
if (lastOracleReservePriceSpreadPct.gt(ZERO)) {
shortSpread = Math.max(
shortSpread,
lastOracleReservePriceSpreadPct.abs().toNumber() +
shortVolSpread.toNumber()
);
} else if (lastOracleReservePriceSpreadPct.lt(ZERO)) {
longSpread = Math.max(
longSpread,
lastOracleReservePriceSpreadPct.abs().toNumber() +
longVolSpread.toNumber()
);
}
spreadTerms.longSpreadwPS = longSpread;
spreadTerms.shortSpreadwPS = shortSpread;
const maxSpreadBaseline = Math.min(
Math.max(
lastOracleReservePriceSpreadPct.abs().toNumber(),
lastOracleConfPct.muln(2).toNumber(),
BN.max(markStd, oracleStd)
.mul(PERCENTAGE_PRECISION)
.div(reservePrice)
.toNumber()
),
BID_ASK_SPREAD_PRECISION.toNumber()
);
const maxTargetSpread: number = Math.floor(
Math.max(maxSpread, maxSpreadBaseline)
);
const inventorySpreadScale = calculateInventoryScale(
baseAssetAmountWithAmm,
baseAssetReserve,
minBaseAssetReserve,
maxBaseAssetReserve,
baseAssetAmountWithAmm.gt(ZERO) ? longSpread : shortSpread,
maxTargetSpread
);
if (baseAssetAmountWithAmm.gt(ZERO)) {
longSpread *= inventorySpreadScale;
} else if (baseAssetAmountWithAmm.lt(ZERO)) {
shortSpread *= inventorySpreadScale;
}
spreadTerms.maxTargetSpread = maxTargetSpread;
spreadTerms.inventorySpreadScale = inventorySpreadScale;
spreadTerms.longSpreadwInvScale = longSpread;
spreadTerms.shortSpreadwInvScale = shortSpread;
const MAX_SPREAD_SCALE = 10;
if (totalFeeMinusDistributions.gt(ZERO)) {
const effectiveLeverage = calculateEffectiveLeverage(
baseSpread,
quoteAssetReserve,
terminalQuoteAssetReserve,
pegMultiplier,
baseAssetAmountWithAmm,
reservePrice,
totalFeeMinusDistributions
);
spreadTerms.effectiveLeverage = effectiveLeverage;
const spreadScale = Math.min(MAX_SPREAD_SCALE, 1 + effectiveLeverage);
spreadTerms.effectiveLeverageCapped = spreadScale;
if (baseAssetAmountWithAmm.gt(ZERO)) {
longSpread *= spreadScale;
longSpread = Math.floor(longSpread);
} else {
shortSpread *= spreadScale;
shortSpread = Math.floor(shortSpread);
}
} else {
longSpread *= MAX_SPREAD_SCALE;
shortSpread *= MAX_SPREAD_SCALE;
}
spreadTerms.longSpreadwEL = longSpread;
spreadTerms.shortSpreadwEL = shortSpread;
if (
netRevenueSinceLastFunding.lt(
DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT
)
) {
const maxRetreat = maxTargetSpread / 10;
let revenueRetreatAmount = maxRetreat;
if (
netRevenueSinceLastFunding.gte(
DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT.mul(new BN(1000))
)
) {
revenueRetreatAmount = Math.min(
maxRetreat,
Math.floor(
(baseSpread * netRevenueSinceLastFunding.abs().toNumber()) /
DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT.abs().toNumber()
)
);
}
const halfRevenueRetreatAmount = Math.floor(revenueRetreatAmount / 2);
spreadTerms.revenueRetreatAmount = revenueRetreatAmount;
spreadTerms.halfRevenueRetreatAmount = halfRevenueRetreatAmount;
if (baseAssetAmountWithAmm.gt(ZERO)) {
longSpread += revenueRetreatAmount;
shortSpread += halfRevenueRetreatAmount;
} else if (baseAssetAmountWithAmm.lt(ZERO)) {
longSpread += halfRevenueRetreatAmount;
shortSpread += revenueRetreatAmount;
} else {
longSpread += halfRevenueRetreatAmount;
shortSpread += halfRevenueRetreatAmount;
}
}
spreadTerms.longSpreadwRevRetreat = longSpread;
spreadTerms.shortSpreadwRevRetreat = shortSpread;
const totalSpread = longSpread + shortSpread;
if (totalSpread > maxTargetSpread) {
if (longSpread > shortSpread) {
longSpread = Math.ceil((longSpread * maxTargetSpread) / totalSpread);
shortSpread = Math.floor(maxTargetSpread - longSpread);
} else {
shortSpread = Math.ceil((shortSpread * maxTargetSpread) / totalSpread);
longSpread = Math.floor(maxTargetSpread - shortSpread);
}
}
spreadTerms.totalSpread = totalSpread;
spreadTerms.longSpread = longSpread;
spreadTerms.shortSpread = shortSpread;
if (returnTerms) {
return spreadTerms;
}
return [longSpread, shortSpread];
}
export function calculateSpread(
amm: AMM,
oraclePriceData: OraclePriceData,
now?: BN,
reservePrice?: BN
): [number, number] {
if (amm.baseSpread == 0 || amm.curveUpdateIntensity == 0) {
return [amm.baseSpread / 2, amm.baseSpread / 2];
}
if (!reservePrice) {
reservePrice = calculatePrice(
amm.baseAssetReserve,
amm.quoteAssetReserve,
amm.pegMultiplier
);
}
const targetPrice = oraclePriceData?.price || reservePrice;
const targetMarkSpreadPct = reservePrice
.sub(targetPrice)
.mul(BID_ASK_SPREAD_PRECISION)
.div(reservePrice);
now = now || new BN(new Date().getTime() / 1000); //todo
const liveOracleStd = calculateLiveOracleStd(amm, oraclePriceData, now);
const confIntervalPct = getNewOracleConfPct(
amm,
oraclePriceData,
reservePrice,
now
);
const spreads = calculateSpreadBN(
amm.baseSpread,
targetMarkSpreadPct,
confIntervalPct,
amm.maxSpread,
amm.quoteAssetReserve,
amm.terminalQuoteAssetReserve,
amm.pegMultiplier,
amm.baseAssetAmountWithAmm,
reservePrice,
amm.totalFeeMinusDistributions,
amm.netRevenueSinceLastFunding,
amm.baseAssetReserve,
amm.minBaseAssetReserve,
amm.maxBaseAssetReserve,
amm.markStd,
liveOracleStd,
amm.longIntensityVolume,
amm.shortIntensityVolume,
amm.volume24H
);
const longSpread = spreads[0];
const shortSpread = spreads[1];
return [longSpread, shortSpread];
}
export function getQuoteAssetReservePredictionMarketBounds(
amm: AMM,
direction: PositionDirection
): [BN, BN] {
let quoteAssetReserveLowerBound = ZERO;
const pegSqrt = squareRootBN(
amm.pegMultiplier.mul(PEG_PRECISION).addn(1)
).addn(1);
let quoteAssetReserveUpperBound = amm.sqrtK
.mul(pegSqrt)
.div(amm.pegMultiplier);
if (direction === PositionDirection.LONG) {
quoteAssetReserveLowerBound = amm.sqrtK
.muln(22361)
.mul(pegSqrt)
.divn(100000)
.div(amm.pegMultiplier);
} else {
quoteAssetReserveUpperBound = amm.sqrtK
.muln(97467)
.mul(pegSqrt)
.divn(100000)
.div(amm.pegMultiplier);
}
return [quoteAssetReserveLowerBound, quoteAssetReserveUpperBound];
}
export function calculateSpreadReserves(
amm: AMM,
oraclePriceData: OraclePriceData,
now?: BN,
isPrediction = false
) {
function calculateSpreadReserve(
spread: number,
direction: PositionDirection,
amm: AMM
): {
baseAssetReserve;
quoteAssetReserve;
} {
if (spread === 0) {
return {
baseAssetReserve: amm.baseAssetReserve,
quoteAssetReserve: amm.quoteAssetReserve,
};
}
let spreadFraction = new BN(spread / 2);
// make non-zero
if (spreadFraction.eq(ZERO)) {
spreadFraction = spread >= 0 ? new BN(1) : new BN(-1);
}
const quoteAssetReserveDelta = amm.quoteAssetReserve.div(
BID_ASK_SPREAD_PRECISION.div(spreadFraction)
);
let quoteAssetReserve;
if (quoteAssetReserveDelta.gte(ZERO)) {
quoteAssetReserve = amm.quoteAssetReserve.add(
quoteAssetReserveDelta.abs()
);
} else {
quoteAssetReserve = amm.quoteAssetReserve.sub(
quoteAssetReserveDelta.abs()
);
}
if (isPrediction) {
const [qarLower, qarUpper] = getQuoteAssetReservePredictionMarketBounds(
amm,
direction
);
quoteAssetReserve = clampBN(quoteAssetReserve, qarLower, qarUpper);
}
const baseAssetReserve = amm.sqrtK.mul(amm.sqrtK).div(quoteAssetReserve);
return {
baseAssetReserve,
quoteAssetReserve,
};
}
const reservePrice = calculatePrice(
amm.baseAssetReserve,
amm.quoteAssetReserve,
amm.pegMultiplier
);
// always allow 10 bps of price offset, up to a fifth of the market's max_spread
let maxOffset = 0;
let referencePriceOffset = ZERO;
if (amm.curveUpdateIntensity > 100) {
maxOffset = Math.max(
amm.maxSpread / 5,
(PERCENTAGE_PRECISION.toNumber() / 10000) *
(amm.curveUpdateIntensity - 100)
);
const liquidityFraction = calculateInventoryLiquidityRatio(
amm.baseAssetAmountWithAmm,
amm.baseAssetReserve,
amm.minBaseAssetReserve,
amm.maxBaseAssetReserve
);
const liquidityFractionSigned = liquidityFraction.mul(
sigNum(amm.baseAssetAmountWithAmm.add(amm.baseAssetAmountWithUnsettledLp))
);
referencePriceOffset = calculateReferencePriceOffset(
reservePrice,
amm.last24HAvgFundingRate,
liquidityFractionSigned,
amm.historicalOracleData.lastOraclePriceTwap5Min,
amm.lastMarkPriceTwap5Min,
amm.historicalOracleData.lastOraclePriceTwap,
amm.lastMarkPriceTwap,
maxOffset
);
}
const [longSpread, shortSpread] = calculateSpread(
amm,
oraclePriceData,
now,
reservePrice
);
const askReserves = calculateSpreadReserve(
longSpread + referencePriceOffset.toNumber(),
PositionDirection.LONG,
amm
);
const bidReserves = calculateSpreadReserve(
-shortSpread + referencePriceOffset.toNumber(),
PositionDirection.SHORT,
amm
);
return [bidReserves, askReserves];
}
/**
* Helper function calculating constant product curve output. Agnostic to whether input asset is quote or base
*
* @param inputAssetReserve
* @param swapAmount
* @param swapDirection
* @param invariant
* @returns newInputAssetReserve and newOutputAssetReserve after swap. : Precision AMM_RESERVE_PRECISION
*/
export function calculateSwapOutput(
inputAssetReserve: BN,
swapAmount: BN,
swapDirection: SwapDirection,
invariant: BN
): [BN, BN] {
let newInputAssetReserve;
if (swapDirection === SwapDirection.ADD) {
newInputAssetReserve = inputAssetReserve.add(swapAmount);
} else {
newInputAssetReserve = inputAssetReserve.sub(swapAmount);
}
const newOutputAssetReserve = invariant.div(newInputAssetReserve);
return [newInputAssetReserve, newOutputAssetReserve];
}
/**
* Translate long/shorting quote/base asset into amm operation
*
* @param inputAssetType
* @param positionDirection
*/
export function getSwapDirection(
inputAssetType: AssetType,
positionDirection: PositionDirection
): SwapDirection {
if (isVariant(positionDirection, 'long') && inputAssetType === 'base') {
return SwapDirection.REMOVE;
}
if (isVariant(positionDirection, 'short') && inputAssetType === 'quote') {
return SwapDirection.REMOVE;
}
return SwapDirection.ADD;
}
/**
* Helper function calculating terminal price of amm
*
* @param market
* @returns cost : Precision PRICE_PRECISION
*/
export function calculateTerminalPrice(market: PerpMarketAccount) {
const directionToClose = market.amm.baseAssetAmountWithAmm.gt(ZERO)
? PositionDirection.SHORT
: PositionDirection.LONG;
const [newQuoteAssetReserve, newBaseAssetReserve] =
calculateAmmReservesAfterSwap(
market.amm,
'base',
market.amm.baseAssetAmountWithAmm.abs(),
getSwapDirection('base', directionToClose)
);
const terminalPrice = newQuoteAssetReserve
.mul(PRICE_PRECISION)
.mul(market.amm.pegMultiplier)
.div(PEG_PRECISION)
.div(newBaseAssetReserve);
return terminalPrice;
}
export function calculateMaxBaseAssetAmountToTrade(
amm: AMM,
limit_price: BN,
direction: PositionDirection,
oraclePriceData?: OraclePriceData,
now?: BN,
isPrediction = false
): [BN, PositionDirection] {
const invariant = amm.sqrtK.mul(amm.sqrtK);
const newBaseAssetReserveSquared = invariant
.mul(PRICE_PRECISION)
.mul(amm.pegMultiplier)
.div(limit_price)
.div(PEG_PRECISION);
const newBaseAssetReserve = squareRootBN(newBaseAssetReserveSquared);
const [shortSpreadReserves, longSpreadReserves] = calculateSpreadReserves(
amm,
oraclePriceData,
now,
isPrediction
);
const baseAssetReserveBefore: BN = isVariant(direction, 'long')
? longSpreadReserves.baseAssetReserve
: shortSpreadReserves.baseAssetReserve;
if (newBaseAssetReserve.gt(baseAssetReserveBefore)) {
return [
newBaseAssetReserve.sub(baseAssetReserveBefore),
PositionDirection.SHORT,
];
} else if (newBaseAssetReserve.lt(baseAssetReserveBefore)) {
return [
baseAssetReserveBefore.sub(newBaseAssetReserve),
PositionDirection.LONG,
];
} else {
console.log('tradeSize Too Small');
return [new BN(0), PositionDirection.LONG];
}
}
export function calculateQuoteAssetAmountSwapped(
quoteAssetReserves: BN,
pegMultiplier: BN,
swapDirection: SwapDirection
): BN {
if (isVariant(swapDirection, 'remove')) {
quoteAssetReserves = quoteAssetReserves.add(ONE);
}
let quoteAssetAmount = quoteAssetReserves
.mul(pegMultiplier)
.div(AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
if (isVariant(swapDirection, 'remove')) {
quoteAssetAmount = quoteAssetAmount.add(ONE);
}
return quoteAssetAmount;
}
export function calculateMaxBaseAssetAmountFillable(
amm: AMM,
orderDirection: PositionDirection
): BN {
const maxFillSize = amm.baseAssetReserve.div(
new BN(amm.maxFillReserveFraction)
);
let maxBaseAssetAmountOnSide: BN;
if (isVariant(orderDirection, 'long')) {
maxBaseAssetAmountOnSide = BN.max(
ZERO,
amm.baseAssetReserve.sub(amm.minBaseAssetReserve)
);
} else {
maxBaseAssetAmountOnSide = BN.max(
ZERO,
amm.maxBaseAssetReserve.sub(amm.baseAssetReserve)
);
}
return standardizeBaseAssetAmount(
BN.min(maxFillSize, maxBaseAssetAmountOnSide),
amm.orderStepSize
);
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/fuel.ts
|
import { BN } from '@coral-xyz/anchor';
import { SpotMarketAccount, PerpMarketAccount } from '..';
import {
QUOTE_PRECISION,
ZERO,
FUEL_WINDOW,
} from '../constants/numericConstants';
export function calculateInsuranceFuelBonus(
spotMarket: SpotMarketAccount,
tokenStakeAmount: BN,
fuelBonusNumerator: BN
): BN {
const result = tokenStakeAmount
.abs()
.mul(fuelBonusNumerator)
.mul(new BN(spotMarket.fuelBoostInsurance))
.div(FUEL_WINDOW)
.div(QUOTE_PRECISION.div(new BN(10)));
return result;
}
export function calculateSpotFuelBonus(
spotMarket: SpotMarketAccount,
signedTokenValue: BN,
fuelBonusNumerator: BN
): BN {
let result: BN;
if (signedTokenValue.abs().lte(QUOTE_PRECISION)) {
result = ZERO;
} else if (signedTokenValue.gt(new BN(0))) {
result = signedTokenValue
.abs()
.mul(fuelBonusNumerator)
.mul(new BN(spotMarket.fuelBoostDeposits))
.div(FUEL_WINDOW)
.div(QUOTE_PRECISION.div(new BN(10)));
} else {
result = signedTokenValue
.abs()
.mul(fuelBonusNumerator)
.mul(new BN(spotMarket.fuelBoostBorrows))
.div(FUEL_WINDOW)
.div(QUOTE_PRECISION.div(new BN(10)));
}
return result;
}
export function calculatePerpFuelBonus(
perpMarket: PerpMarketAccount,
baseAssetValue: BN,
fuelBonusNumerator: BN
): BN {
let result: BN;
if (baseAssetValue.abs().lte(QUOTE_PRECISION)) {
result = new BN(0);
} else {
result = baseAssetValue
.abs()
.mul(fuelBonusNumerator)
.mul(new BN(perpMarket.fuelBoostPosition))
.div(FUEL_WINDOW)
.div(QUOTE_PRECISION.div(new BN(10)));
}
return result;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/market.ts
|
import { BN } from '@coral-xyz/anchor';
import {
PerpMarketAccount,
PositionDirection,
MarginCategory,
SpotMarketAccount,
SpotBalanceType,
MarketType,
} from '../types';
import {
calculateAmmReservesAfterSwap,
calculatePrice,
calculateUpdatedAMMSpreadReserves,
getSwapDirection,
calculateUpdatedAMM,
calculateMarketOpenBidAsk,
} from './amm';
import {
calculateSizeDiscountAssetWeight,
calculateSizePremiumLiabilityWeight,
} from './margin';
import { OraclePriceData } from '../oracles/types';
import {
BASE_PRECISION,
MARGIN_PRECISION,
PRICE_TO_QUOTE_PRECISION,
ZERO,
QUOTE_SPOT_MARKET_INDEX,
} from '../constants/numericConstants';
import { getTokenAmount } from './spotBalance';
import { DLOB } from '../dlob/DLOB';
import { assert } from '../assert/assert';
/**
* Calculates market mark price
*
* @param market
* @return markPrice : Precision PRICE_PRECISION
*/
export function calculateReservePrice(
market: PerpMarketAccount,
oraclePriceData: OraclePriceData
): BN {
const newAmm = calculateUpdatedAMM(market.amm, oraclePriceData);
return calculatePrice(
newAmm.baseAssetReserve,
newAmm.quoteAssetReserve,
newAmm.pegMultiplier
);
}
/**
* Calculates market bid price
*
* @param market
* @return bidPrice : Precision PRICE_PRECISION
*/
export function calculateBidPrice(
market: PerpMarketAccount,
oraclePriceData: OraclePriceData
): BN {
const { baseAssetReserve, quoteAssetReserve, newPeg } =
calculateUpdatedAMMSpreadReserves(
market.amm,
PositionDirection.SHORT,
oraclePriceData
);
return calculatePrice(baseAssetReserve, quoteAssetReserve, newPeg);
}
/**
* Calculates market ask price
*
* @param market
* @return askPrice : Precision PRICE_PRECISION
*/
export function calculateAskPrice(
market: PerpMarketAccount,
oraclePriceData: OraclePriceData
): BN {
const { baseAssetReserve, quoteAssetReserve, newPeg } =
calculateUpdatedAMMSpreadReserves(
market.amm,
PositionDirection.LONG,
oraclePriceData
);
return calculatePrice(baseAssetReserve, quoteAssetReserve, newPeg);
}
export function calculateNewMarketAfterTrade(
baseAssetAmount: BN,
direction: PositionDirection,
market: PerpMarketAccount
): PerpMarketAccount {
const [newQuoteAssetReserve, newBaseAssetReserve] =
calculateAmmReservesAfterSwap(
market.amm,
'base',
baseAssetAmount.abs(),
getSwapDirection('base', direction)
);
const newAmm = Object.assign({}, market.amm);
const newMarket = Object.assign({}, market);
newMarket.amm = newAmm;
newMarket.amm.quoteAssetReserve = newQuoteAssetReserve;
newMarket.amm.baseAssetReserve = newBaseAssetReserve;
return newMarket;
}
export function calculateOracleReserveSpread(
market: PerpMarketAccount,
oraclePriceData: OraclePriceData
): BN {
const reservePrice = calculateReservePrice(market, oraclePriceData);
return calculateOracleSpread(reservePrice, oraclePriceData);
}
export function calculateOracleSpread(
price: BN,
oraclePriceData: OraclePriceData
): BN {
return price.sub(oraclePriceData.price);
}
export function calculateMarketMarginRatio(
market: PerpMarketAccount,
size: BN,
marginCategory: MarginCategory,
customMarginRatio = 0,
userHighLeverageMode = false
): number {
let marginRationInitial;
let marginRatioMaintenance;
if (
userHighLeverageMode &&
market.highLeverageMarginRatioInitial > 0 &&
market.highLeverageMarginRatioMaintenance
) {
marginRationInitial = market.highLeverageMarginRatioInitial;
marginRatioMaintenance = market.highLeverageMarginRatioMaintenance;
} else {
marginRationInitial = market.marginRatioInitial;
marginRatioMaintenance = market.marginRatioMaintenance;
}
let marginRatio;
switch (marginCategory) {
case 'Initial': {
// use lowest leverage between max allowed and optional user custom max
marginRatio = Math.max(
calculateSizePremiumLiabilityWeight(
size,
new BN(market.imfFactor),
new BN(marginRationInitial),
MARGIN_PRECISION
).toNumber(),
customMarginRatio
);
break;
}
case 'Maintenance': {
marginRatio = calculateSizePremiumLiabilityWeight(
size,
new BN(market.imfFactor),
new BN(marginRatioMaintenance),
MARGIN_PRECISION
).toNumber();
break;
}
}
return marginRatio;
}
export function calculateUnrealizedAssetWeight(
market: PerpMarketAccount,
quoteSpotMarket: SpotMarketAccount,
unrealizedPnl: BN,
marginCategory: MarginCategory,
oraclePriceData: OraclePriceData
): BN {
let assetWeight: BN;
switch (marginCategory) {
case 'Initial':
assetWeight = new BN(market.unrealizedPnlInitialAssetWeight);
if (market.unrealizedPnlMaxImbalance.gt(ZERO)) {
const netUnsettledPnl = calculateNetUserPnlImbalance(
market,
quoteSpotMarket,
oraclePriceData
);
if (netUnsettledPnl.gt(market.unrealizedPnlMaxImbalance)) {
assetWeight = assetWeight
.mul(market.unrealizedPnlMaxImbalance)
.div(netUnsettledPnl);
}
}
assetWeight = calculateSizeDiscountAssetWeight(
unrealizedPnl,
new BN(market.unrealizedPnlImfFactor),
assetWeight
);
break;
case 'Maintenance':
assetWeight = new BN(market.unrealizedPnlMaintenanceAssetWeight);
break;
}
return assetWeight;
}
export function calculateMarketAvailablePNL(
perpMarket: PerpMarketAccount,
spotMarket: SpotMarketAccount
): BN {
return getTokenAmount(
perpMarket.pnlPool.scaledBalance,
spotMarket,
SpotBalanceType.DEPOSIT
);
}
export function calculateMarketMaxAvailableInsurance(
perpMarket: PerpMarketAccount,
spotMarket: SpotMarketAccount
): BN {
assert(spotMarket.marketIndex == QUOTE_SPOT_MARKET_INDEX);
// todo: insuranceFundAllocation technically not guaranteed to be in Insurance Fund
const insuranceFundAllocation =
perpMarket.insuranceClaim.quoteMaxInsurance.sub(
perpMarket.insuranceClaim.quoteSettledInsurance
);
const ammFeePool = getTokenAmount(
perpMarket.amm.feePool.scaledBalance,
spotMarket,
SpotBalanceType.DEPOSIT
);
return insuranceFundAllocation.add(ammFeePool);
}
export function calculateNetUserPnl(
perpMarket: PerpMarketAccount,
oraclePriceData: OraclePriceData
): BN {
const netUserPositionValue = perpMarket.amm.baseAssetAmountWithAmm
.add(perpMarket.amm.baseAssetAmountWithUnsettledLp)
.mul(oraclePriceData.price)
.div(BASE_PRECISION)
.div(PRICE_TO_QUOTE_PRECISION);
const netUserCostBasis = perpMarket.amm.quoteAssetAmount
.add(perpMarket.amm.quoteAssetAmountWithUnsettledLp)
.add(perpMarket.amm.netUnsettledFundingPnl);
const netUserPnl = netUserPositionValue.add(netUserCostBasis);
return netUserPnl;
}
export function calculateNetUserPnlImbalance(
perpMarket: PerpMarketAccount,
spotMarket: SpotMarketAccount,
oraclePriceData: OraclePriceData,
applyFeePoolDiscount = true
): BN {
const netUserPnl = calculateNetUserPnl(perpMarket, oraclePriceData);
const pnlPool = getTokenAmount(
perpMarket.pnlPool.scaledBalance,
spotMarket,
SpotBalanceType.DEPOSIT
);
let feePool = getTokenAmount(
perpMarket.amm.feePool.scaledBalance,
spotMarket,
SpotBalanceType.DEPOSIT
);
if (applyFeePoolDiscount) {
feePool = feePool.div(new BN(5));
}
const imbalance = netUserPnl.sub(pnlPool.add(feePool));
return imbalance;
}
export function calculateAvailablePerpLiquidity(
market: PerpMarketAccount,
oraclePriceData: OraclePriceData,
dlob: DLOB,
slot: number
): { bids: BN; asks: BN } {
let [bids, asks] = calculateMarketOpenBidAsk(
market.amm.baseAssetReserve,
market.amm.minBaseAssetReserve,
market.amm.maxBaseAssetReserve,
market.amm.orderStepSize
);
asks = asks.abs();
for (const bid of dlob.getRestingLimitBids(
market.marketIndex,
slot,
MarketType.PERP,
oraclePriceData
)) {
bids = bids.add(
bid.order.baseAssetAmount.sub(bid.order.baseAssetAmountFilled)
);
}
for (const ask of dlob.getRestingLimitAsks(
market.marketIndex,
slot,
MarketType.PERP,
oraclePriceData
)) {
asks = asks.add(
ask.order.baseAssetAmount.sub(ask.order.baseAssetAmountFilled)
);
}
return {
bids: bids,
asks: asks,
};
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/trade.ts
|
import {
MarketType,
PerpMarketAccount,
PositionDirection,
SpotMarketAccount,
UserStatsAccount,
} from '../types';
import { BN } from '@coral-xyz/anchor';
import { assert } from '../assert/assert';
import {
PRICE_PRECISION,
PEG_PRECISION,
AMM_TO_QUOTE_PRECISION_RATIO,
ZERO,
BASE_PRECISION,
BN_MAX,
} from '../constants/numericConstants';
import {
calculateBidPrice,
calculateAskPrice,
calculateReservePrice,
} from './market';
import {
calculateAmmReservesAfterSwap,
calculatePrice,
getSwapDirection,
AssetType,
calculateUpdatedAMMSpreadReserves,
calculateQuoteAssetAmountSwapped,
calculateMarketOpenBidAsk,
} from './amm';
import { squareRootBN } from './utils';
import { isVariant } from '../types';
import { OraclePriceData } from '../oracles/types';
import { DLOB } from '../dlob/DLOB';
import { PublicKey } from '@solana/web3.js';
import { Orderbook } from '@project-serum/serum';
import { L2OrderBook } from '../dlob/orderBookLevels';
const MAXPCT = new BN(1000); //percentage units are [0,1000] => [0,1]
export type PriceImpactUnit =
| 'entryPrice'
| 'maxPrice'
| 'priceDelta'
| 'priceDeltaAsNumber'
| 'pctAvg'
| 'pctMax'
| 'quoteAssetAmount'
| 'quoteAssetAmountPeg'
| 'acquiredBaseAssetAmount'
| 'acquiredQuoteAssetAmount'
| 'all';
/**
* Calculates avg/max slippage (price impact) for candidate trade
*
* @deprecated use calculateEstimatedPerpEntryPrice instead
*
* @param direction
* @param amount
* @param market
* @param inputAssetType which asset is being traded
* @param useSpread whether to consider spread with calculating slippage
* @return [pctAvgSlippage, pctMaxSlippage, entryPrice, newPrice]
*
* 'pctAvgSlippage' => the percentage change to entryPrice (average est slippage in execution) : Precision PRICE_PRECISION
*
* 'pctMaxSlippage' => the percentage change to maxPrice (highest est slippage in execution) : Precision PRICE_PRECISION
*
* 'entryPrice' => the average price of the trade : Precision PRICE_PRECISION
*
* 'newPrice' => the price of the asset after the trade : Precision PRICE_PRECISION
*/
export function calculateTradeSlippage(
direction: PositionDirection,
amount: BN,
market: PerpMarketAccount,
inputAssetType: AssetType = 'quote',
oraclePriceData: OraclePriceData,
useSpread = true
): [BN, BN, BN, BN] {
let oldPrice: BN;
if (useSpread && market.amm.baseSpread > 0) {
if (isVariant(direction, 'long')) {
oldPrice = calculateAskPrice(market, oraclePriceData);
} else {
oldPrice = calculateBidPrice(market, oraclePriceData);
}
} else {
oldPrice = calculateReservePrice(market, oraclePriceData);
}
if (amount.eq(ZERO)) {
return [ZERO, ZERO, oldPrice, oldPrice];
}
const [acquiredBaseReserve, acquiredQuoteReserve, acquiredQuoteAssetAmount] =
calculateTradeAcquiredAmounts(
direction,
amount,
market,
inputAssetType,
oraclePriceData,
useSpread
);
const entryPrice = acquiredQuoteAssetAmount
.mul(AMM_TO_QUOTE_PRECISION_RATIO)
.mul(PRICE_PRECISION)
.div(acquiredBaseReserve.abs());
let amm: Parameters<typeof calculateAmmReservesAfterSwap>[0];
if (useSpread && market.amm.baseSpread > 0) {
const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } =
calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
amm = {
baseAssetReserve,
quoteAssetReserve,
sqrtK: sqrtK,
pegMultiplier: newPeg,
};
} else {
amm = market.amm;
}
const newPrice = calculatePrice(
amm.baseAssetReserve.sub(acquiredBaseReserve),
amm.quoteAssetReserve.sub(acquiredQuoteReserve),
amm.pegMultiplier
);
if (direction == PositionDirection.SHORT) {
assert(newPrice.lte(oldPrice));
} else {
assert(oldPrice.lte(newPrice));
}
const pctMaxSlippage = newPrice
.sub(oldPrice)
.mul(PRICE_PRECISION)
.div(oldPrice)
.abs();
const pctAvgSlippage = entryPrice
.sub(oldPrice)
.mul(PRICE_PRECISION)
.div(oldPrice)
.abs();
return [pctAvgSlippage, pctMaxSlippage, entryPrice, newPrice];
}
/**
* Calculates acquired amounts for trade executed
* @param direction
* @param amount
* @param market
* @param inputAssetType
* @param useSpread
* @return
* | 'acquiredBase' => positive/negative change in user's base : BN AMM_RESERVE_PRECISION
* | 'acquiredQuote' => positive/negative change in user's quote : BN TODO-PRECISION
*/
export function calculateTradeAcquiredAmounts(
direction: PositionDirection,
amount: BN,
market: PerpMarketAccount,
inputAssetType: AssetType = 'quote',
oraclePriceData: OraclePriceData,
useSpread = true
): [BN, BN, BN] {
if (amount.eq(ZERO)) {
return [ZERO, ZERO, ZERO];
}
const swapDirection = getSwapDirection(inputAssetType, direction);
let amm: Parameters<typeof calculateAmmReservesAfterSwap>[0];
if (useSpread && market.amm.baseSpread > 0) {
const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } =
calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
amm = {
baseAssetReserve,
quoteAssetReserve,
sqrtK: sqrtK,
pegMultiplier: newPeg,
};
} else {
amm = market.amm;
}
const [newQuoteAssetReserve, newBaseAssetReserve] =
calculateAmmReservesAfterSwap(amm, inputAssetType, amount, swapDirection);
const acquiredBase = amm.baseAssetReserve.sub(newBaseAssetReserve);
const acquiredQuote = amm.quoteAssetReserve.sub(newQuoteAssetReserve);
const acquiredQuoteAssetAmount = calculateQuoteAssetAmountSwapped(
acquiredQuote.abs(),
amm.pegMultiplier,
swapDirection
);
return [acquiredBase, acquiredQuote, acquiredQuoteAssetAmount];
}
/**
* calculateTargetPriceTrade
* simple function for finding arbitraging trades
*
* @deprecated
*
* @param market
* @param targetPrice
* @param pct optional default is 100% gap filling, can set smaller.
* @param outputAssetType which asset to trade.
* @param useSpread whether or not to consider the spread when calculating the trade size
* @returns trade direction/size in order to push price to a targetPrice,
*
* [
* direction => direction of trade required, PositionDirection
* tradeSize => size of trade required, TODO-PRECISION
* entryPrice => the entry price for the trade, PRICE_PRECISION
* targetPrice => the target price PRICE_PRECISION
* ]
*/
export function calculateTargetPriceTrade(
market: PerpMarketAccount,
targetPrice: BN,
pct: BN = MAXPCT,
outputAssetType: AssetType = 'quote',
oraclePriceData?: OraclePriceData,
useSpread = true
): [PositionDirection, BN, BN, BN] {
assert(market.amm.baseAssetReserve.gt(ZERO));
assert(targetPrice.gt(ZERO));
assert(pct.lte(MAXPCT) && pct.gt(ZERO));
const reservePriceBefore = calculateReservePrice(market, oraclePriceData);
const bidPriceBefore = calculateBidPrice(market, oraclePriceData);
const askPriceBefore = calculateAskPrice(market, oraclePriceData);
let direction;
if (targetPrice.gt(reservePriceBefore)) {
const priceGap = targetPrice.sub(reservePriceBefore);
const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
targetPrice = reservePriceBefore.add(priceGapScaled);
direction = PositionDirection.LONG;
} else {
const priceGap = reservePriceBefore.sub(targetPrice);
const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
targetPrice = reservePriceBefore.sub(priceGapScaled);
direction = PositionDirection.SHORT;
}
let tradeSize;
let baseSize;
let baseAssetReserveBefore: BN;
let quoteAssetReserveBefore: BN;
let peg = market.amm.pegMultiplier;
if (useSpread && market.amm.baseSpread > 0) {
const { baseAssetReserve, quoteAssetReserve, newPeg } =
calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
baseAssetReserveBefore = baseAssetReserve;
quoteAssetReserveBefore = quoteAssetReserve;
peg = newPeg;
} else {
baseAssetReserveBefore = market.amm.baseAssetReserve;
quoteAssetReserveBefore = market.amm.quoteAssetReserve;
}
const invariant = market.amm.sqrtK.mul(market.amm.sqrtK);
const k = invariant.mul(PRICE_PRECISION);
let baseAssetReserveAfter;
let quoteAssetReserveAfter;
const biasModifier = new BN(1);
let markPriceAfter;
if (
useSpread &&
targetPrice.lt(askPriceBefore) &&
targetPrice.gt(bidPriceBefore)
) {
// no trade, market is at target
if (reservePriceBefore.gt(targetPrice)) {
direction = PositionDirection.SHORT;
} else {
direction = PositionDirection.LONG;
}
tradeSize = ZERO;
return [direction, tradeSize, targetPrice, targetPrice];
} else if (reservePriceBefore.gt(targetPrice)) {
// overestimate y2
baseAssetReserveAfter = squareRootBN(
k.div(targetPrice).mul(peg).div(PEG_PRECISION).sub(biasModifier)
).sub(new BN(1));
quoteAssetReserveAfter = k.div(PRICE_PRECISION).div(baseAssetReserveAfter);
markPriceAfter = calculatePrice(
baseAssetReserveAfter,
quoteAssetReserveAfter,
peg
);
direction = PositionDirection.SHORT;
tradeSize = quoteAssetReserveBefore
.sub(quoteAssetReserveAfter)
.mul(peg)
.div(PEG_PRECISION)
.div(AMM_TO_QUOTE_PRECISION_RATIO);
baseSize = baseAssetReserveAfter.sub(baseAssetReserveBefore);
} else if (reservePriceBefore.lt(targetPrice)) {
// underestimate y2
baseAssetReserveAfter = squareRootBN(
k.div(targetPrice).mul(peg).div(PEG_PRECISION).add(biasModifier)
).add(new BN(1));
quoteAssetReserveAfter = k.div(PRICE_PRECISION).div(baseAssetReserveAfter);
markPriceAfter = calculatePrice(
baseAssetReserveAfter,
quoteAssetReserveAfter,
peg
);
direction = PositionDirection.LONG;
tradeSize = quoteAssetReserveAfter
.sub(quoteAssetReserveBefore)
.mul(peg)
.div(PEG_PRECISION)
.div(AMM_TO_QUOTE_PRECISION_RATIO);
baseSize = baseAssetReserveBefore.sub(baseAssetReserveAfter);
} else {
// no trade, market is at target
direction = PositionDirection.LONG;
tradeSize = ZERO;
return [direction, tradeSize, targetPrice, targetPrice];
}
let tp1 = targetPrice;
let tp2 = markPriceAfter;
let originalDiff = targetPrice.sub(reservePriceBefore);
if (direction == PositionDirection.SHORT) {
tp1 = markPriceAfter;
tp2 = targetPrice;
originalDiff = reservePriceBefore.sub(targetPrice);
}
const entryPrice = tradeSize
.mul(AMM_TO_QUOTE_PRECISION_RATIO)
.mul(PRICE_PRECISION)
.div(baseSize.abs());
assert(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
assert(
tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000,
'Target Price Calculation incorrect' +
tp2.toString() +
'>=' +
tp1.toString() +
'err: ' +
tp2.sub(tp1).abs().toString()
);
if (outputAssetType == 'quote') {
return [direction, tradeSize, entryPrice, targetPrice];
} else {
return [direction, baseSize, entryPrice, targetPrice];
}
}
/**
* Calculates the estimated entry price and price impact of order, in base or quote
* Price impact is based on the difference between the entry price and the best bid/ask price (whether it's dlob or vamm)
*
* @param assetType
* @param amount
* @param direction
* @param market
* @param oraclePriceData
* @param dlob
* @param slot
* @param usersToSkip
*/
export function calculateEstimatedPerpEntryPrice(
assetType: AssetType,
amount: BN,
direction: PositionDirection,
market: PerpMarketAccount,
oraclePriceData: OraclePriceData,
dlob: DLOB,
slot: number,
usersToSkip = new Map<PublicKey, boolean>()
): {
entryPrice: BN;
priceImpact: BN;
bestPrice: BN;
worstPrice: BN;
baseFilled: BN;
quoteFilled: BN;
} {
if (amount.eq(ZERO)) {
return {
entryPrice: ZERO,
priceImpact: ZERO,
bestPrice: ZERO,
worstPrice: ZERO,
baseFilled: ZERO,
quoteFilled: ZERO,
};
}
const takerIsLong = isVariant(direction, 'long');
const limitOrders = dlob[
takerIsLong ? 'getRestingLimitAsks' : 'getRestingLimitBids'
](market.marketIndex, slot, MarketType.PERP, oraclePriceData);
const swapDirection = getSwapDirection(assetType, direction);
const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } =
calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
const amm = {
baseAssetReserve,
quoteAssetReserve,
sqrtK: sqrtK,
pegMultiplier: newPeg,
};
const [ammBids, ammAsks] = calculateMarketOpenBidAsk(
market.amm.baseAssetReserve,
market.amm.minBaseAssetReserve,
market.amm.maxBaseAssetReserve,
market.amm.orderStepSize
);
let ammLiquidity: BN;
if (assetType === 'base') {
ammLiquidity = takerIsLong ? ammAsks.abs() : ammBids;
} else {
const [afterSwapQuoteReserves, _] = calculateAmmReservesAfterSwap(
amm,
'base',
takerIsLong ? ammAsks.abs() : ammBids,
getSwapDirection('base', direction)
);
ammLiquidity = calculateQuoteAssetAmountSwapped(
amm.quoteAssetReserve.sub(afterSwapQuoteReserves).abs(),
amm.pegMultiplier,
swapDirection
);
}
const invariant = amm.sqrtK.mul(amm.sqrtK);
let bestPrice = calculatePrice(
amm.baseAssetReserve,
amm.quoteAssetReserve,
amm.pegMultiplier
);
let cumulativeBaseFilled = ZERO;
let cumulativeQuoteFilled = ZERO;
let limitOrder = limitOrders.next().value;
if (limitOrder) {
const limitOrderPrice = limitOrder.getPrice(oraclePriceData, slot);
bestPrice = takerIsLong
? BN.min(limitOrderPrice, bestPrice)
: BN.max(limitOrderPrice, bestPrice);
}
let worstPrice = bestPrice;
if (assetType === 'base') {
while (
!cumulativeBaseFilled.eq(amount) &&
(ammLiquidity.gt(ZERO) || limitOrder)
) {
const limitOrderPrice = limitOrder?.getPrice(oraclePriceData, slot);
let maxAmmFill: BN;
if (limitOrderPrice) {
const newBaseReserves = squareRootBN(
invariant
.mul(PRICE_PRECISION)
.mul(amm.pegMultiplier)
.div(limitOrderPrice)
.div(PEG_PRECISION)
);
// will be zero if the limit order price is better than the amm price
maxAmmFill = takerIsLong
? amm.baseAssetReserve.sub(newBaseReserves)
: newBaseReserves.sub(amm.baseAssetReserve);
} else {
maxAmmFill = amount.sub(cumulativeBaseFilled);
}
maxAmmFill = BN.min(maxAmmFill, ammLiquidity);
if (maxAmmFill.gt(ZERO)) {
const baseFilled = BN.min(amount.sub(cumulativeBaseFilled), maxAmmFill);
const [afterSwapQuoteReserves, afterSwapBaseReserves] =
calculateAmmReservesAfterSwap(amm, 'base', baseFilled, swapDirection);
ammLiquidity = ammLiquidity.sub(baseFilled);
const quoteFilled = calculateQuoteAssetAmountSwapped(
amm.quoteAssetReserve.sub(afterSwapQuoteReserves).abs(),
amm.pegMultiplier,
swapDirection
);
cumulativeBaseFilled = cumulativeBaseFilled.add(baseFilled);
cumulativeQuoteFilled = cumulativeQuoteFilled.add(quoteFilled);
amm.baseAssetReserve = afterSwapBaseReserves;
amm.quoteAssetReserve = afterSwapQuoteReserves;
worstPrice = calculatePrice(
amm.baseAssetReserve,
amm.quoteAssetReserve,
amm.pegMultiplier
);
if (cumulativeBaseFilled.eq(amount)) {
break;
}
}
if (!limitOrder) {
continue;
}
if (usersToSkip.has(limitOrder.userAccount)) {
continue;
}
const baseFilled = BN.min(
limitOrder.order.baseAssetAmount.sub(
limitOrder.order.baseAssetAmountFilled
),
amount.sub(cumulativeBaseFilled)
);
const quoteFilled = baseFilled.mul(limitOrderPrice).div(BASE_PRECISION);
cumulativeBaseFilled = cumulativeBaseFilled.add(baseFilled);
cumulativeQuoteFilled = cumulativeQuoteFilled.add(quoteFilled);
worstPrice = limitOrderPrice;
if (cumulativeBaseFilled.eq(amount)) {
break;
}
limitOrder = limitOrders.next().value;
}
} else {
while (
!cumulativeQuoteFilled.eq(amount) &&
(ammLiquidity.gt(ZERO) || limitOrder)
) {
const limitOrderPrice = limitOrder?.getPrice(oraclePriceData, slot);
let maxAmmFill: BN;
if (limitOrderPrice) {
const newQuoteReserves = squareRootBN(
invariant
.mul(PEG_PRECISION)
.mul(limitOrderPrice)
.div(amm.pegMultiplier)
.div(PRICE_PRECISION)
);
// will be zero if the limit order price is better than the amm price
maxAmmFill = takerIsLong
? newQuoteReserves.sub(amm.quoteAssetReserve)
: amm.quoteAssetReserve.sub(newQuoteReserves);
} else {
maxAmmFill = amount.sub(cumulativeQuoteFilled);
}
maxAmmFill = BN.min(maxAmmFill, ammLiquidity);
if (maxAmmFill.gt(ZERO)) {
const quoteFilled = BN.min(
amount.sub(cumulativeQuoteFilled),
maxAmmFill
);
const [afterSwapQuoteReserves, afterSwapBaseReserves] =
calculateAmmReservesAfterSwap(
amm,
'quote',
quoteFilled,
swapDirection
);
ammLiquidity = ammLiquidity.sub(quoteFilled);
const baseFilled = afterSwapBaseReserves
.sub(amm.baseAssetReserve)
.abs();
cumulativeBaseFilled = cumulativeBaseFilled.add(baseFilled);
cumulativeQuoteFilled = cumulativeQuoteFilled.add(quoteFilled);
amm.baseAssetReserve = afterSwapBaseReserves;
amm.quoteAssetReserve = afterSwapQuoteReserves;
worstPrice = calculatePrice(
amm.baseAssetReserve,
amm.quoteAssetReserve,
amm.pegMultiplier
);
if (cumulativeQuoteFilled.eq(amount)) {
break;
}
}
if (!limitOrder) {
continue;
}
if (usersToSkip.has(limitOrder.userAccount)) {
continue;
}
const quoteFilled = BN.min(
limitOrder.order.baseAssetAmount
.sub(limitOrder.order.baseAssetAmountFilled)
.mul(limitOrderPrice)
.div(BASE_PRECISION),
amount.sub(cumulativeQuoteFilled)
);
const baseFilled = quoteFilled.mul(BASE_PRECISION).div(limitOrderPrice);
cumulativeBaseFilled = cumulativeBaseFilled.add(baseFilled);
cumulativeQuoteFilled = cumulativeQuoteFilled.add(quoteFilled);
worstPrice = limitOrderPrice;
if (cumulativeQuoteFilled.eq(amount)) {
break;
}
limitOrder = limitOrders.next().value;
}
}
const entryPrice =
cumulativeBaseFilled && cumulativeBaseFilled.gt(ZERO)
? cumulativeQuoteFilled.mul(BASE_PRECISION).div(cumulativeBaseFilled)
: ZERO;
const priceImpact =
bestPrice && bestPrice.gt(ZERO)
? entryPrice.sub(bestPrice).mul(PRICE_PRECISION).div(bestPrice).abs()
: ZERO;
return {
entryPrice,
priceImpact,
bestPrice,
worstPrice,
baseFilled: cumulativeBaseFilled,
quoteFilled: cumulativeQuoteFilled,
};
}
/**
* Calculates the estimated entry price and price impact of order, in base or quote
* Price impact is based on the difference between the entry price and the best bid/ask price (whether it's dlob or serum)
*
* @param assetType
* @param amount
* @param direction
* @param market
* @param oraclePriceData
* @param dlob
* @param serumBids
* @param serumAsks
* @param slot
* @param usersToSkip
*/
export function calculateEstimatedSpotEntryPrice(
assetType: AssetType,
amount: BN,
direction: PositionDirection,
market: SpotMarketAccount,
oraclePriceData: OraclePriceData,
dlob: DLOB,
serumBids: Orderbook,
serumAsks: Orderbook,
slot: number,
usersToSkip = new Map<PublicKey, boolean>()
): {
entryPrice: BN;
priceImpact: BN;
bestPrice: BN;
worstPrice: BN;
baseFilled: BN;
quoteFilled: BN;
} {
if (amount.eq(ZERO)) {
return {
entryPrice: ZERO,
priceImpact: ZERO,
bestPrice: ZERO,
worstPrice: ZERO,
baseFilled: ZERO,
quoteFilled: ZERO,
};
}
const basePrecision = new BN(Math.pow(10, market.decimals));
const takerIsLong = isVariant(direction, 'long');
const dlobLimitOrders = dlob[
takerIsLong ? 'getRestingLimitAsks' : 'getRestingLimitBids'
](market.marketIndex, slot, MarketType.SPOT, oraclePriceData);
const serumLimitOrders = takerIsLong
? serumAsks.getL2(100)
: serumBids.getL2(100);
let cumulativeBaseFilled = ZERO;
let cumulativeQuoteFilled = ZERO;
let dlobLimitOrder = dlobLimitOrders.next().value;
let serumLimitOrder = serumLimitOrders.shift();
const dlobLimitOrderPrice = dlobLimitOrder?.getPrice(oraclePriceData, slot);
const serumLimitOrderPrice = serumLimitOrder
? new BN(serumLimitOrder[0] * PRICE_PRECISION.toNumber())
: undefined;
const bestPrice = takerIsLong
? BN.min(serumLimitOrderPrice || BN_MAX, dlobLimitOrderPrice || BN_MAX)
: BN.max(serumLimitOrderPrice || ZERO, dlobLimitOrderPrice || ZERO);
let worstPrice = bestPrice;
if (assetType === 'base') {
while (
!cumulativeBaseFilled.eq(amount) &&
(dlobLimitOrder || serumLimitOrder)
) {
const dlobLimitOrderPrice = dlobLimitOrder?.getPrice(
oraclePriceData,
slot
);
const serumLimitOrderPrice = serumLimitOrder
? new BN(serumLimitOrder[0] * PRICE_PRECISION.toNumber())
: undefined;
const useSerum = takerIsLong
? (serumLimitOrderPrice || BN_MAX).lt(dlobLimitOrderPrice || BN_MAX)
: (serumLimitOrderPrice || ZERO).gt(dlobLimitOrderPrice || ZERO);
if (!useSerum) {
if (dlobLimitOrder && usersToSkip.has(dlobLimitOrder.userAccount)) {
continue;
}
const baseFilled = BN.min(
dlobLimitOrder.order.baseAssetAmount.sub(
dlobLimitOrder.order.baseAssetAmountFilled
),
amount.sub(cumulativeBaseFilled)
);
const quoteFilled = baseFilled
.mul(dlobLimitOrderPrice)
.div(basePrecision);
cumulativeBaseFilled = cumulativeBaseFilled.add(baseFilled);
cumulativeQuoteFilled = cumulativeQuoteFilled.add(quoteFilled);
worstPrice = dlobLimitOrderPrice;
dlobLimitOrder = dlobLimitOrders.next().value;
} else {
const baseFilled = BN.min(
new BN(serumLimitOrder[1] * basePrecision.toNumber()),
amount.sub(cumulativeBaseFilled)
);
const quoteFilled = baseFilled
.mul(serumLimitOrderPrice)
.div(basePrecision);
cumulativeBaseFilled = cumulativeBaseFilled.add(baseFilled);
cumulativeQuoteFilled = cumulativeQuoteFilled.add(quoteFilled);
worstPrice = serumLimitOrderPrice;
serumLimitOrder = serumLimitOrders.shift();
}
}
} else {
while (
!cumulativeQuoteFilled.eq(amount) &&
(dlobLimitOrder || serumLimitOrder)
) {
const dlobLimitOrderPrice = dlobLimitOrder?.getPrice(
oraclePriceData,
slot
);
const serumLimitOrderPrice = serumLimitOrder
? new BN(serumLimitOrder[0] * PRICE_PRECISION.toNumber())
: undefined;
const useSerum = takerIsLong
? (serumLimitOrderPrice || BN_MAX).lt(dlobLimitOrderPrice || BN_MAX)
: (serumLimitOrderPrice || ZERO).gt(dlobLimitOrderPrice || ZERO);
if (!useSerum) {
if (dlobLimitOrder && usersToSkip.has(dlobLimitOrder.userAccount)) {
continue;
}
const quoteFilled = BN.min(
dlobLimitOrder.order.baseAssetAmount
.sub(dlobLimitOrder.order.baseAssetAmountFilled)
.mul(dlobLimitOrderPrice)
.div(basePrecision),
amount.sub(cumulativeQuoteFilled)
);
const baseFilled = quoteFilled
.mul(basePrecision)
.div(dlobLimitOrderPrice);
cumulativeBaseFilled = cumulativeBaseFilled.add(baseFilled);
cumulativeQuoteFilled = cumulativeQuoteFilled.add(quoteFilled);
worstPrice = dlobLimitOrderPrice;
dlobLimitOrder = dlobLimitOrders.next().value;
} else {
const serumOrderBaseAmount = new BN(
serumLimitOrder[1] * basePrecision.toNumber()
);
const quoteFilled = BN.min(
serumOrderBaseAmount.mul(serumLimitOrderPrice).div(basePrecision),
amount.sub(cumulativeQuoteFilled)
);
const baseFilled = quoteFilled
.mul(basePrecision)
.div(serumLimitOrderPrice);
cumulativeBaseFilled = cumulativeBaseFilled.add(baseFilled);
cumulativeQuoteFilled = cumulativeQuoteFilled.add(quoteFilled);
worstPrice = serumLimitOrderPrice;
serumLimitOrder = serumLimitOrders.shift();
}
}
}
const entryPrice =
cumulativeBaseFilled && cumulativeBaseFilled.gt(ZERO)
? cumulativeQuoteFilled.mul(basePrecision).div(cumulativeBaseFilled)
: ZERO;
const priceImpact =
bestPrice && bestPrice.gt(ZERO)
? entryPrice.sub(bestPrice).mul(PRICE_PRECISION).div(bestPrice).abs()
: ZERO;
return {
entryPrice,
priceImpact,
bestPrice,
worstPrice,
baseFilled: cumulativeBaseFilled,
quoteFilled: cumulativeQuoteFilled,
};
}
export function calculateEstimatedEntryPriceWithL2(
assetType: AssetType,
amount: BN,
direction: PositionDirection,
basePrecision: BN,
l2: L2OrderBook
): {
entryPrice: BN;
priceImpact: BN;
bestPrice: BN;
worstPrice: BN;
baseFilled: BN;
quoteFilled: BN;
} {
const takerIsLong = isVariant(direction, 'long');
let cumulativeBaseFilled = ZERO;
let cumulativeQuoteFilled = ZERO;
const levels = [...(takerIsLong ? l2.asks : l2.bids)];
let nextLevel = levels.shift();
let bestPrice: BN;
let worstPrice: BN;
if (nextLevel) {
bestPrice = nextLevel.price;
worstPrice = nextLevel.price;
} else {
bestPrice = takerIsLong ? BN_MAX : ZERO;
worstPrice = bestPrice;
}
if (assetType === 'base') {
while (!cumulativeBaseFilled.eq(amount) && nextLevel) {
const price = nextLevel.price;
const size = nextLevel.size;
worstPrice = price;
const baseFilled = BN.min(size, amount.sub(cumulativeBaseFilled));
const quoteFilled = baseFilled.mul(price).div(basePrecision);
cumulativeBaseFilled = cumulativeBaseFilled.add(baseFilled);
cumulativeQuoteFilled = cumulativeQuoteFilled.add(quoteFilled);
nextLevel = levels.shift();
}
} else {
while (!cumulativeQuoteFilled.eq(amount) && nextLevel) {
const price = nextLevel.price;
const size = nextLevel.size;
worstPrice = price;
const quoteFilled = BN.min(
size.mul(price).div(basePrecision),
amount.sub(cumulativeQuoteFilled)
);
const baseFilled = quoteFilled.mul(basePrecision).div(price);
cumulativeBaseFilled = cumulativeBaseFilled.add(baseFilled);
cumulativeQuoteFilled = cumulativeQuoteFilled.add(quoteFilled);
nextLevel = levels.shift();
}
}
const entryPrice =
cumulativeBaseFilled && cumulativeBaseFilled.gt(ZERO)
? cumulativeQuoteFilled.mul(basePrecision).div(cumulativeBaseFilled)
: ZERO;
const priceImpact =
bestPrice && bestPrice.gt(ZERO)
? entryPrice.sub(bestPrice).mul(PRICE_PRECISION).div(bestPrice).abs()
: ZERO;
return {
entryPrice,
priceImpact,
bestPrice,
worstPrice,
baseFilled: cumulativeBaseFilled,
quoteFilled: cumulativeQuoteFilled,
};
}
export function getUser30dRollingVolumeEstimate(
userStatsAccount: UserStatsAccount,
now?: BN
) {
now = now || new BN(new Date().getTime() / 1000);
const sinceLastTaker = BN.max(
now.sub(userStatsAccount.lastTakerVolume30DTs),
ZERO
);
const sinceLastMaker = BN.max(
now.sub(userStatsAccount.lastMakerVolume30DTs),
ZERO
);
const thirtyDaysInSeconds = new BN(60 * 60 * 24 * 30);
const last30dVolume = userStatsAccount.takerVolume30D
.mul(BN.max(thirtyDaysInSeconds.sub(sinceLastTaker), ZERO))
.div(thirtyDaysInSeconds)
.add(
userStatsAccount.makerVolume30D
.mul(BN.max(thirtyDaysInSeconds.sub(sinceLastMaker), ZERO))
.div(thirtyDaysInSeconds)
);
return last30dVolume;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/spotMarket.ts
|
import { BN } from '@coral-xyz/anchor';
import {
isVariant,
MarginCategory,
SpotBalanceType,
SpotMarketAccount,
} from '../types';
import {
calculateAssetWeight,
calculateLiabilityWeight,
getTokenAmount,
} from './spotBalance';
import { MARGIN_PRECISION, ZERO } from '../constants/numericConstants';
import { numberToSafeBN } from './utils';
export function castNumberToSpotPrecision(
value: number | BN,
spotMarket: SpotMarketAccount
): BN {
if (typeof value === 'number') {
return numberToSafeBN(value, new BN(Math.pow(10, spotMarket.decimals)));
} else {
return value.mul(new BN(Math.pow(10, spotMarket.decimals)));
}
}
export function calculateSpotMarketMarginRatio(
market: SpotMarketAccount,
oraclePrice: BN,
marginCategory: MarginCategory,
size: BN,
balanceType: SpotBalanceType,
customMarginRatio = 0
): number {
let marginRatio;
if (isVariant(balanceType, 'deposit')) {
const assetWeight = calculateAssetWeight(
size,
oraclePrice,
market,
marginCategory
);
marginRatio = MARGIN_PRECISION.sub(assetWeight).toNumber();
} else {
const liabilityWeight = calculateLiabilityWeight(
size,
market,
marginCategory
);
marginRatio = liabilityWeight.sub(MARGIN_PRECISION).toNumber();
}
if (marginCategory === 'Initial') {
// use lowest leverage between max allowed and optional user custom max
return Math.max(marginRatio, customMarginRatio);
}
return marginRatio;
}
/**
* Returns the maximum remaining deposit that can be made to the spot market. If the maxTokenDeposits on the market is zero then there is no limit and this function will also return zero. (so that needs to be checked)
* @param market
* @returns
*/
export function calculateMaxRemainingDeposit(market: SpotMarketAccount) {
const marketMaxTokenDeposits = market.maxTokenDeposits;
if (marketMaxTokenDeposits.eq(ZERO)) {
// If the maxTokenDeposits is set to zero then that means there is no limit. Return the largest number we can to represent infinite available deposit.
return ZERO;
}
const totalDepositsTokenAmount = getTokenAmount(
market.depositBalance,
market,
SpotBalanceType.DEPOSIT
);
return marketMaxTokenDeposits.sub(totalDepositsTokenAmount);
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/userStatus.ts
|
import { UserAccount, UserStatus } from '..';
export function isUserProtectedMaker(userAccount: UserAccount): boolean {
return (userAccount.status & UserStatus.PROTECTED_MAKER) > 0;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/funding.ts
|
import { BN } from '@coral-xyz/anchor';
import {
AMM_RESERVE_PRECISION,
PRICE_PRECISION,
QUOTE_PRECISION,
ZERO,
ONE,
FUNDING_RATE_OFFSET_DENOMINATOR,
} from '../constants/numericConstants';
import { PerpMarketAccount, isVariant } from '../types';
import { OraclePriceData } from '../oracles/types';
import { calculateBidAskPrice } from './amm';
import { calculateLiveOracleTwap } from './oracles';
import { clampBN } from './utils';
function calculateLiveMarkTwap(
market: PerpMarketAccount,
oraclePriceData?: OraclePriceData,
markPrice?: BN,
now?: BN,
period = new BN(3600)
): BN {
now = now || new BN((Date.now() / 1000).toFixed(0));
const lastMarkTwapWithMantissa = market.amm.lastMarkPriceTwap;
const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
const markTwapTimeSinceLastUpdate = BN.max(
period,
BN.max(ZERO, period.sub(timeSinceLastMarkChange))
);
if (!markPrice) {
const [bid, ask] = calculateBidAskPrice(market.amm, oraclePriceData);
markPrice = bid.add(ask).div(new BN(2));
}
const markTwapWithMantissa = markTwapTimeSinceLastUpdate
.mul(lastMarkTwapWithMantissa)
.add(timeSinceLastMarkChange.mul(markPrice))
.div(timeSinceLastMarkChange.add(markTwapTimeSinceLastUpdate));
return markTwapWithMantissa;
}
function shrinkStaleTwaps(
market: PerpMarketAccount,
markTwapWithMantissa: BN,
oracleTwapWithMantissa: BN,
now?: BN
) {
now = now || new BN((Date.now() / 1000).toFixed(0));
let newMarkTwap = markTwapWithMantissa;
let newOracleTwap = oracleTwapWithMantissa;
if (
market.amm.lastMarkPriceTwapTs.gt(
market.amm.historicalOracleData.lastOraclePriceTwapTs
)
) {
// shrink oracle based on invalid intervals
const oracleInvalidDuration = BN.max(
ZERO,
market.amm.lastMarkPriceTwapTs.sub(
market.amm.historicalOracleData.lastOraclePriceTwapTs
)
);
const timeSinceLastOracleTwapUpdate = now.sub(
market.amm.historicalOracleData.lastOraclePriceTwapTs
);
const oracleTwapTimeSinceLastUpdate = BN.max(
ONE,
BN.min(
market.amm.fundingPeriod,
BN.max(ONE, market.amm.fundingPeriod.sub(timeSinceLastOracleTwapUpdate))
)
);
newOracleTwap = oracleTwapTimeSinceLastUpdate
.mul(oracleTwapWithMantissa)
.add(oracleInvalidDuration.mul(markTwapWithMantissa))
.div(oracleTwapTimeSinceLastUpdate.add(oracleInvalidDuration));
} else if (
market.amm.lastMarkPriceTwapTs.lt(
market.amm.historicalOracleData.lastOraclePriceTwapTs
)
) {
// shrink mark to oracle twap over tradless intervals
const tradelessDuration = BN.max(
ZERO,
market.amm.historicalOracleData.lastOraclePriceTwapTs.sub(
market.amm.lastMarkPriceTwapTs
)
);
const timeSinceLastMarkTwapUpdate = now.sub(market.amm.lastMarkPriceTwapTs);
const markTwapTimeSinceLastUpdate = BN.max(
ONE,
BN.min(
market.amm.fundingPeriod,
BN.max(ONE, market.amm.fundingPeriod.sub(timeSinceLastMarkTwapUpdate))
)
);
newMarkTwap = markTwapTimeSinceLastUpdate
.mul(markTwapWithMantissa)
.add(tradelessDuration.mul(oracleTwapWithMantissa))
.div(markTwapTimeSinceLastUpdate.add(tradelessDuration));
}
return [newMarkTwap, newOracleTwap];
}
/**
*
* @param market
* @param oraclePriceData
* @param periodAdjustment
* @returns Estimated funding rate. : Precision //TODO-PRECISION
*/
export async function calculateAllEstimatedFundingRate(
market: PerpMarketAccount,
oraclePriceData?: OraclePriceData,
markPrice?: BN,
now?: BN
): Promise<[BN, BN, BN, BN, BN]> {
if (isVariant(market.status, 'uninitialized')) {
return [ZERO, ZERO, ZERO, ZERO, ZERO];
}
// todo: sufficiently differs from blockchain timestamp?
now = now || new BN((Date.now() / 1000).toFixed(0));
// calculate real-time mark and oracle twap
const liveMarkTwap = calculateLiveMarkTwap(
market,
oraclePriceData,
markPrice,
now,
market.amm.fundingPeriod
);
const liveOracleTwap = calculateLiveOracleTwap(
market.amm.historicalOracleData,
oraclePriceData,
now,
market.amm.fundingPeriod
);
const [markTwap, oracleTwap] = shrinkStaleTwaps(
market,
liveMarkTwap,
liveOracleTwap,
now
);
// if(!markTwap.eq(liveMarkTwap)){
// console.log('shrink mark:', liveMarkTwap.toString(), '->', markTwap.toString());
// }
// if(!oracleTwap.eq(liveOracleTwap)){
// console.log('shrink orac:', liveOracleTwap.toString(), '->', oracleTwap.toString());
// }
const twapSpread = markTwap.sub(oracleTwap);
const twapSpreadWithOffset = twapSpread.add(
oracleTwap.abs().div(FUNDING_RATE_OFFSET_DENOMINATOR)
);
const maxSpread = getMaxPriceDivergenceForFundingRate(market, oracleTwap);
const clampedSpreadWithOffset = clampBN(
twapSpreadWithOffset,
maxSpread.mul(new BN(-1)),
maxSpread
);
const twapSpreadPct = clampedSpreadWithOffset
.mul(PRICE_PRECISION)
.mul(new BN(100))
.div(oracleTwap);
const secondsInHour = new BN(3600);
const hoursInDay = new BN(24);
const timeSinceLastUpdate = now.sub(market.amm.lastFundingRateTs);
const lowerboundEst = twapSpreadPct
.mul(market.amm.fundingPeriod)
.mul(BN.min(secondsInHour, timeSinceLastUpdate))
.div(secondsInHour)
.div(secondsInHour)
.div(hoursInDay);
const interpEst = twapSpreadPct.div(hoursInDay);
const interpRateQuote = twapSpreadPct
.div(hoursInDay)
.div(PRICE_PRECISION.div(QUOTE_PRECISION));
let feePoolSize = calculateFundingPool(market);
if (interpRateQuote.lt(new BN(0))) {
feePoolSize = feePoolSize.mul(new BN(-1));
}
let cappedAltEst: BN;
let largerSide: BN;
let smallerSide: BN;
if (
market.amm.baseAssetAmountLong.gt(market.amm.baseAssetAmountShort.abs())
) {
largerSide = market.amm.baseAssetAmountLong.abs();
smallerSide = market.amm.baseAssetAmountShort.abs();
if (twapSpread.gt(new BN(0))) {
return [markTwap, oracleTwap, lowerboundEst, interpEst, interpEst];
}
} else if (
market.amm.baseAssetAmountLong.lt(market.amm.baseAssetAmountShort.abs())
) {
largerSide = market.amm.baseAssetAmountShort.abs();
smallerSide = market.amm.baseAssetAmountLong.abs();
if (twapSpread.lt(new BN(0))) {
return [markTwap, oracleTwap, lowerboundEst, interpEst, interpEst];
}
} else {
return [markTwap, oracleTwap, lowerboundEst, interpEst, interpEst];
}
if (largerSide.gt(ZERO)) {
// funding smaller flow
cappedAltEst = smallerSide.mul(twapSpread).div(hoursInDay);
const feePoolTopOff = feePoolSize
.mul(PRICE_PRECISION.div(QUOTE_PRECISION))
.mul(AMM_RESERVE_PRECISION);
cappedAltEst = cappedAltEst.add(feePoolTopOff).div(largerSide);
cappedAltEst = cappedAltEst
.mul(PRICE_PRECISION)
.mul(new BN(100))
.div(oracleTwap);
if (cappedAltEst.abs().gte(interpEst.abs())) {
cappedAltEst = interpEst;
}
} else {
cappedAltEst = interpEst;
}
return [markTwap, oracleTwap, lowerboundEst, cappedAltEst, interpEst];
}
function getMaxPriceDivergenceForFundingRate(
market: PerpMarketAccount,
oracleTwap: BN
) {
if (isVariant(market.contractTier, 'a')) {
return oracleTwap.divn(33);
} else if (isVariant(market.contractTier, 'b')) {
return oracleTwap.divn(33);
} else if (isVariant(market.contractTier, 'c')) {
return oracleTwap.divn(20);
} else {
return oracleTwap.divn(10);
}
}
/**
*
* @param market
* @param oraclePriceData
* @param periodAdjustment
* @returns Estimated funding rate. : Precision //TODO-PRECISION
*/
export async function calculateLongShortFundingRate(
market: PerpMarketAccount,
oraclePriceData?: OraclePriceData,
markPrice?: BN,
now?: BN
): Promise<[BN, BN]> {
const [_1, _2, _, cappedAltEst, interpEst] =
await calculateAllEstimatedFundingRate(
market,
oraclePriceData,
markPrice,
now
);
if (market.amm.baseAssetAmountLong.gt(market.amm.baseAssetAmountShort)) {
return [cappedAltEst, interpEst];
} else if (
market.amm.baseAssetAmountLong.lt(market.amm.baseAssetAmountShort)
) {
return [interpEst, cappedAltEst];
} else {
return [interpEst, interpEst];
}
}
/**
*
* @param market
* @param oraclePriceData
* @param periodAdjustment
* @returns Estimated funding rate. : Precision //TODO-PRECISION
*/
export async function calculateLongShortFundingRateAndLiveTwaps(
market: PerpMarketAccount,
oraclePriceData?: OraclePriceData,
markPrice?: BN,
now?: BN
): Promise<[BN, BN, BN, BN]> {
const [markTwapLive, oracleTwapLive, _2, cappedAltEst, interpEst] =
await calculateAllEstimatedFundingRate(
market,
oraclePriceData,
markPrice,
now
);
if (
market.amm.baseAssetAmountLong.gt(market.amm.baseAssetAmountShort.abs())
) {
return [markTwapLive, oracleTwapLive, cappedAltEst, interpEst];
} else if (
market.amm.baseAssetAmountLong.lt(market.amm.baseAssetAmountShort.abs())
) {
return [markTwapLive, oracleTwapLive, interpEst, cappedAltEst];
} else {
return [markTwapLive, oracleTwapLive, interpEst, interpEst];
}
}
/**
*
* @param market
* @returns Estimated fee pool size
*/
export function calculateFundingPool(market: PerpMarketAccount): BN {
// todo
const totalFeeLB = market.amm.totalExchangeFee.div(new BN(2));
const feePool = BN.max(
ZERO,
market.amm.totalFeeMinusDistributions
.sub(totalFeeLB)
.mul(new BN(1))
.div(new BN(3))
);
return feePool;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/math/oracles.ts
|
import { AMM, OracleGuardRails, isVariant } from '../types';
import { OraclePriceData } from '../oracles/types';
import {
BID_ASK_SPREAD_PRECISION,
MARGIN_PRECISION,
PRICE_PRECISION,
ONE,
ZERO,
FIVE_MINUTE,
PERCENTAGE_PRECISION,
} from '../constants/numericConstants';
import { BN, HistoricalOracleData, PerpMarketAccount } from '../index';
import { assert } from '../assert/assert';
export function oraclePriceBands(
market: PerpMarketAccount,
oraclePriceData: OraclePriceData
): [BN, BN] {
const maxPercentDiff =
market.marginRatioInitial - market.marginRatioMaintenance;
const offset = oraclePriceData.price
.mul(new BN(maxPercentDiff))
.div(MARGIN_PRECISION);
assert(offset.gte(ZERO));
return [oraclePriceData.price.sub(offset), oraclePriceData.price.add(offset)];
}
export function getMaxConfidenceIntervalMultiplier(
market: PerpMarketAccount
): BN {
let maxConfidenceIntervalMultiplier;
if (isVariant(market.contractTier, 'a')) {
maxConfidenceIntervalMultiplier = new BN(1);
} else if (isVariant(market.contractTier, 'b')) {
maxConfidenceIntervalMultiplier = new BN(1);
} else if (isVariant(market.contractTier, 'c')) {
maxConfidenceIntervalMultiplier = new BN(2);
} else if (isVariant(market.contractTier, 'speculative')) {
maxConfidenceIntervalMultiplier = new BN(10);
} else {
maxConfidenceIntervalMultiplier = new BN(50);
}
return maxConfidenceIntervalMultiplier;
}
export function isOracleValid(
market: PerpMarketAccount,
oraclePriceData: OraclePriceData,
oracleGuardRails: OracleGuardRails,
slot: number
): boolean {
// checks if oracle is valid for an AMM only fill
const amm = market.amm;
const isOraclePriceNonPositive = oraclePriceData.price.lte(ZERO);
const isOraclePriceTooVolatile =
oraclePriceData.price
.div(BN.max(ONE, amm.historicalOracleData.lastOraclePriceTwap))
.gt(oracleGuardRails.validity.tooVolatileRatio) ||
amm.historicalOracleData.lastOraclePriceTwap
.div(BN.max(ONE, oraclePriceData.price))
.gt(oracleGuardRails.validity.tooVolatileRatio);
const maxConfidenceIntervalMultiplier =
getMaxConfidenceIntervalMultiplier(market);
const isConfidenceTooLarge = BN.max(ONE, oraclePriceData.confidence)
.mul(BID_ASK_SPREAD_PRECISION)
.div(oraclePriceData.price)
.gt(
oracleGuardRails.validity.confidenceIntervalMaxSize.mul(
maxConfidenceIntervalMultiplier
)
);
const oracleIsStale = new BN(slot)
.sub(oraclePriceData.slot)
.gt(oracleGuardRails.validity.slotsBeforeStaleForAmm);
return !(
!oraclePriceData.hasSufficientNumberOfDataPoints ||
oracleIsStale ||
isOraclePriceNonPositive ||
isOraclePriceTooVolatile ||
isConfidenceTooLarge
);
}
export function isOracleTooDivergent(
amm: AMM,
oraclePriceData: OraclePriceData,
oracleGuardRails: OracleGuardRails,
now: BN
): boolean {
const sinceLastUpdate = now.sub(
amm.historicalOracleData.lastOraclePriceTwapTs
);
const sinceStart = BN.max(ZERO, FIVE_MINUTE.sub(sinceLastUpdate));
const oracleTwap5min = amm.historicalOracleData.lastOraclePriceTwap5Min
.mul(sinceStart)
.add(oraclePriceData.price)
.mul(sinceLastUpdate)
.div(sinceStart.add(sinceLastUpdate));
const oracleSpread = oracleTwap5min.sub(oraclePriceData.price);
const oracleSpreadPct = oracleSpread.mul(PRICE_PRECISION).div(oracleTwap5min);
const maxDivergence = BN.max(
oracleGuardRails.priceDivergence.markOraclePercentDivergence,
PERCENTAGE_PRECISION.div(new BN(10))
);
const tooDivergent = oracleSpreadPct.abs().gte(maxDivergence);
return tooDivergent;
}
export function calculateLiveOracleTwap(
histOracleData: HistoricalOracleData,
oraclePriceData: OraclePriceData,
now: BN,
period: BN
): BN {
let oracleTwap = undefined;
if (period.eq(FIVE_MINUTE)) {
oracleTwap = histOracleData.lastOraclePriceTwap5Min;
} else {
//todo: assumes its fundingPeriod (1hr)
// period = amm.fundingPeriod;
oracleTwap = histOracleData.lastOraclePriceTwap;
}
const sinceLastUpdate = BN.max(
ONE,
now.sub(histOracleData.lastOraclePriceTwapTs)
);
const sinceStart = BN.max(ZERO, period.sub(sinceLastUpdate));
const clampRange = oracleTwap.div(new BN(3));
const clampedOraclePrice = BN.min(
oracleTwap.add(clampRange),
BN.max(oraclePriceData.price, oracleTwap.sub(clampRange))
);
const newOracleTwap = oracleTwap
.mul(sinceStart)
.add(clampedOraclePrice.mul(sinceLastUpdate))
.div(sinceStart.add(sinceLastUpdate));
return newOracleTwap;
}
export function calculateLiveOracleStd(
amm: AMM,
oraclePriceData: OraclePriceData,
now: BN
): BN {
const sinceLastUpdate = BN.max(
ONE,
now.sub(amm.historicalOracleData.lastOraclePriceTwapTs)
);
const sinceStart = BN.max(ZERO, amm.fundingPeriod.sub(sinceLastUpdate));
const liveOracleTwap = calculateLiveOracleTwap(
amm.historicalOracleData,
oraclePriceData,
now,
amm.fundingPeriod
);
const priceDeltaVsTwap = oraclePriceData.price.sub(liveOracleTwap).abs();
const oracleStd = priceDeltaVsTwap.add(
amm.oracleStd.mul(sinceStart).div(sinceStart.add(sinceLastUpdate))
);
return oracleStd;
}
export function getNewOracleConfPct(
amm: AMM,
oraclePriceData: OraclePriceData,
reservePrice: BN,
now: BN
): BN {
const confInterval = oraclePriceData.confidence || ZERO;
const sinceLastUpdate = BN.max(
ZERO,
now.sub(amm.historicalOracleData.lastOraclePriceTwapTs)
);
let lowerBoundConfPct = amm.lastOracleConfPct;
if (sinceLastUpdate.gt(ZERO)) {
const lowerBoundConfDivisor = BN.max(
new BN(21).sub(sinceLastUpdate),
new BN(5)
);
lowerBoundConfPct = amm.lastOracleConfPct.sub(
amm.lastOracleConfPct.div(lowerBoundConfDivisor)
);
}
const confIntervalPct = confInterval
.mul(BID_ASK_SPREAD_PRECISION)
.div(reservePrice);
const confIntervalPctResult = BN.max(confIntervalPct, lowerBoundConfPct);
return confIntervalPctResult;
}
export function trimVaaSignatures(vaa: Buffer, n = 3): Buffer {
const currentNumSignatures = vaa[5];
if (n > currentNumSignatures) {
throw new Error(
"Resulting VAA can't have more signatures than the original VAA"
);
}
const trimmedVaa = Buffer.concat([
vaa.subarray(0, 6 + n * 66),
vaa.subarray(6 + currentNumSignatures * 66),
]);
trimmedVaa[5] = n;
return trimmedVaa;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/sdk/src
|
solana_public_repos/drift-labs/protocol-v2/sdk/src/tx/txParamProcessor.ts
|
import {
Connection,
RpcResponseAndContext,
SimulatedTransactionResponse,
VersionedTransaction,
} from '@solana/web3.js';
import { BaseTxParams, ProcessingTxParams } from '..';
const COMPUTE_UNIT_BUFFER_FACTOR = 1.2;
const MAX_COMPUTE_UNITS = 1_400_000;
const TEST_SIMS_ALWAYS_FAIL = false;
type TransactionBuildingProps = {
txParams: BaseTxParams;
};
/**
* This class is responsible for running through a "processing" pipeline for a base transaction, to adjust the standard transaction parameters based on a given configuration.
*/
export class TransactionParamProcessor {
private static async getComputeUnitsFromSim(
txSim: RpcResponseAndContext<SimulatedTransactionResponse>
) {
if (txSim?.value?.unitsConsumed) {
return txSim?.value?.unitsConsumed;
}
return undefined;
}
public static async getTxSimComputeUnits(
tx: VersionedTransaction,
connection: Connection,
bufferMultiplier: number, // Making this a mandatory param to force the user to remember that simulated CU's can be inaccurate and a buffer should be applied
lowerBoundCu?: number
): Promise<{ success: boolean; computeUnits: number }> {
try {
if (TEST_SIMS_ALWAYS_FAIL)
throw new Error('Test Error::SIMS_ALWAYS_FAIL');
const simTxResult = await connection.simulateTransaction(tx, {
replaceRecentBlockhash: true, // This is important to ensure that the blockhash is not too new.. Otherwise we will very often receive a "blockHashNotFound" error
});
if (simTxResult?.value?.err) {
throw new Error(simTxResult?.value?.err?.toString());
}
const computeUnits = await this.getComputeUnitsFromSim(simTxResult);
// Apply the buffer, but round down to the MAX_COMPUTE_UNITS, and round up to the nearest whole number
let bufferedComputeUnits = Math.ceil(
Math.min(computeUnits * bufferMultiplier, MAX_COMPUTE_UNITS)
);
// If a lower bound CU is passed then enforce it
if (lowerBoundCu) {
bufferedComputeUnits = Math.max(
bufferedComputeUnits,
Math.min(lowerBoundCu, MAX_COMPUTE_UNITS)
);
}
return {
success: true,
computeUnits: bufferedComputeUnits,
};
} catch (e) {
console.warn(
`Failed to get Simulated Compute Units for txParamProcessor`,
e
);
return {
success: false,
computeUnits: undefined,
};
}
}
static async process(props: {
baseTxParams: BaseTxParams;
processConfig: ProcessingTxParams;
processParams: {
connection: Connection;
};
txBuilder: (
baseTransactionProps: TransactionBuildingProps
) => Promise<VersionedTransaction>;
}): Promise<BaseTxParams> {
// # Exit early if no process config is provided
if (!props.processConfig || Object.keys(props.processConfig).length === 0) {
return props.baseTxParams;
}
// # Setup
const {
txBuilder: txBuilder,
processConfig,
processParams: processProps,
} = props;
const finalTxParams: BaseTxParams = {
...props.baseTxParams,
};
// # Run Processes
if (processConfig.useSimulatedComputeUnits) {
const txToSim = await txBuilder({
txParams: { ...finalTxParams, computeUnits: MAX_COMPUTE_UNITS },
});
const txSimComputeUnitsResult = await this.getTxSimComputeUnits(
txToSim,
processProps.connection,
processConfig?.computeUnitsBufferMultiplier ??
COMPUTE_UNIT_BUFFER_FACTOR
);
if (txSimComputeUnitsResult.success) {
// Adjust the transaction based on the simulated compute units
finalTxParams.computeUnits = txSimComputeUnitsResult.computeUnits;
}
}
if (processConfig?.useSimulatedComputeUnitsForCUPriceCalculation) {
if (!processConfig?.useSimulatedComputeUnits) {
throw new Error(
`encountered useSimulatedComputeUnitsForFees=true, but useSimulatedComputeUnits is false`
);
}
if (!processConfig?.getCUPriceFromComputeUnits) {
throw new Error(
`encountered useSimulatedComputeUnitsForFees=true, but getComputeUnitPriceFromUnitsToUse helper method is undefined`
);
}
const simulatedComputeUnits = finalTxParams.computeUnits;
const computeUnitPrice = processConfig.getCUPriceFromComputeUnits(
simulatedComputeUnits
);
console.debug(
`🔧:: Adjusting compute unit price for simulated compute unit budget :: ${finalTxParams.computeUnitsPrice}=>${computeUnitPrice}`
);
finalTxParams.computeUnitsPrice = computeUnitPrice;
}
// # Return Final Tx Params
return finalTxParams;
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.