@thru/programs 0.3.17 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/dist/abi-manager/index.cjs +154 -33
- package/dist/abi-manager/index.cjs.map +1 -1
- package/dist/abi-manager/index.d.cts +1 -1
- package/dist/abi-manager/index.d.ts +1 -1
- package/dist/abi-manager/index.js +3 -2
- package/dist/amm/index.cjs +81 -47
- package/dist/amm/index.cjs.map +1 -1
- package/dist/amm/index.js +2 -3
- package/dist/amm/index.js.map +1 -1
- package/dist/bootstrap-addresses/index.cjs +58 -20
- package/dist/bootstrap-addresses/index.cjs.map +1 -1
- package/dist/bootstrap-addresses/index.d.cts +38 -19
- package/dist/bootstrap-addresses/index.d.ts +38 -19
- package/dist/bootstrap-addresses/index.js +2 -3
- package/dist/{chunk-6IC6CO5S.js → chunk-2NNQJFKS.js} +5 -4
- package/dist/chunk-2NNQJFKS.js.map +1 -0
- package/dist/chunk-4F54VFIH.js +58 -0
- package/dist/chunk-4F54VFIH.js.map +1 -0
- package/dist/{chunk-BNYDH4ZP.js → chunk-A2BWZE2D.js} +12 -10
- package/dist/chunk-A2BWZE2D.js.map +1 -0
- package/dist/{chunk-7DRJVAYI.js → chunk-A44ZPXY6.js} +5 -58
- package/dist/chunk-A44ZPXY6.js.map +1 -0
- package/dist/{chunk-YX7BLFQZ.js → chunk-JHINXDSG.js} +44 -5
- package/dist/chunk-JHINXDSG.js.map +1 -0
- package/dist/chunk-QGOAPK5X.js +174 -0
- package/dist/chunk-QGOAPK5X.js.map +1 -0
- package/dist/chunk-S3UTJHRO.js +77 -0
- package/dist/chunk-S3UTJHRO.js.map +1 -0
- package/dist/{chunk-CYG4PB65.js → chunk-ZOFTRAAH.js} +4 -4
- package/dist/{chunk-CYG4PB65.js.map → chunk-ZOFTRAAH.js.map} +1 -1
- package/dist/{chunk-ZHF2PH5H.js → chunk-ZP7A3GHV.js} +3 -4
- package/dist/chunk-ZP7A3GHV.js.map +1 -0
- package/dist/clob/index.cjs +380 -322
- package/dist/clob/index.cjs.map +1 -1
- package/dist/clob/index.d.cts +4 -3
- package/dist/clob/index.d.ts +4 -3
- package/dist/clob/index.js +36 -198
- package/dist/clob/index.js.map +1 -1
- package/dist/deploy/index.cjs +241 -169
- package/dist/deploy/index.cjs.map +1 -1
- package/dist/deploy/index.d.cts +5 -0
- package/dist/deploy/index.d.ts +5 -0
- package/dist/deploy/index.js +66 -37
- package/dist/deploy/index.js.map +1 -1
- package/dist/manager/index.cjs +15 -2
- package/dist/manager/index.cjs.map +1 -1
- package/dist/manager/index.d.cts +6 -79
- package/dist/manager/index.d.ts +6 -79
- package/dist/manager/index.js +2 -3
- package/dist/multicall/index.cjs +57 -23
- package/dist/multicall/index.cjs.map +1 -1
- package/dist/multicall/index.js +3 -4
- package/dist/oracle/index.cjs +64 -30
- package/dist/oracle/index.cjs.map +1 -1
- package/dist/oracle/index.d.cts +3 -39
- package/dist/oracle/index.d.ts +3 -39
- package/dist/oracle/index.js +2 -3
- package/dist/oracle/index.js.map +1 -1
- package/dist/orderbook-CEYM4N_S.d.cts +5 -0
- package/dist/orderbook-CEYM4N_S.d.ts +5 -0
- package/dist/passkey-manager/index.cjs +52 -18
- package/dist/passkey-manager/index.cjs.map +1 -1
- package/dist/passkey-manager/index.js +2 -3
- package/dist/passkey-manager/index.js.map +1 -1
- package/dist/perp/index.cjs +16750 -0
- package/dist/perp/index.cjs.map +1 -0
- package/dist/perp/index.d.cts +4577 -0
- package/dist/perp/index.d.ts +4577 -0
- package/dist/perp/index.js +16244 -0
- package/dist/perp/index.js.map +1 -0
- package/dist/token/index.js +2 -1
- package/dist/types-5XmDprcB.d.ts +81 -0
- package/dist/types-Cpi7Ibs2.d.cts +81 -0
- package/dist/types-T4cL02K7.d.cts +39 -0
- package/dist/types-T4cL02K7.d.ts +39 -0
- package/dist/uploader/index.cjs +46 -8
- package/dist/uploader/index.cjs.map +1 -1
- package/dist/uploader/index.d.cts +2 -1
- package/dist/uploader/index.d.ts +2 -1
- package/dist/uploader/index.js +2 -2
- package/package.json +7 -2
- package/src/abi-manager/constants.ts +2 -1
- package/src/abi-manager/index.test.ts +2 -2
- package/src/bootstrap-addresses/index.test.ts +70 -18
- package/src/bootstrap-addresses/index.ts +56 -19
- package/src/clob/index.ts +67 -201
- package/src/deploy/accounts.ts +7 -3
- package/src/deploy/chain.ts +1 -1
- package/src/deploy/constants.ts +3 -4
- package/src/deploy/deploy.test.ts +11 -10
- package/src/deploy/inspection.ts +3 -2
- package/src/deploy/types.ts +5 -0
- package/src/deploy/uploader.ts +5 -4
- package/src/deploy/workflows.test.ts +74 -5
- package/src/deploy/workflows.ts +55 -17
- package/src/manager/constants.ts +14 -2
- package/src/manager/derivation.ts +3 -3
- package/src/manager/index.test.ts +3 -3
- package/src/manager/index.ts +3 -0
- package/src/manager/types.ts +1 -1
- package/src/multicall/index.test.ts +1 -1
- package/src/passkey-manager/validate.test.ts +1 -1
- package/src/perp/abi/thru/common/primitives/types.ts +2428 -0
- package/src/perp/abi/thru/program/perp/types.ts +16813 -0
- package/src/perp/index.test.ts +822 -0
- package/src/perp/index.ts +1793 -0
- package/src/uploader/constants.ts +5 -4
- package/src/uploader/index.test.ts +2 -2
- package/src/uploader/index.ts +1 -0
- package/src/utils/helpers.ts +1 -1
- package/src/utils/orderbook.test.ts +86 -0
- package/src/utils/orderbook.ts +214 -0
- package/tsup.config.ts +1 -0
- package/dist/chunk-6IC6CO5S.js.map +0 -1
- package/dist/chunk-7DHFYBRW.js +0 -51
- package/dist/chunk-7DHFYBRW.js.map +0 -1
- package/dist/chunk-7DRJVAYI.js.map +0 -1
- package/dist/chunk-BNYDH4ZP.js.map +0 -1
- package/dist/chunk-VNTPD4AR.js +0 -37
- package/dist/chunk-VNTPD4AR.js.map +0 -1
- package/dist/chunk-YX7BLFQZ.js.map +0 -1
- package/dist/chunk-ZHF2PH5H.js.map +0 -1
|
@@ -0,0 +1,1793 @@
|
|
|
1
|
+
import { Pubkey, deriveProgramAddress } from '@thru/sdk';
|
|
2
|
+
import type { Account } from '@thru/sdk';
|
|
3
|
+
import type { Thru } from '@thru/sdk/client';
|
|
4
|
+
import { deriveManagedProgramAddresses } from '../manager/derivation';
|
|
5
|
+
import type { OracleFeed } from '../oracle/types';
|
|
6
|
+
import { deriveTokenAccountAddress } from '../token/derivation';
|
|
7
|
+
import {
|
|
8
|
+
accountData,
|
|
9
|
+
accountIndex,
|
|
10
|
+
assertU16,
|
|
11
|
+
type AccountLookupContext,
|
|
12
|
+
type InstructionData,
|
|
13
|
+
} from '../utils/helpers';
|
|
14
|
+
import {
|
|
15
|
+
CLIENT_ID_SIZE,
|
|
16
|
+
EVENT_REMOVE_REASON_EVICTED,
|
|
17
|
+
EVENT_REMOVE_REASON_EXPIRED,
|
|
18
|
+
EVENT_REMOVE_REASON_FILLED,
|
|
19
|
+
EVENT_REMOVE_REASON_USER,
|
|
20
|
+
EVENT_SIDE_BUY,
|
|
21
|
+
EVENT_SIDE_SELL,
|
|
22
|
+
NULL_ACCOUNT_INDEX,
|
|
23
|
+
ORDER_FLAG_BUY,
|
|
24
|
+
ORDER_FLAG_HAS_CLIENT_ID,
|
|
25
|
+
ORDER_TYPE_ALO,
|
|
26
|
+
ORDER_TYPE_FOK,
|
|
27
|
+
ORDER_TYPE_GTC,
|
|
28
|
+
ORDER_TYPE_IOC,
|
|
29
|
+
ORDER_TYPE_MTL,
|
|
30
|
+
STATUS_FLAG_DEPOSITS_FROZEN,
|
|
31
|
+
STATUS_FLAG_MASK,
|
|
32
|
+
STATUS_FLAG_PAUSED,
|
|
33
|
+
STATUS_FLAG_POST_ONLY,
|
|
34
|
+
STATUS_FLAG_WITHDRAWALS_FROZEN,
|
|
35
|
+
assertClientId,
|
|
36
|
+
assertStatusFlags,
|
|
37
|
+
assertU64,
|
|
38
|
+
assertU8,
|
|
39
|
+
buildModifyOrderMetadata,
|
|
40
|
+
bitField,
|
|
41
|
+
bytesFromView,
|
|
42
|
+
cbookLevelFromView,
|
|
43
|
+
eventSideFromValue,
|
|
44
|
+
fixedSeed,
|
|
45
|
+
groupByPrice,
|
|
46
|
+
optionalAccountIndex,
|
|
47
|
+
orderFlags,
|
|
48
|
+
orderTypeFromValue,
|
|
49
|
+
pubkeyViewToAddress,
|
|
50
|
+
removalReasonFromValue,
|
|
51
|
+
type OrderRemovalReason,
|
|
52
|
+
type OrderSide,
|
|
53
|
+
type OrderType,
|
|
54
|
+
} from '../utils/orderbook';
|
|
55
|
+
import {
|
|
56
|
+
CbookAccount,
|
|
57
|
+
CreateOrderEntryInstructionBuilder,
|
|
58
|
+
ExchangeInitializeInstructionBuilder,
|
|
59
|
+
ExchangeMetaAccount,
|
|
60
|
+
ExchangeSetAdminInstructionBuilder,
|
|
61
|
+
ExchangeSetStatusInstructionBuilder,
|
|
62
|
+
LiquidateInstructionBuilder,
|
|
63
|
+
MarketAccount as MarketAccountView,
|
|
64
|
+
MarketCreateInstructionBuilder,
|
|
65
|
+
MarketRecordInstructionBuilder,
|
|
66
|
+
MarketSetOracleInstructionBuilder,
|
|
67
|
+
MarketSetStatusInstructionBuilder,
|
|
68
|
+
ModifyOrderEntryInstructionBuilder,
|
|
69
|
+
OrderArenaAccount,
|
|
70
|
+
OrderArenaHeader,
|
|
71
|
+
OrderEntry as OrderEntryView,
|
|
72
|
+
PerpEvent,
|
|
73
|
+
PerpInstructionBuilder,
|
|
74
|
+
SeatArenaAccount,
|
|
75
|
+
SeatArenaHeader,
|
|
76
|
+
SeatCreateInstructionBuilder,
|
|
77
|
+
SeatEntry as SeatEntryView,
|
|
78
|
+
TokenTransferInstructionBuilder,
|
|
79
|
+
} from './abi/thru/program/perp/types';
|
|
80
|
+
|
|
81
|
+
export * from './abi/thru/program/perp/types';
|
|
82
|
+
|
|
83
|
+
/* The perp program is a copy of the spot CLOB with the base asset replaced by
|
|
84
|
+
a synthetic position (see thru-perps/README.md in the repository). Prices
|
|
85
|
+
are quote atoms per base atom; quantities are base atoms; positions and
|
|
86
|
+
resting orders are stored in lots. The perp is cross-margined: nothing is
|
|
87
|
+
locked, every position and resting order needs a fraction of its notional
|
|
88
|
+
at the oracle mark
|
|
89
|
+
|
|
90
|
+
mark = min(feed.price * mark_num / mark_den, price_cap)
|
|
91
|
+
notional_mark = lots * lot_size * mark
|
|
92
|
+
upnl = long: notional_mark - entry_notional, short: the negative
|
|
93
|
+
equity = quantity_quote + upnl
|
|
94
|
+
im_position = ceil(notional_mark * initial_margin_bps / 10000)
|
|
95
|
+
mm_position = ceil(notional_mark * maintenance_margin_bps / 10000)
|
|
96
|
+
im_orders = ceil((side(bids) + side(asks)) * initial_margin_bps / 10000), where resting
|
|
97
|
+
orders are netted against the position they would reduce:
|
|
98
|
+
side(lots, notional, reducible) = ceil(notional * (lots - reducible) / lots),
|
|
99
|
+
bid_reducible = min(open_bid_lots, short_lots), ask_reducible = min(open_ask_lots, long_lots)
|
|
100
|
+
free = equity - im_position - im_orders (withdrawable, must stay >= 0)
|
|
101
|
+
liquidatable = has a position and equity < mm_position
|
|
102
|
+
|
|
103
|
+
Realized PnL settles into quantity_quote on every fill; a seat that loses
|
|
104
|
+
more than its collateral leaves market.bad_debt. The demo deployment on
|
|
105
|
+
Alphanet is not a bootstrap program: it is managed by the deployer's key
|
|
106
|
+
under PERP_PROGRAM_SEED. */
|
|
107
|
+
|
|
108
|
+
export const PERP_PROGRAM_SEED = 'perps-demo';
|
|
109
|
+
export const PERP_PROGRAM_ADDRESSES = deriveManagedProgramAddresses(PERP_PROGRAM_SEED);
|
|
110
|
+
export const PERP_PROGRAM_ADDRESS = PERP_PROGRAM_ADDRESSES.programAccountAddress;
|
|
111
|
+
export const PERP_PROGRAM_META_ADDRESS = PERP_PROGRAM_ADDRESSES.programMetaAccountAddress;
|
|
112
|
+
|
|
113
|
+
export const PERP_INSTRUCTION_MARKET_RECORD = 0;
|
|
114
|
+
export const PERP_INSTRUCTION_SEAT_CREATE = 1;
|
|
115
|
+
export const PERP_INSTRUCTION_TOKEN_DEPOSIT = 2;
|
|
116
|
+
export const PERP_INSTRUCTION_TOKEN_WITHDRAW = 3;
|
|
117
|
+
export const PERP_INSTRUCTION_CREATE_ORDER_ENTRY = 4;
|
|
118
|
+
export const PERP_INSTRUCTION_MODIFY_ORDER_ENTRY = 5;
|
|
119
|
+
export const PERP_INSTRUCTION_MARKET_SET_STATUS = 8;
|
|
120
|
+
export const PERP_INSTRUCTION_MARKET_CREATE = 9;
|
|
121
|
+
export const PERP_INSTRUCTION_EXCHANGE_INITIALIZE = 11;
|
|
122
|
+
export const PERP_INSTRUCTION_EXCHANGE_SET_STATUS = 12;
|
|
123
|
+
export const PERP_INSTRUCTION_EXCHANGE_SET_ADMIN = 13;
|
|
124
|
+
export const PERP_INSTRUCTION_EXCHANGE_RECOVER_ADMIN = 14;
|
|
125
|
+
export const PERP_INSTRUCTION_MARKET_SET_EXCHANGE_STATUS = 15;
|
|
126
|
+
export const PERP_INSTRUCTION_LIQUIDATE = 0x10;
|
|
127
|
+
export const PERP_INSTRUCTION_MARKET_SET_ORACLE = 0x11;
|
|
128
|
+
/** Market record slot the demo tooling uses for its single market per transaction. */
|
|
129
|
+
export const PERP_DEFAULT_MARKET_RECORD_INDEX = 1;
|
|
130
|
+
|
|
131
|
+
/* Program specific user error codes (signed; the transaction status carries
|
|
132
|
+
them as u64 two's complement). The rest of the table is shared with the
|
|
133
|
+
spot CLOB. */
|
|
134
|
+
export const PERP_ERR_PRICE_ABOVE_CAP = -205n;
|
|
135
|
+
export const PERP_ERR_INVALID_PRICE_CAP = -206n;
|
|
136
|
+
export const PERP_ERR_INVALID_POSITION_LIMIT = -207n;
|
|
137
|
+
export const PERP_ERR_POSITION_LIMIT = -208n;
|
|
138
|
+
export const PERP_ERR_ARITH_OVERFLOW = -209n;
|
|
139
|
+
export const PERP_ERR_ORACLE_MISSING = -210n;
|
|
140
|
+
export const PERP_ERR_ORACLE_MISMATCH = -211n;
|
|
141
|
+
export const PERP_ERR_ORACLE_INVALID = -212n;
|
|
142
|
+
export const PERP_ERR_ORACLE_STALE = -213n;
|
|
143
|
+
export const PERP_ERR_INVALID_MARGIN_PARAMS = -214n;
|
|
144
|
+
export const PERP_ERR_NOT_LIQUIDATABLE = -215n;
|
|
145
|
+
export const PERP_ERR_SELF_LIQUIDATION = -216n;
|
|
146
|
+
export const PERP_ERR_INSUFFICIENT_COLLATERAL = -403n;
|
|
147
|
+
export const PERP_ERR_INSUFFICIENT_FUNDS_QUOTE = -401n;
|
|
148
|
+
|
|
149
|
+
export const PERP_EVENT_SEAT_ASSIGNED = 1;
|
|
150
|
+
export const PERP_EVENT_ORDER_CANCELLED = 2;
|
|
151
|
+
export const PERP_EVENT_MARKET_CREATED = 3;
|
|
152
|
+
export const PERP_EVENT_ORDER_FILLED = 4;
|
|
153
|
+
export const PERP_EVENT_ORDER_POSTED = 5;
|
|
154
|
+
export const PERP_EVENT_ORDER_ENTRY_REMOVED = 6;
|
|
155
|
+
export const PERP_EVENT_ORDER_MODIFIED = 7;
|
|
156
|
+
export const PERP_EVENT_TOKEN_DEPOSIT = 8;
|
|
157
|
+
export const PERP_EVENT_TOKEN_WITHDRAW = 9;
|
|
158
|
+
export const PERP_EVENT_MARKET_STATUS = 10;
|
|
159
|
+
export const PERP_EVENT_EXCHANGE_INITIALIZED = 11;
|
|
160
|
+
export const PERP_EVENT_EXCHANGE_STATUS = 12;
|
|
161
|
+
export const PERP_EVENT_EXCHANGE_ADMIN = 13;
|
|
162
|
+
export const PERP_EVENT_MARKET_EXCHANGE_STATUS = 14;
|
|
163
|
+
export const PERP_EVENT_LIQUIDATION = 15;
|
|
164
|
+
|
|
165
|
+
export const PERP_BPS_DENOMINATOR = 10_000n;
|
|
166
|
+
|
|
167
|
+
/* Book, flag and event encodings shared with the spot CLOB (utils/orderbook). */
|
|
168
|
+
export const PERP_EVENT_SIDE_BUY = EVENT_SIDE_BUY;
|
|
169
|
+
export const PERP_EVENT_SIDE_SELL = EVENT_SIDE_SELL;
|
|
170
|
+
export const PERP_EVENT_REMOVE_REASON_FILLED = EVENT_REMOVE_REASON_FILLED;
|
|
171
|
+
export const PERP_EVENT_REMOVE_REASON_EXPIRED = EVENT_REMOVE_REASON_EXPIRED;
|
|
172
|
+
export const PERP_EVENT_REMOVE_REASON_EVICTED = EVENT_REMOVE_REASON_EVICTED;
|
|
173
|
+
export const PERP_EVENT_REMOVE_REASON_USER = EVENT_REMOVE_REASON_USER;
|
|
174
|
+
|
|
175
|
+
export const PERP_STATUS_FLAG_PAUSED = STATUS_FLAG_PAUSED;
|
|
176
|
+
export const PERP_STATUS_FLAG_POST_ONLY = STATUS_FLAG_POST_ONLY;
|
|
177
|
+
export const PERP_STATUS_FLAG_WITHDRAWALS_FROZEN = STATUS_FLAG_WITHDRAWALS_FROZEN;
|
|
178
|
+
export const PERP_STATUS_FLAG_DEPOSITS_FROZEN = STATUS_FLAG_DEPOSITS_FROZEN;
|
|
179
|
+
export const PERP_STATUS_FLAG_MASK = STATUS_FLAG_MASK;
|
|
180
|
+
|
|
181
|
+
export const PERP_ORDER_TYPE_GTC = ORDER_TYPE_GTC;
|
|
182
|
+
export const PERP_ORDER_TYPE_MTL = ORDER_TYPE_MTL;
|
|
183
|
+
export const PERP_ORDER_TYPE_ALO = ORDER_TYPE_ALO;
|
|
184
|
+
export const PERP_ORDER_TYPE_IOC = ORDER_TYPE_IOC;
|
|
185
|
+
export const PERP_ORDER_TYPE_FOK = ORDER_TYPE_FOK;
|
|
186
|
+
|
|
187
|
+
export const PERP_ORDER_FLAG_BUY = ORDER_FLAG_BUY;
|
|
188
|
+
export const PERP_ORDER_FLAG_HAS_CLIENT_ID = ORDER_FLAG_HAS_CLIENT_ID;
|
|
189
|
+
export const PERP_MODIFY_FLAG_FAIL_IF_OUT_OF_RANGE = 1 << 0;
|
|
190
|
+
export const PERP_MODIFY_FLAG_HAS_CLIENT_ID = 1 << 1;
|
|
191
|
+
export const PERP_MODIFY_FLAG_HAS_ORDER_ID = 1 << 2;
|
|
192
|
+
|
|
193
|
+
export const PERP_MARKET_MAGIC = 0x79;
|
|
194
|
+
export const PERP_MARKET_ACCOUNT_SIZE = 320;
|
|
195
|
+
/** The seat arena's header entry starts here; seat index 1 follows it. */
|
|
196
|
+
export const PERP_SEAT_MANAGER_RESERVED_SIZE = 512;
|
|
197
|
+
export const PERP_EXCHANGE_META_ACCOUNT_SIZE = 96;
|
|
198
|
+
export const PERP_EXCHANGE_META_MAGIC = 0xf17eda2c9e290078n;
|
|
199
|
+
export const PERP_EXCHANGE_META_VERSION = 1;
|
|
200
|
+
export const PERP_EXCHANGE_META_SEED = fixedSeed('exchange_meta');
|
|
201
|
+
export const PERP_SEAT_ARENA_HEADER_SIZE = 128;
|
|
202
|
+
export const PERP_SEAT_ENTRY_SIZE = 128;
|
|
203
|
+
export const PERP_SEAT_ARENA_ENTRIES_OFFSET =
|
|
204
|
+
PERP_SEAT_MANAGER_RESERVED_SIZE + PERP_SEAT_ARENA_HEADER_SIZE;
|
|
205
|
+
export const PERP_ORDER_ARENA_HEADER_SIZE = 64;
|
|
206
|
+
/** 8 reserved bytes, the arena header, then order entry 1. */
|
|
207
|
+
export const PERP_ORDER_ARENA_ENTRIES_OFFSET = 8 + PERP_ORDER_ARENA_HEADER_SIZE;
|
|
208
|
+
export const PERP_ORDER_ENTRY_SIZE = 64;
|
|
209
|
+
export const PERP_CBOOK_HEADER_SIZE = 16;
|
|
210
|
+
export const PERP_CBOOK_LEVEL_SIZE = 8;
|
|
211
|
+
export const PERP_CBOOK_MAX_SIZE = ((1 << 24) - PERP_CBOOK_HEADER_SIZE) / PERP_CBOOK_LEVEL_SIZE;
|
|
212
|
+
export const PERP_CBOOK_EMPTY_PRICE_IN_TICKS = (1n << 64n) - 1n;
|
|
213
|
+
export const PERP_CBOOK_MAX_PRICE_IN_TICKS =
|
|
214
|
+
PERP_CBOOK_EMPTY_PRICE_IN_TICKS - 2n - BigInt(PERP_CBOOK_MAX_SIZE);
|
|
215
|
+
export const PERP_CLIENT_ID_SIZE = CLIENT_ID_SIZE;
|
|
216
|
+
export const PERP_NULL_INDEX = 0xfffff;
|
|
217
|
+
export const PERP_NULL_ACCOUNT_INDEX = NULL_ACCOUNT_INDEX;
|
|
218
|
+
export const PERP_MAX_ORDER_EXPIRATION_TIME = 9_223_372_036_854_775_807n;
|
|
219
|
+
|
|
220
|
+
type PerpInstructionVariant =
|
|
221
|
+
| 'market_record'
|
|
222
|
+
| 'seat_create'
|
|
223
|
+
| 'token_deposit'
|
|
224
|
+
| 'token_withdraw'
|
|
225
|
+
| 'create_order_entry'
|
|
226
|
+
| 'modify_order_entry'
|
|
227
|
+
| 'market_set_status'
|
|
228
|
+
| 'market_create'
|
|
229
|
+
| 'exchange_initialize'
|
|
230
|
+
| 'exchange_set_status'
|
|
231
|
+
| 'exchange_set_admin'
|
|
232
|
+
| 'exchange_recover_admin'
|
|
233
|
+
| 'market_set_exchange_status'
|
|
234
|
+
| 'liquidate'
|
|
235
|
+
| 'market_set_oracle';
|
|
236
|
+
|
|
237
|
+
export type PerpOrderSide = OrderSide;
|
|
238
|
+
export type PerpOrderType = OrderType;
|
|
239
|
+
export type PerpOrderRemovalReason = OrderRemovalReason;
|
|
240
|
+
|
|
241
|
+
export type { AccountLookupContext, InstructionData };
|
|
242
|
+
|
|
243
|
+
export interface PerpMarketRecordArgs {
|
|
244
|
+
marketRecordIndex: number;
|
|
245
|
+
seatArenaAccountBytes: Uint8Array;
|
|
246
|
+
orderArenaAccountBytes: Uint8Array;
|
|
247
|
+
bidsCbookAccountBytes: Uint8Array;
|
|
248
|
+
asksCbookAccountBytes: Uint8Array;
|
|
249
|
+
seatAuthorityAccountBytes?: Uint8Array;
|
|
250
|
+
seatIndex?: number;
|
|
251
|
+
exchangeMetaAccountBytes: Uint8Array;
|
|
252
|
+
tokenProgramAccountBytes?: Uint8Array;
|
|
253
|
+
quoteVaultAccountBytes?: Uint8Array;
|
|
254
|
+
marketAuthorityAccountBytes?: Uint8Array;
|
|
255
|
+
/** Oracle feed account (read-only). Required by every instruction that
|
|
256
|
+
needs the mark: post/match, withdraw and liquidate. Absent = 0xffff. */
|
|
257
|
+
oracleFeedAccountBytes?: Uint8Array;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export interface PerpMarginParams {
|
|
261
|
+
/** Initial margin as a fraction of notional at the mark, 1..10000. */
|
|
262
|
+
initialMarginBps: number;
|
|
263
|
+
/** Maintenance margin, 1 <= maintenance < initial. */
|
|
264
|
+
maintenanceMarginBps: number;
|
|
265
|
+
/** Fee the liquidated seat pays its liquidator, <= 10000. */
|
|
266
|
+
liquidationFeeBps: number;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export interface PerpOracleParams {
|
|
270
|
+
/** mark = min(feed.price * markNum / markDen, priceCap) */
|
|
271
|
+
markNum: bigint;
|
|
272
|
+
markDen: bigint;
|
|
273
|
+
/** The feed's exponent the market requires (feeds with another exponent are rejected). */
|
|
274
|
+
oracleExponent: number;
|
|
275
|
+
/** 0 = use the feed's own max_staleness_ns. */
|
|
276
|
+
maxMarkAgeNs: bigint;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export interface PerpMarketCreateArgs extends PerpMarginParams, PerpOracleParams {
|
|
280
|
+
marketRecordIndex: number;
|
|
281
|
+
tokenProgramAccountBytes: Uint8Array;
|
|
282
|
+
exchangeMetaAccountBytes: Uint8Array;
|
|
283
|
+
quoteMintAccountBytes: Uint8Array;
|
|
284
|
+
lotSize: bigint;
|
|
285
|
+
tickSize: bigint;
|
|
286
|
+
priceCap: bigint;
|
|
287
|
+
maxPositionLots: bigint;
|
|
288
|
+
oracleFeedAccountBytes: Uint8Array;
|
|
289
|
+
seatArenaAccountBytes: Uint8Array;
|
|
290
|
+
orderArenaAccountBytes: Uint8Array;
|
|
291
|
+
bidsCbookAccountBytes: Uint8Array;
|
|
292
|
+
asksCbookAccountBytes: Uint8Array;
|
|
293
|
+
quoteVaultAccountBytes: Uint8Array;
|
|
294
|
+
marketAuthorityAccountBytes: Uint8Array;
|
|
295
|
+
seatArenaStateProof: Uint8Array;
|
|
296
|
+
orderArenaStateProof: Uint8Array;
|
|
297
|
+
bidsCbookStateProof: Uint8Array;
|
|
298
|
+
asksCbookStateProof: Uint8Array;
|
|
299
|
+
quoteVaultStateProof: Uint8Array;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export interface PerpExchangeInitializeArgs {
|
|
303
|
+
exchangeMetaAccountBytes: Uint8Array;
|
|
304
|
+
programMetaAccountBytes: Uint8Array;
|
|
305
|
+
authorityAccountBytes: Uint8Array;
|
|
306
|
+
tokenProgramAccountBytes: Uint8Array;
|
|
307
|
+
exchangeAdminAccountBytes: Uint8Array;
|
|
308
|
+
stateProof: Uint8Array;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
export interface PerpExchangeSetStatusArgs {
|
|
312
|
+
exchangeMetaAccountBytes: Uint8Array;
|
|
313
|
+
exchangeAdminAccountBytes: Uint8Array;
|
|
314
|
+
statusFlags: number;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export interface PerpExchangeSetAdminArgs {
|
|
318
|
+
exchangeMetaAccountBytes: Uint8Array;
|
|
319
|
+
authorityAccountBytes: Uint8Array;
|
|
320
|
+
newAdminAccountBytes: Uint8Array;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export interface PerpSeatCreateArgs {
|
|
324
|
+
marketRecordIndex: number;
|
|
325
|
+
seatAuthorityAccountBytes: Uint8Array;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
export interface PerpTokenTransferArgs {
|
|
329
|
+
marketRecordIndex: number;
|
|
330
|
+
tokenProgramAccountBytes: Uint8Array;
|
|
331
|
+
fromAccountBytes: Uint8Array;
|
|
332
|
+
toAccountBytes: Uint8Array;
|
|
333
|
+
amount: bigint;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
export interface PerpCreateOrderArgs {
|
|
337
|
+
marketRecordIndex: number;
|
|
338
|
+
side: PerpOrderSide;
|
|
339
|
+
orderType?: PerpOrderType;
|
|
340
|
+
price: bigint;
|
|
341
|
+
quantity: bigint;
|
|
342
|
+
expirationTime?: bigint;
|
|
343
|
+
clientId?: Uint8Array;
|
|
344
|
+
discardAfterMatch?: boolean;
|
|
345
|
+
failIfOutsideBook?: boolean;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export interface PerpModifyOrderArgs {
|
|
349
|
+
marketRecordIndex: number;
|
|
350
|
+
orderEntryIndex: number;
|
|
351
|
+
quantity: bigint;
|
|
352
|
+
expirationTime: bigint;
|
|
353
|
+
failIfOutOfRange?: boolean;
|
|
354
|
+
clientId?: Uint8Array;
|
|
355
|
+
orderId?: bigint;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
export interface PerpMarketSetStatusArgs {
|
|
359
|
+
marketRecordIndex: number;
|
|
360
|
+
statusFlags: number;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export interface PerpLiquidateArgs {
|
|
364
|
+
marketRecordIndex: number;
|
|
365
|
+
/** Seat to liquidate; the signer's seat (in the market record) is the liquidator. */
|
|
366
|
+
targetSeatIndex: number;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export interface PerpMarketSetOracleArgs extends PerpOracleParams {
|
|
370
|
+
marketRecordIndex: number;
|
|
371
|
+
/** The new feed account; also has to be the record's oracle feed account. */
|
|
372
|
+
oracleFeedAccountBytes: Uint8Array;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export interface PerpMarket {
|
|
376
|
+
magic: number;
|
|
377
|
+
statusFlags: number;
|
|
378
|
+
exchangeStatusFlags: number;
|
|
379
|
+
lotSize: bigint;
|
|
380
|
+
tickSize: bigint;
|
|
381
|
+
nextOrderId: bigint;
|
|
382
|
+
priceCap: bigint;
|
|
383
|
+
maxPositionLots: bigint;
|
|
384
|
+
openInterestLots: bigint;
|
|
385
|
+
/** Quote written off at bankrupt fills (recorded only, no insurance fund). */
|
|
386
|
+
badDebt: bigint;
|
|
387
|
+
orderArena: string;
|
|
388
|
+
bidsCbook: string;
|
|
389
|
+
asksCbook: string;
|
|
390
|
+
quoteVault: string;
|
|
391
|
+
marketAuthority: string;
|
|
392
|
+
oracleFeed: string;
|
|
393
|
+
markNum: bigint;
|
|
394
|
+
markDen: bigint;
|
|
395
|
+
initialMarginBps: number;
|
|
396
|
+
maintenanceMarginBps: number;
|
|
397
|
+
liquidationFeeBps: number;
|
|
398
|
+
oracleExponent: number;
|
|
399
|
+
maxMarkAgeNs: bigint;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
export interface PerpExchangeMeta {
|
|
403
|
+
magic: bigint;
|
|
404
|
+
version: number;
|
|
405
|
+
statusFlags: number;
|
|
406
|
+
tokenProgram: string;
|
|
407
|
+
exchangeAdmin: string;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
export interface PerpArenaHeader {
|
|
411
|
+
nextEntryIndex: number;
|
|
412
|
+
freeMagic: bigint;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
export interface PerpArenaSlot<T> {
|
|
416
|
+
index: number;
|
|
417
|
+
active: boolean;
|
|
418
|
+
entry: T;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** Arena slots by arena index - 1. Inactive slots are holes (`slots[i]` is
|
|
422
|
+
undefined), so `length` is the arena capacity while `map`/`filter`/
|
|
423
|
+
`forEach` visit the active entries only. */
|
|
424
|
+
export type PerpArenaSlots<T> = Array<PerpArenaSlot<T> | undefined>;
|
|
425
|
+
|
|
426
|
+
export interface PerpSeatEntry {
|
|
427
|
+
seatIndex: number;
|
|
428
|
+
seatAuthority: string;
|
|
429
|
+
/** Collateral: deposits - withdrawals + realized pnl - fees. Not the
|
|
430
|
+
withdrawable amount; see perpFreeCollateral. */
|
|
431
|
+
quantityQuote: bigint;
|
|
432
|
+
longLots: bigint;
|
|
433
|
+
shortLots: bigint;
|
|
434
|
+
openBidLots: bigint;
|
|
435
|
+
openAskLots: bigint;
|
|
436
|
+
headOrderEntryIndex: number;
|
|
437
|
+
/** Quote paid (long) or received (short) for the open lots; average
|
|
438
|
+
entry = entryNotional / (lots * lotSize). */
|
|
439
|
+
entryNotional: bigint;
|
|
440
|
+
/** Sum of lots * lotSize * price over resting bids / asks. */
|
|
441
|
+
openBidNotional: bigint;
|
|
442
|
+
openAskNotional: bigint;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
export interface PerpOrderEntry {
|
|
446
|
+
orderEntryIndex: number;
|
|
447
|
+
seatNextOrderEntryIndex: number;
|
|
448
|
+
seatPreviousOrderEntryIndex: number;
|
|
449
|
+
seatIndex: number;
|
|
450
|
+
levelNextOrderEntryIndex: number;
|
|
451
|
+
levelPreviousOrderEntryIndex: number;
|
|
452
|
+
levelIndex: number;
|
|
453
|
+
levelAccountIndex: number;
|
|
454
|
+
quantityInLots: bigint;
|
|
455
|
+
orderId: bigint;
|
|
456
|
+
clientId: Uint8Array;
|
|
457
|
+
expirationTime: bigint;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
export interface PerpCbookLevel {
|
|
461
|
+
levelIndex: number;
|
|
462
|
+
headOrderEntryIndex: number;
|
|
463
|
+
tailOrderEntryIndex: number;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
export interface PerpCbook {
|
|
467
|
+
bestLevelIndex: number;
|
|
468
|
+
bestPriceInTicks: bigint;
|
|
469
|
+
levels: PerpCbookLevel[];
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
export interface PerpOrderBookOrder {
|
|
473
|
+
side: PerpOrderSide;
|
|
474
|
+
priceInTicks: bigint;
|
|
475
|
+
quantityInLots: bigint;
|
|
476
|
+
orderId: bigint;
|
|
477
|
+
orderEntryIndex: number;
|
|
478
|
+
seatIndex: number;
|
|
479
|
+
clientId: Uint8Array;
|
|
480
|
+
expirationTime: bigint;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
export interface PerpOrderBookLevel {
|
|
484
|
+
side: PerpOrderSide;
|
|
485
|
+
priceInTicks: bigint;
|
|
486
|
+
quantityInLots: bigint;
|
|
487
|
+
orders: PerpOrderBookOrder[];
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
export interface PerpOrderBookSnapshot {
|
|
491
|
+
bids: PerpOrderBookLevel[];
|
|
492
|
+
asks: PerpOrderBookLevel[];
|
|
493
|
+
bestBid: PerpOrderBookLevel | null;
|
|
494
|
+
bestAsk: PerpOrderBookLevel | null;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
export interface PerpMarketAccounts {
|
|
498
|
+
seatArena: { address: string; bytes: Uint8Array };
|
|
499
|
+
orderArena: { address: string; bytes: Uint8Array };
|
|
500
|
+
bidsCbook: { address: string; bytes: Uint8Array };
|
|
501
|
+
asksCbook: { address: string; bytes: Uint8Array };
|
|
502
|
+
quoteVault: { address: string; bytes: Uint8Array };
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
export interface ParsedPerpEventBase {
|
|
506
|
+
eventType: bigint;
|
|
507
|
+
variant: string;
|
|
508
|
+
payload: Uint8Array;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
export type ParsedPerpEvent =
|
|
512
|
+
| (ParsedPerpEventBase & {
|
|
513
|
+
variant: 'seat_assigned';
|
|
514
|
+
seatIndex: number;
|
|
515
|
+
seatAuthority: string;
|
|
516
|
+
market: string;
|
|
517
|
+
})
|
|
518
|
+
| (ParsedPerpEventBase & {
|
|
519
|
+
variant: 'order_cancelled';
|
|
520
|
+
seatIndex: number;
|
|
521
|
+
side: PerpOrderSide;
|
|
522
|
+
orderType: PerpOrderType;
|
|
523
|
+
price: bigint;
|
|
524
|
+
quantity: bigint;
|
|
525
|
+
clientId: Uint8Array;
|
|
526
|
+
market: string;
|
|
527
|
+
seatAuthority: string;
|
|
528
|
+
})
|
|
529
|
+
| (ParsedPerpEventBase & {
|
|
530
|
+
variant: 'market_created';
|
|
531
|
+
lotSize: bigint;
|
|
532
|
+
tickSize: bigint;
|
|
533
|
+
priceCap: bigint;
|
|
534
|
+
maxPositionLots: bigint;
|
|
535
|
+
quoteMint: string;
|
|
536
|
+
marketAuthority: string;
|
|
537
|
+
market: string;
|
|
538
|
+
orderArena: string;
|
|
539
|
+
bidsCbook: string;
|
|
540
|
+
asksCbook: string;
|
|
541
|
+
quoteVault: string;
|
|
542
|
+
})
|
|
543
|
+
| (ParsedPerpEventBase & {
|
|
544
|
+
variant: 'order_filled';
|
|
545
|
+
takerSeatIndex: number;
|
|
546
|
+
makerSeatIndex: number;
|
|
547
|
+
takerSide: PerpOrderSide;
|
|
548
|
+
price: bigint;
|
|
549
|
+
quantity: bigint;
|
|
550
|
+
makerOrderId: bigint;
|
|
551
|
+
makerClientId: Uint8Array;
|
|
552
|
+
takerLongLots: bigint;
|
|
553
|
+
takerShortLots: bigint;
|
|
554
|
+
makerLongLots: bigint;
|
|
555
|
+
makerShortLots: bigint;
|
|
556
|
+
market: string;
|
|
557
|
+
takerSeatAuthority: string;
|
|
558
|
+
makerSeatAuthority: string;
|
|
559
|
+
})
|
|
560
|
+
| (ParsedPerpEventBase & {
|
|
561
|
+
variant: 'order_posted';
|
|
562
|
+
seatIndex: number;
|
|
563
|
+
side: PerpOrderSide;
|
|
564
|
+
orderType: PerpOrderType;
|
|
565
|
+
price: bigint;
|
|
566
|
+
quantity: bigint;
|
|
567
|
+
orderId: bigint;
|
|
568
|
+
clientId: Uint8Array;
|
|
569
|
+
market: string;
|
|
570
|
+
seatAuthority: string;
|
|
571
|
+
})
|
|
572
|
+
| (ParsedPerpEventBase & {
|
|
573
|
+
variant: 'order_entry_removed';
|
|
574
|
+
seatIndex: number;
|
|
575
|
+
side: PerpOrderSide;
|
|
576
|
+
reason: PerpOrderRemovalReason;
|
|
577
|
+
price: bigint;
|
|
578
|
+
quantity: bigint;
|
|
579
|
+
orderId: bigint;
|
|
580
|
+
clientId: Uint8Array;
|
|
581
|
+
market: string;
|
|
582
|
+
seatAuthority: string;
|
|
583
|
+
})
|
|
584
|
+
| (ParsedPerpEventBase & {
|
|
585
|
+
variant: 'order_modified';
|
|
586
|
+
seatIndex: number;
|
|
587
|
+
side: PerpOrderSide;
|
|
588
|
+
price: bigint;
|
|
589
|
+
quantity: bigint;
|
|
590
|
+
orderId: bigint;
|
|
591
|
+
clientId: Uint8Array;
|
|
592
|
+
expirationTime: bigint;
|
|
593
|
+
market: string;
|
|
594
|
+
seatAuthority: string;
|
|
595
|
+
})
|
|
596
|
+
| (ParsedPerpEventBase & {
|
|
597
|
+
variant: 'token_deposit' | 'token_withdraw';
|
|
598
|
+
seatIndex: number;
|
|
599
|
+
amount: bigint;
|
|
600
|
+
quantityQuote: bigint;
|
|
601
|
+
longLots: bigint;
|
|
602
|
+
shortLots: bigint;
|
|
603
|
+
market: string;
|
|
604
|
+
seatAuthority: string;
|
|
605
|
+
wallet: string;
|
|
606
|
+
vault: string;
|
|
607
|
+
})
|
|
608
|
+
| (ParsedPerpEventBase & {
|
|
609
|
+
variant: 'liquidation';
|
|
610
|
+
market: string;
|
|
611
|
+
liquidator: string;
|
|
612
|
+
target: string;
|
|
613
|
+
liquidatorSeatIndex: number;
|
|
614
|
+
targetSeatIndex: number;
|
|
615
|
+
lots: bigint;
|
|
616
|
+
/** Transfer price: the mark clamped to the target's bankruptcy price. */
|
|
617
|
+
markPrice: bigint;
|
|
618
|
+
fee: bigint;
|
|
619
|
+
badDebt: bigint;
|
|
620
|
+
targetQuoteAfter: bigint;
|
|
621
|
+
liquidatorQuoteAfter: bigint;
|
|
622
|
+
/** Side of the target's position before the transfer. */
|
|
623
|
+
targetSide: 'long' | 'short';
|
|
624
|
+
})
|
|
625
|
+
| (ParsedPerpEventBase & {
|
|
626
|
+
variant:
|
|
627
|
+
| 'market_status'
|
|
628
|
+
| 'exchange_initialized'
|
|
629
|
+
| 'exchange_status'
|
|
630
|
+
| 'exchange_admin'
|
|
631
|
+
| 'market_exchange_status';
|
|
632
|
+
});
|
|
633
|
+
|
|
634
|
+
/* Derivation ***************************************************************/
|
|
635
|
+
|
|
636
|
+
export function derivePerpExchangeMetaAddress(
|
|
637
|
+
perpProgramAddress: string | Uint8Array | Pubkey = PERP_PROGRAM_ADDRESS,
|
|
638
|
+
) {
|
|
639
|
+
return deriveProgramAddress({
|
|
640
|
+
programAddress: perpProgramAddress,
|
|
641
|
+
seed: PERP_EXCHANGE_META_SEED,
|
|
642
|
+
ephemeral: false,
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** Mirrors derive_seed / derive_seed_unique in tn_perp_program/process/market_manager.c:
|
|
647
|
+
|
|
648
|
+
base = sha256(authority[32] || lot_size u64le || tick_size u64le ||
|
|
649
|
+
price_cap u64le || quote_mint[32] || initial_margin_bps u16le)
|
|
650
|
+
|
|
651
|
+
then one byte id per account ('s', 'o', 'b', 'a'). The quote vault is a
|
|
652
|
+
token account owned by the perp program with
|
|
653
|
+
new_account_seed = sha256(base || 'Q'). The u16 initial_margin_bps
|
|
654
|
+
(milestone 2, appended last, little-endian, 2 bytes) keeps margined
|
|
655
|
+
markets from colliding with milestone 1 markets. */
|
|
656
|
+
export async function derivePerpMarketAccounts(args: {
|
|
657
|
+
thru: Thru;
|
|
658
|
+
perpProgramAddress?: string;
|
|
659
|
+
tokenProgramAddress: string;
|
|
660
|
+
marketAuthorityAddress: string;
|
|
661
|
+
quoteMintAddress: string;
|
|
662
|
+
lotSize: bigint;
|
|
663
|
+
tickSize: bigint;
|
|
664
|
+
priceCap: bigint;
|
|
665
|
+
initialMarginBps: number;
|
|
666
|
+
}): Promise<PerpMarketAccounts> {
|
|
667
|
+
const perpProgram = args.perpProgramAddress ?? PERP_PROGRAM_ADDRESS;
|
|
668
|
+
const baseSeed = await sha256(
|
|
669
|
+
Pubkey.from(args.marketAuthorityAddress).toBytes(),
|
|
670
|
+
u64le(args.lotSize),
|
|
671
|
+
u64le(args.tickSize),
|
|
672
|
+
u64le(args.priceCap),
|
|
673
|
+
Pubkey.from(args.quoteMintAddress).toBytes(),
|
|
674
|
+
u16le(assertBps(args.initialMarginBps, 'initialMarginBps')),
|
|
675
|
+
);
|
|
676
|
+
const unique = async (id: string) => sha256(baseSeed, new TextEncoder().encode(id));
|
|
677
|
+
const pda = (seed: Uint8Array) => {
|
|
678
|
+
const derived = deriveProgramAddress({ programAddress: perpProgram, seed, ephemeral: false });
|
|
679
|
+
return { address: derived.address, bytes: derived.bytes };
|
|
680
|
+
};
|
|
681
|
+
const vault = deriveTokenAccountAddress(
|
|
682
|
+
args.thru,
|
|
683
|
+
perpProgram,
|
|
684
|
+
args.quoteMintAddress,
|
|
685
|
+
args.tokenProgramAddress,
|
|
686
|
+
await unique('Q'),
|
|
687
|
+
);
|
|
688
|
+
return {
|
|
689
|
+
seatArena: pda(await unique('s')),
|
|
690
|
+
orderArena: pda(await unique('o')),
|
|
691
|
+
bidsCbook: pda(await unique('b')),
|
|
692
|
+
asksCbook: pda(await unique('a')),
|
|
693
|
+
quoteVault: { address: vault.address, bytes: vault.bytes },
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/* Market accounts ***********************************************************/
|
|
698
|
+
|
|
699
|
+
/** Read-write accounts of a market in market record order: seat arena,
|
|
700
|
+
order arena, bids and asks cbooks. */
|
|
701
|
+
export function perpMarketAccountAddresses<T>(market: {
|
|
702
|
+
seatArena: T;
|
|
703
|
+
orderArena: T;
|
|
704
|
+
bidsCbook: T;
|
|
705
|
+
asksCbook: T;
|
|
706
|
+
}): T[] {
|
|
707
|
+
return [market.seatArena, market.orderArena, market.bidsCbook, market.asksCbook];
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/** Read-only accounts every trading transaction carries: the exchange meta
|
|
711
|
+
and the oracle feed the program reads the mark from. */
|
|
712
|
+
export function perpMarketReadOnlyAddresses<T>(market: { exchangeMeta: T; oracleFeed: T }): T[] {
|
|
713
|
+
return [market.exchangeMeta, market.oracleFeed];
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/* Margin math (bigint exact, mirrors utils/perp_math.h, utils/market.h and
|
|
717
|
+
utils/seat_entry.h). Every function takes the mark in quote atoms per base
|
|
718
|
+
atom as produced by perpMarkPrice. */
|
|
719
|
+
|
|
720
|
+
export type PerpMarginMarket = Pick<
|
|
721
|
+
PerpMarket,
|
|
722
|
+
'lotSize' | 'priceCap' | 'maxPositionLots' | 'initialMarginBps' | 'maintenanceMarginBps' | 'liquidationFeeBps'
|
|
723
|
+
>;
|
|
724
|
+
export type PerpMarkMarket = Pick<PerpMarket, 'priceCap' | 'markNum' | 'markDen'>;
|
|
725
|
+
export type PerpMarginSeat = Pick<
|
|
726
|
+
PerpSeatEntry,
|
|
727
|
+
'quantityQuote' | 'longLots' | 'shortLots' | 'openBidLots' | 'openAskLots' | 'entryNotional' | 'openBidNotional' | 'openAskNotional'
|
|
728
|
+
>;
|
|
729
|
+
|
|
730
|
+
/** mark = min(feed.price * markNum / markDen, priceCap); the program rejects
|
|
731
|
+
a zero mark (ORACLE_INVALID) and so does this. `feedPrice` is the raw
|
|
732
|
+
feed value (price_usd = feedPrice * 10^exponent). */
|
|
733
|
+
export function perpMarkPrice(feedPrice: bigint, market: PerpMarkMarket): bigint {
|
|
734
|
+
if (market.markNum <= 0n) throw new Error('markNum must be positive');
|
|
735
|
+
if (market.markDen <= 0n) throw new Error('markDen must be positive');
|
|
736
|
+
const mark = minBig((feedPrice * market.markNum) / market.markDen, market.priceCap);
|
|
737
|
+
if (mark <= 0n) throw new Error('mark price is zero');
|
|
738
|
+
return mark;
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/** The mark from a parsed oracle feed (parseOracleFeedAccount): the feed has
|
|
742
|
+
to be a price feed with the exponent the market pins, as the program
|
|
743
|
+
checks (ORACLE_INVALID / ORACLE_MISMATCH), then perpMarkPrice. */
|
|
744
|
+
export function perpMarkFromFeed(feed: OracleFeed, market: PerpMarkMarket & Pick<PerpMarket, 'oracleExponent'>): bigint {
|
|
745
|
+
if (feed.kind !== 'price') {
|
|
746
|
+
throw new Error(`oracle feed "${feed.common.feedName}" is a ${feed.kind} feed, not a price feed`);
|
|
747
|
+
}
|
|
748
|
+
if (feed.exponent !== market.oracleExponent) {
|
|
749
|
+
throw new Error(`oracle feed "${feed.common.feedName}" exponent ${feed.exponent} differs from the market's ${market.oracleExponent}`);
|
|
750
|
+
}
|
|
751
|
+
return perpMarkPrice(feed.price, market);
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/** markNum / markDen such that mark = feed.price * markNum / markDen is the
|
|
755
|
+
oracle price in quote atoms per base atom: price_usd = raw * 10^exponent
|
|
756
|
+
and atoms = price_usd * 10^(quoteDecimals - baseDecimals), so the fraction
|
|
757
|
+
is 10^(quoteDecimals - baseDecimals + exponent); a negative power goes in
|
|
758
|
+
the denominator. */
|
|
759
|
+
export function perpMarkFraction(quoteDecimals: number, baseDecimals: number, exponent: number): { markNum: bigint; markDen: bigint } {
|
|
760
|
+
for (const [label, value] of [['quoteDecimals', quoteDecimals], ['baseDecimals', baseDecimals], ['exponent', exponent]] as const) {
|
|
761
|
+
if (!Number.isInteger(value)) throw new Error(`${label} must be an integer`);
|
|
762
|
+
}
|
|
763
|
+
const power = quoteDecimals - baseDecimals + exponent;
|
|
764
|
+
return power >= 0 ? { markNum: 10n ** BigInt(power), markDen: 1n } : { markNum: 1n, markDen: 10n ** BigInt(-power) };
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** Display leverage of a market: floor(10000 / initialMarginBps). */
|
|
768
|
+
export function perpMaxLeverage(initialMarginBps: number): number {
|
|
769
|
+
if (!Number.isInteger(initialMarginBps) || initialMarginBps < 1 || initialMarginBps > Number(PERP_BPS_DENOMINATOR)) {
|
|
770
|
+
throw new Error(`initialMarginBps must be an integer between 1 and ${PERP_BPS_DENOMINATOR}`);
|
|
771
|
+
}
|
|
772
|
+
return Math.floor(Number(PERP_BPS_DENOMINATOR) / initialMarginBps);
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
/** lots * lotSize * price */
|
|
777
|
+
export function perpNotional(market: Pick<PerpMarket, 'lotSize'>, lots: bigint, price: bigint): bigint {
|
|
778
|
+
return lots * market.lotSize * price;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/** ceil(amount * bps / 10000) */
|
|
782
|
+
export function perpCeilBps(amount: bigint, bps: number | bigint): bigint {
|
|
783
|
+
return ceilDiv(amount * BigInt(bps), PERP_BPS_DENOMINATOR);
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/** Signed: long notional_mark - entryNotional, short entryNotional - notional_mark, flat 0. */
|
|
787
|
+
export function perpUnrealizedPnl(market: Pick<PerpMarket, 'lotSize'>, seat: PerpMarginSeat, mark: bigint): bigint {
|
|
788
|
+
if (seat.longLots > 0n) return perpNotional(market, seat.longLots, mark) - seat.entryNotional;
|
|
789
|
+
if (seat.shortLots > 0n) return seat.entryNotional - perpNotional(market, seat.shortLots, mark);
|
|
790
|
+
return 0n;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/** Signed: quantityQuote + unrealized pnl. */
|
|
794
|
+
export function perpEquity(market: Pick<PerpMarket, 'lotSize'>, seat: PerpMarginSeat, mark: bigint): bigint {
|
|
795
|
+
return seat.quantityQuote + perpUnrealizedPnl(market, seat, mark);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/** im_position = ceil(notional_mark * initialMarginBps / 10000) */
|
|
799
|
+
export function perpPositionInitialMargin(
|
|
800
|
+
market: Pick<PerpMarket, 'lotSize' | 'initialMarginBps'>,
|
|
801
|
+
seat: PerpMarginSeat,
|
|
802
|
+
mark: bigint,
|
|
803
|
+
): bigint {
|
|
804
|
+
return perpCeilBps(perpNotional(market, seat.longLots + seat.shortLots, mark), market.initialMarginBps);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
/** The part of one side's open notional that needs margin: resting orders
|
|
808
|
+
are netted against the position they would reduce, so of `lots` at
|
|
809
|
+
`notional` only `lots - reducible` count, pro rata and rounded up:
|
|
810
|
+
ceil(notional * (lots - reducible) / lots); 0 when the side is empty or
|
|
811
|
+
fully reducing. Mirrors seat_side_margin_notional. */
|
|
812
|
+
export function perpSideMarginNotional(lots: bigint, notional: bigint, reducible: bigint): bigint {
|
|
813
|
+
if (lots <= 0n) return 0n;
|
|
814
|
+
const margined = lots > reducible ? lots - reducible : 0n;
|
|
815
|
+
if (margined === 0n) return 0n;
|
|
816
|
+
if (margined === lots) return notional;
|
|
817
|
+
return ceilDiv(notional * margined, lots);
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/** im_orders = ceil((side(bids) + side(asks)) * initialMarginBps / 10000) with
|
|
821
|
+
bid_reducible = min(openBidLots, shortLots) and ask_reducible =
|
|
822
|
+
min(openAskLots, longLots). Mirrors seat_im_orders. */
|
|
823
|
+
export function perpOrderInitialMargin(market: Pick<PerpMarket, 'initialMarginBps'>, seat: PerpMarginSeat): bigint {
|
|
824
|
+
const bids = perpSideMarginNotional(seat.openBidLots, seat.openBidNotional, minBig(seat.openBidLots, seat.shortLots));
|
|
825
|
+
const asks = perpSideMarginNotional(seat.openAskLots, seat.openAskNotional, minBig(seat.openAskLots, seat.longLots));
|
|
826
|
+
return perpCeilBps(bids + asks, market.initialMarginBps);
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/** Initial margin of the position and every resting order. */
|
|
830
|
+
export function perpInitialMargin(
|
|
831
|
+
market: Pick<PerpMarket, 'lotSize' | 'initialMarginBps'>,
|
|
832
|
+
seat: PerpMarginSeat,
|
|
833
|
+
mark: bigint,
|
|
834
|
+
): bigint {
|
|
835
|
+
return perpPositionInitialMargin(market, seat, mark) + perpOrderInitialMargin(market, seat);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/** mm_position = ceil(notional_mark * maintenanceMarginBps / 10000) */
|
|
839
|
+
export function perpMaintenanceMargin(
|
|
840
|
+
market: Pick<PerpMarket, 'lotSize' | 'maintenanceMarginBps'>,
|
|
841
|
+
seat: PerpMarginSeat,
|
|
842
|
+
mark: bigint,
|
|
843
|
+
): bigint {
|
|
844
|
+
return perpCeilBps(perpNotional(market, seat.longLots + seat.shortLots, mark), market.maintenanceMarginBps);
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/** Signed: equity - im_position - im_orders. Withdrawable when >= 0; a
|
|
848
|
+
post that would make it negative fails with INSUFFICIENT_COLLATERAL. */
|
|
849
|
+
export function perpFreeCollateral(
|
|
850
|
+
market: Pick<PerpMarket, 'lotSize' | 'initialMarginBps'>,
|
|
851
|
+
seat: PerpMarginSeat,
|
|
852
|
+
mark: bigint,
|
|
853
|
+
): bigint {
|
|
854
|
+
return perpEquity(market, seat, mark) - perpInitialMargin(market, seat, mark);
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
/** Initial margin one lot needs at price p: ceil(lotSize * p * initialMarginBps / 10000). */
|
|
858
|
+
export function perpLotInitialMargin(market: Pick<PerpMarket, 'lotSize' | 'initialMarginBps'>, price: bigint): bigint {
|
|
859
|
+
return perpCeilBps(market.lotSize * price, market.initialMarginBps);
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/** Taker capacity (seat_max_buy_lots): closing short lots are always
|
|
863
|
+
allowed; opening lots are limited by the position limit and by
|
|
864
|
+
max(free, 0) / ceil(lotSize * price * initialMarginBps / 10000). */
|
|
865
|
+
export function perpMaxBuyLots(market: PerpMarginMarket, seat: PerpMarginSeat, price: bigint, mark: bigint): bigint {
|
|
866
|
+
const capacity = maxBig(market.maxPositionLots - seat.longLots - seat.openBidLots, 0n);
|
|
867
|
+
return seat.shortLots + minBig(capacity, affordableLots(market, seat, price, mark));
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
export function perpMaxSellLots(market: PerpMarginMarket, seat: PerpMarginSeat, price: bigint, mark: bigint): bigint {
|
|
871
|
+
const capacity = maxBig(market.maxPositionLots - seat.shortLots - seat.openAskLots, 0n);
|
|
872
|
+
return seat.longLots + minBig(capacity, affordableLots(market, seat, price, mark));
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
function affordableLots(market: PerpMarginMarket, seat: PerpMarginSeat, price: bigint, mark: bigint): bigint {
|
|
876
|
+
const perLot = perpLotInitialMargin(market, price);
|
|
877
|
+
const free = maxBig(perpFreeCollateral(market, seat, mark), 0n);
|
|
878
|
+
return perLot === 0n ? market.maxPositionLots : free / perLot;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/** Whether a post of `lots` at `price` on `side` passes the margin check:
|
|
882
|
+
free recomputed with the order's lots and notional added to the side's
|
|
883
|
+
open lots and notional (so the netting against the position applies to
|
|
884
|
+
the new order too) must stay >= 0. Position limits are not checked here. */
|
|
885
|
+
export function perpCanPostOrder(
|
|
886
|
+
market: PerpMarginMarket,
|
|
887
|
+
seat: PerpMarginSeat,
|
|
888
|
+
side: PerpOrderSide,
|
|
889
|
+
lots: bigint,
|
|
890
|
+
price: bigint,
|
|
891
|
+
mark: bigint,
|
|
892
|
+
): boolean {
|
|
893
|
+
const notional = perpNotional(market, lots, price);
|
|
894
|
+
const buy = side === 'buy';
|
|
895
|
+
const after: PerpMarginSeat = {
|
|
896
|
+
...seat,
|
|
897
|
+
openBidLots: seat.openBidLots + (buy ? lots : 0n),
|
|
898
|
+
openAskLots: seat.openAskLots + (buy ? 0n : lots),
|
|
899
|
+
openBidNotional: seat.openBidNotional + (buy ? notional : 0n),
|
|
900
|
+
openAskNotional: seat.openAskNotional + (buy ? 0n : notional),
|
|
901
|
+
};
|
|
902
|
+
return perpFreeCollateral(market, after, mark) >= 0n;
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/** Price at which the seat's equity is exactly zero: long
|
|
906
|
+
ceil((entryNotional - quantityQuote) / (lots * lotSize)) (0 when the
|
|
907
|
+
collateral covers the whole entry), short
|
|
908
|
+
floor((entryNotional + quantityQuote) / (lots * lotSize)) capped at
|
|
909
|
+
priceCap. null for a flat seat. */
|
|
910
|
+
export function perpBankruptcyPrice(market: Pick<PerpMarket, 'lotSize' | 'priceCap'>, seat: PerpMarginSeat): bigint | null {
|
|
911
|
+
if (seat.longLots > 0n) {
|
|
912
|
+
if (seat.quantityQuote >= seat.entryNotional) return 0n;
|
|
913
|
+
return ceilDiv(seat.entryNotional - seat.quantityQuote, seat.longLots * market.lotSize);
|
|
914
|
+
}
|
|
915
|
+
if (seat.shortLots > 0n) {
|
|
916
|
+
return minBig((seat.entryNotional + seat.quantityQuote) / (seat.shortLots * market.lotSize), market.priceCap);
|
|
917
|
+
}
|
|
918
|
+
return null;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/** Liquidatable iff the seat has a position and equity < mm_position. */
|
|
922
|
+
export function perpIsLiquidatable(
|
|
923
|
+
market: Pick<PerpMarket, 'lotSize' | 'maintenanceMarginBps'>,
|
|
924
|
+
seat: PerpMarginSeat,
|
|
925
|
+
mark: bigint,
|
|
926
|
+
): boolean {
|
|
927
|
+
if (seat.longLots === 0n && seat.shortLots === 0n) return false;
|
|
928
|
+
return perpEquity(market, seat, mark) < perpMaintenanceMargin(market, seat, mark);
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/** Display helper: the mark at which equity crosses the maintenance margin,
|
|
932
|
+
i.e. the highest mark (long) or lowest mark (short) at which the seat is
|
|
933
|
+
liquidatable. Solving equity = notional_mark * mm / 10000:
|
|
934
|
+
|
|
935
|
+
long m* = 10000 * (entryNotional - quantityQuote) / (L * (10000 - mm))
|
|
936
|
+
short m* = 10000 * (entryNotional + quantityQuote) / (L * (10000 + mm))
|
|
937
|
+
|
|
938
|
+
with L = lots * lotSize; a long is liquidatable below m*, a short above
|
|
939
|
+
it. null when the seat is flat or no mark in [1, priceCap] liquidates it
|
|
940
|
+
(a long whose collateral exceeds the maintenance requirement at any
|
|
941
|
+
price, or a short whose threshold is at or above the cap, where the mark
|
|
942
|
+
is clamped). */
|
|
943
|
+
export function perpLiquidationPrice(
|
|
944
|
+
market: Pick<PerpMarket, 'lotSize' | 'priceCap' | 'maintenanceMarginBps'>,
|
|
945
|
+
seat: PerpMarginSeat,
|
|
946
|
+
): bigint | null {
|
|
947
|
+
const mm = BigInt(market.maintenanceMarginBps);
|
|
948
|
+
if (seat.longLots > 0n) {
|
|
949
|
+
const numerator = PERP_BPS_DENOMINATOR * (seat.entryNotional - seat.quantityQuote);
|
|
950
|
+
if (numerator <= 0n) return null;
|
|
951
|
+
const denominator = seat.longLots * market.lotSize * (PERP_BPS_DENOMINATOR - mm);
|
|
952
|
+
/* highest integer m with m < numerator / denominator */
|
|
953
|
+
const price = ceilDiv(numerator, denominator) - 1n;
|
|
954
|
+
return price >= 1n ? minBig(price, market.priceCap) : null;
|
|
955
|
+
}
|
|
956
|
+
if (seat.shortLots > 0n) {
|
|
957
|
+
const numerator = PERP_BPS_DENOMINATOR * (seat.entryNotional + seat.quantityQuote);
|
|
958
|
+
const denominator = seat.shortLots * market.lotSize * (PERP_BPS_DENOMINATOR + mm);
|
|
959
|
+
/* lowest integer m with m > numerator / denominator */
|
|
960
|
+
const price = numerator / denominator + 1n;
|
|
961
|
+
return price <= market.priceCap ? price : null;
|
|
962
|
+
}
|
|
963
|
+
return null;
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
/** Leverage = notional at the mark / equity, in basis points (10000 = 1x).
|
|
967
|
+
null when the seat has no position or its equity is not positive. */
|
|
968
|
+
export function perpLeverageBps(market: Pick<PerpMarket, 'lotSize'>, seat: PerpMarginSeat, mark: bigint): bigint | null {
|
|
969
|
+
const lots = seat.longLots + seat.shortLots;
|
|
970
|
+
if (lots === 0n) return null;
|
|
971
|
+
const equity = perpEquity(market, seat, mark);
|
|
972
|
+
if (equity <= 0n) return null;
|
|
973
|
+
return (perpNotional(market, lots, mark) * PERP_BPS_DENOMINATOR) / equity;
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
/** Average entry price of the open position (entryNotional / (lots * lotSize)), null when flat. */
|
|
977
|
+
export function perpAverageEntryPrice(market: Pick<PerpMarket, 'lotSize'>, seat: PerpMarginSeat): bigint | null {
|
|
978
|
+
const lots = seat.longLots + seat.shortLots;
|
|
979
|
+
if (lots === 0n) return null;
|
|
980
|
+
return seat.entryNotional / (lots * market.lotSize);
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
/** Liquidation transfer price: the mark clamped to the target's bankruptcy
|
|
984
|
+
price (max for a long target, min for a short one), and the fee the
|
|
985
|
+
liquidator receives, min(notional_at_p_liq * liquidationFeeBps / 10000,
|
|
986
|
+
target.quantityQuote after the transfer). Preview only; the program is
|
|
987
|
+
authoritative. */
|
|
988
|
+
export function perpLiquidationPreview(
|
|
989
|
+
market: PerpMarginMarket,
|
|
990
|
+
target: PerpMarginSeat,
|
|
991
|
+
mark: bigint,
|
|
992
|
+
): { side: 'long' | 'short'; lots: bigint; price: bigint; fee: bigint; targetQuoteAfter: bigint } | null {
|
|
993
|
+
const bankruptcy = perpBankruptcyPrice(market, target);
|
|
994
|
+
if (bankruptcy === null) return null;
|
|
995
|
+
const long = target.longLots > 0n;
|
|
996
|
+
const lots = long ? target.longLots : target.shortLots;
|
|
997
|
+
const price = long ? maxBig(mark, bankruptcy) : minBig(mark, bankruptcy);
|
|
998
|
+
const notional = perpNotional(market, lots, price);
|
|
999
|
+
/* Closing at price realizes the whole position. */
|
|
1000
|
+
const realized = long ? notional - target.entryNotional : target.entryNotional - notional;
|
|
1001
|
+
const quoteAfterClose = maxBig(target.quantityQuote + realized, 0n);
|
|
1002
|
+
const fee = minBig((notional * BigInt(market.liquidationFeeBps)) / PERP_BPS_DENOMINATOR, quoteAfterClose);
|
|
1003
|
+
return { side: long ? 'long' : 'short', lots, price, fee, targetQuoteAfter: quoteAfterClose - fee };
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
|
|
1007
|
+
/* Instruction builders *****************************************************/
|
|
1008
|
+
|
|
1009
|
+
export function createPerpExchangeInitializeInstruction(args: PerpExchangeInitializeArgs): InstructionData {
|
|
1010
|
+
return async (context) => {
|
|
1011
|
+
const builder = new ExchangeInitializeInstructionBuilder()
|
|
1012
|
+
.set_reserved0(0)
|
|
1013
|
+
.set_exchange_meta_account_idx(accountIndex(context, args.exchangeMetaAccountBytes))
|
|
1014
|
+
.set_program_meta_account_idx(accountIndex(context, args.programMetaAccountBytes))
|
|
1015
|
+
.set_authority_account_idx(accountIndex(context, args.authorityAccountBytes))
|
|
1016
|
+
.set_token_program_idx(accountIndex(context, args.tokenProgramAccountBytes))
|
|
1017
|
+
.set_exchange_admin_account_idx(accountIndex(context, args.exchangeAdminAccountBytes));
|
|
1018
|
+
builder.proof().write(args.stateProof).finish();
|
|
1019
|
+
return buildPerpInstruction('exchange_initialize', builder.build());
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
export function createPerpExchangeSetStatusInstruction(args: PerpExchangeSetStatusArgs): InstructionData {
|
|
1024
|
+
return async (context) => {
|
|
1025
|
+
const payload = new ExchangeSetStatusInstructionBuilder()
|
|
1026
|
+
.set_status_flags(assertStatusFlags(args.statusFlags))
|
|
1027
|
+
.set_exchange_meta_account_idx(accountIndex(context, args.exchangeMetaAccountBytes))
|
|
1028
|
+
.set_exchange_admin_account_idx(accountIndex(context, args.exchangeAdminAccountBytes))
|
|
1029
|
+
.set_reserved0(0)
|
|
1030
|
+
.build();
|
|
1031
|
+
return buildPerpInstruction('exchange_set_status', payload);
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
export function createPerpExchangeSetAdminInstruction(args: PerpExchangeSetAdminArgs): InstructionData {
|
|
1036
|
+
return async (context) => {
|
|
1037
|
+
const payload = new ExchangeSetAdminInstructionBuilder()
|
|
1038
|
+
.set_reserved0(0)
|
|
1039
|
+
.set_exchange_meta_account_idx(accountIndex(context, args.exchangeMetaAccountBytes))
|
|
1040
|
+
.set_authority_account_idx(accountIndex(context, args.authorityAccountBytes))
|
|
1041
|
+
.set_new_admin_account_idx(accountIndex(context, args.newAdminAccountBytes))
|
|
1042
|
+
.build();
|
|
1043
|
+
return buildPerpInstruction('exchange_set_admin', payload);
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
export function createPerpMarketRecordInstruction(args: PerpMarketRecordArgs): InstructionData {
|
|
1048
|
+
const seatIndex = args.seatIndex === undefined ? PERP_NULL_INDEX : assertPerpSeatIndex(args.seatIndex);
|
|
1049
|
+
return async (context) => {
|
|
1050
|
+
const payload = new MarketRecordInstructionBuilder()
|
|
1051
|
+
.set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
|
|
1052
|
+
.set_seat_arena_account_idx(accountIndex(context, args.seatArenaAccountBytes))
|
|
1053
|
+
.set_order_arena_account_idx(accountIndex(context, args.orderArenaAccountBytes))
|
|
1054
|
+
.set_bids_cbook_account_idx(accountIndex(context, args.bidsCbookAccountBytes))
|
|
1055
|
+
.set_asks_cbook_account_idx(accountIndex(context, args.asksCbookAccountBytes))
|
|
1056
|
+
.set_seat_authority_account_idx(optionalAccountIndex(context, args.seatAuthorityAccountBytes))
|
|
1057
|
+
.set_seat_idx(seatIndex)
|
|
1058
|
+
.set_exchange_meta_account_idx(accountIndex(context, args.exchangeMetaAccountBytes))
|
|
1059
|
+
.set_token_program_idx(optionalAccountIndex(context, args.tokenProgramAccountBytes))
|
|
1060
|
+
.set_quote_vault_account_idx(args.quoteVaultAccountBytes ? accountIndex(context, args.quoteVaultAccountBytes) : 0)
|
|
1061
|
+
.set_market_authority_account_idx(optionalAccountIndex(context, args.marketAuthorityAccountBytes))
|
|
1062
|
+
.set_oracle_feed_account_idx(optionalAccountIndex(context, args.oracleFeedAccountBytes))
|
|
1063
|
+
.set_reserved0([0, 0, 0, 0, 0, 0])
|
|
1064
|
+
.build();
|
|
1065
|
+
return buildPerpInstruction('market_record', payload);
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
/** The named market authority must authorize the transaction. */
|
|
1070
|
+
export function createPerpMarketCreateInstruction(args: PerpMarketCreateArgs): InstructionData {
|
|
1071
|
+
return async (context) => {
|
|
1072
|
+
assertU64(args.lotSize, 'lotSize');
|
|
1073
|
+
assertU64(args.tickSize, 'tickSize');
|
|
1074
|
+
assertU64(args.priceCap, 'priceCap');
|
|
1075
|
+
assertU64(args.maxPositionLots, 'maxPositionLots');
|
|
1076
|
+
assertMarginParams(args);
|
|
1077
|
+
assertOracleParams(args);
|
|
1078
|
+
const builder = new MarketCreateInstructionBuilder()
|
|
1079
|
+
.set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
|
|
1080
|
+
.set_token_program_idx(accountIndex(context, args.tokenProgramAccountBytes))
|
|
1081
|
+
.set_exchange_meta_account_idx(accountIndex(context, args.exchangeMetaAccountBytes))
|
|
1082
|
+
.set_quote_mint_idx(accountIndex(context, args.quoteMintAccountBytes))
|
|
1083
|
+
.set_lot_size(args.lotSize)
|
|
1084
|
+
.set_tick_size(args.tickSize)
|
|
1085
|
+
.set_price_cap(args.priceCap)
|
|
1086
|
+
.set_max_position_lots(args.maxPositionLots)
|
|
1087
|
+
.set_seat_arena_account_idx(accountIndex(context, args.seatArenaAccountBytes))
|
|
1088
|
+
.set_order_arena_account_idx(accountIndex(context, args.orderArenaAccountBytes))
|
|
1089
|
+
.set_bids_cbook_account_idx(accountIndex(context, args.bidsCbookAccountBytes))
|
|
1090
|
+
.set_asks_cbook_account_idx(accountIndex(context, args.asksCbookAccountBytes))
|
|
1091
|
+
.set_quote_vault_account_idx(accountIndex(context, args.quoteVaultAccountBytes))
|
|
1092
|
+
.set_market_authority_account_idx(accountIndex(context, args.marketAuthorityAccountBytes))
|
|
1093
|
+
.set_oracle_feed_account_idx(accountIndex(context, args.oracleFeedAccountBytes))
|
|
1094
|
+
.set_initial_margin_bps(args.initialMarginBps)
|
|
1095
|
+
.set_maintenance_margin_bps(args.maintenanceMarginBps)
|
|
1096
|
+
.set_liquidation_fee_bps(args.liquidationFeeBps)
|
|
1097
|
+
.set_mark_num(args.markNum)
|
|
1098
|
+
.set_mark_den(args.markDen)
|
|
1099
|
+
.set_oracle_exponent(args.oracleExponent)
|
|
1100
|
+
.set_reserved1(0)
|
|
1101
|
+
.set_max_mark_age_ns(args.maxMarkAgeNs);
|
|
1102
|
+
builder.proof_seat_arena().write(args.seatArenaStateProof).finish();
|
|
1103
|
+
builder.proof_order_arena().write(args.orderArenaStateProof).finish();
|
|
1104
|
+
builder.proof_bids_cbook().write(args.bidsCbookStateProof).finish();
|
|
1105
|
+
builder.proof_asks_cbook().write(args.asksCbookStateProof).finish();
|
|
1106
|
+
builder.proof_quote_vault().write(args.quoteVaultStateProof).finish();
|
|
1107
|
+
return buildPerpInstruction('market_create', builder.build());
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
export function createPerpSeatCreateInstruction(args: PerpSeatCreateArgs): InstructionData {
|
|
1112
|
+
return async (context) => {
|
|
1113
|
+
const payload = new SeatCreateInstructionBuilder()
|
|
1114
|
+
.set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
|
|
1115
|
+
.set_seat_authority_account_idx(accountIndex(context, args.seatAuthorityAccountBytes))
|
|
1116
|
+
.set_reserved0([0, 0, 0, 0])
|
|
1117
|
+
.build();
|
|
1118
|
+
return buildPerpInstruction('seat_create', payload);
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
export function createPerpTokenDepositInstruction(args: PerpTokenTransferArgs): InstructionData {
|
|
1123
|
+
return createTokenTransferInstruction('token_deposit', args);
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
export function createPerpTokenWithdrawInstruction(args: PerpTokenTransferArgs): InstructionData {
|
|
1127
|
+
return createTokenTransferInstruction('token_withdraw', args);
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
export function createPerpOrderEntryInstruction(args: PerpCreateOrderArgs): InstructionData {
|
|
1131
|
+
return async () => {
|
|
1132
|
+
const flags = orderFlags(args);
|
|
1133
|
+
assertU64(args.price, 'price');
|
|
1134
|
+
assertU64(args.quantity, 'quantity');
|
|
1135
|
+
const builder = new CreateOrderEntryInstructionBuilder()
|
|
1136
|
+
.set_instruction_flags(flags)
|
|
1137
|
+
.set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
|
|
1138
|
+
.set_reserved0([0, 0, 0, 0, 0])
|
|
1139
|
+
.set_price(args.price)
|
|
1140
|
+
.set_quantity(args.quantity)
|
|
1141
|
+
.set_exp_time(args.expirationTime ?? PERP_MAX_ORDER_EXPIRATION_TIME);
|
|
1142
|
+
if (args.clientId) builder.client_id().write(assertClientId(args.clientId)).finish();
|
|
1143
|
+
return buildPerpInstruction('create_order_entry', builder.build());
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
export function createPerpModifyOrderEntryInstruction(args: PerpModifyOrderArgs): InstructionData {
|
|
1148
|
+
return async () => {
|
|
1149
|
+
let flags = args.failIfOutOfRange ? PERP_MODIFY_FLAG_FAIL_IF_OUT_OF_RANGE : 0;
|
|
1150
|
+
if (args.clientId) flags |= PERP_MODIFY_FLAG_HAS_CLIENT_ID;
|
|
1151
|
+
if (args.orderId !== undefined) flags |= PERP_MODIFY_FLAG_HAS_ORDER_ID;
|
|
1152
|
+
const metadata = buildModifyOrderMetadata(args);
|
|
1153
|
+
assertU64(args.quantity, 'quantity');
|
|
1154
|
+
const builder = new ModifyOrderEntryInstructionBuilder()
|
|
1155
|
+
.set_instruction_flags(flags)
|
|
1156
|
+
.set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
|
|
1157
|
+
.set_reserved0(0)
|
|
1158
|
+
.set_order_entry_idx(args.orderEntryIndex)
|
|
1159
|
+
.set_quantity(args.quantity)
|
|
1160
|
+
.set_exp_time(args.expirationTime);
|
|
1161
|
+
if (metadata.length) builder.metadata().write(metadata).finish();
|
|
1162
|
+
return buildPerpInstruction('modify_order_entry', builder.build());
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
/** Cancel is modify with quantity 0. */
|
|
1167
|
+
export function createPerpCancelOrderInstruction(args: {
|
|
1168
|
+
marketRecordIndex: number;
|
|
1169
|
+
orderEntryIndex: number;
|
|
1170
|
+
orderId?: bigint;
|
|
1171
|
+
}): InstructionData {
|
|
1172
|
+
return createPerpModifyOrderEntryInstruction({
|
|
1173
|
+
marketRecordIndex: args.marketRecordIndex,
|
|
1174
|
+
orderEntryIndex: args.orderEntryIndex,
|
|
1175
|
+
quantity: 0n,
|
|
1176
|
+
expirationTime: 0n,
|
|
1177
|
+
orderId: args.orderId,
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
export function createPerpMarketSetStatusInstruction(args: PerpMarketSetStatusArgs): InstructionData {
|
|
1182
|
+
return async () => {
|
|
1183
|
+
const payload = new MarketSetStatusInstructionBuilder()
|
|
1184
|
+
.set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
|
|
1185
|
+
.set_status_flags(assertStatusFlags(args.statusFlags))
|
|
1186
|
+
.set_reserved0([0, 0, 0, 0, 0])
|
|
1187
|
+
.build();
|
|
1188
|
+
return buildPerpInstruction('market_set_status', payload);
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
/** Liquidate `targetSeatIndex`; the signer's seat from the market record is
|
|
1193
|
+
the liquidator and takes over the position at the mark clamped to the
|
|
1194
|
+
target's bankruptcy price. The record needs the oracle feed account. */
|
|
1195
|
+
export function createPerpLiquidateInstruction(args: PerpLiquidateArgs): InstructionData {
|
|
1196
|
+
return async () => {
|
|
1197
|
+
const payload = new LiquidateInstructionBuilder()
|
|
1198
|
+
.set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
|
|
1199
|
+
.set_reserved0(0)
|
|
1200
|
+
.set_target_seat_idx(assertPerpSeatIndex(args.targetSeatIndex, 'targetSeatIndex'))
|
|
1201
|
+
.build();
|
|
1202
|
+
return buildPerpInstruction('liquidate', payload);
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
/** Market authority only: replaces the feed pubkey, mark fraction, required
|
|
1207
|
+
exponent and max mark age. The record must carry the market authority
|
|
1208
|
+
and the new feed account. */
|
|
1209
|
+
export function createPerpMarketSetOracleInstruction(args: PerpMarketSetOracleArgs): InstructionData {
|
|
1210
|
+
return async (context) => {
|
|
1211
|
+
assertOracleParams(args);
|
|
1212
|
+
const payload = new MarketSetOracleInstructionBuilder()
|
|
1213
|
+
.set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
|
|
1214
|
+
.set_oracle_feed_account_idx(accountIndex(context, args.oracleFeedAccountBytes))
|
|
1215
|
+
.set_oracle_exponent(args.oracleExponent)
|
|
1216
|
+
.set_mark_num(args.markNum)
|
|
1217
|
+
.set_mark_den(args.markDen)
|
|
1218
|
+
.set_max_mark_age_ns(args.maxMarkAgeNs)
|
|
1219
|
+
.set_reserved0(0n)
|
|
1220
|
+
.build();
|
|
1221
|
+
return buildPerpInstruction('market_set_oracle', payload);
|
|
1222
|
+
};
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
/** The perp entrypoint accepts several instructions concatenated in one
|
|
1226
|
+
payload; every trading instruction is preceded by a market_record. */
|
|
1227
|
+
export function concatPerpInstructions(...instructions: InstructionData[]): InstructionData {
|
|
1228
|
+
return async (context) => {
|
|
1229
|
+
const chunks: Uint8Array[] = [];
|
|
1230
|
+
for (const instruction of instructions) chunks.push(await instruction(context));
|
|
1231
|
+
const size = chunks.reduce((total, chunk) => total + chunk.length, 0);
|
|
1232
|
+
const bytes = new Uint8Array(size);
|
|
1233
|
+
let offset = 0;
|
|
1234
|
+
for (const chunk of chunks) {
|
|
1235
|
+
bytes.set(chunk, offset);
|
|
1236
|
+
offset += chunk.length;
|
|
1237
|
+
}
|
|
1238
|
+
return bytes;
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
/* Account parsers **********************************************************/
|
|
1243
|
+
|
|
1244
|
+
export function parsePerpExchangeMetaAccount(accountOrData: Account | Uint8Array): PerpExchangeMeta {
|
|
1245
|
+
const data = accountData(accountOrData, 'perp exchange metadata account');
|
|
1246
|
+
if (data.length !== PERP_EXCHANGE_META_ACCOUNT_SIZE) {
|
|
1247
|
+
throw new Error(`perp exchange metadata account must be ${PERP_EXCHANGE_META_ACCOUNT_SIZE} bytes`);
|
|
1248
|
+
}
|
|
1249
|
+
const parsed = ExchangeMetaAccount.from_array(data);
|
|
1250
|
+
if (!parsed) throw new Error('perp exchange metadata account data is malformed');
|
|
1251
|
+
if (parsed.get_magic() !== PERP_EXCHANGE_META_MAGIC) {
|
|
1252
|
+
throw new Error('perp exchange metadata account has an invalid magic value');
|
|
1253
|
+
}
|
|
1254
|
+
if (parsed.get_version() !== PERP_EXCHANGE_META_VERSION) {
|
|
1255
|
+
throw new Error('perp exchange metadata account has an unsupported version');
|
|
1256
|
+
}
|
|
1257
|
+
return {
|
|
1258
|
+
magic: parsed.get_magic(),
|
|
1259
|
+
version: parsed.get_version(),
|
|
1260
|
+
statusFlags: parsed.get_status_flags(),
|
|
1261
|
+
tokenProgram: pubkeyViewToAddress(parsed.get_token_program_pubkey()),
|
|
1262
|
+
exchangeAdmin: pubkeyViewToAddress(parsed.get_exchange_admin_pubkey()),
|
|
1263
|
+
};
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
export function parsePerpMarketAccount(accountOrData: Account | Uint8Array): PerpMarket {
|
|
1267
|
+
const data = accountData(accountOrData, 'perp market account');
|
|
1268
|
+
if (data[0] !== PERP_MARKET_MAGIC) throw new Error('account is not a perp market account');
|
|
1269
|
+
if (data.length < PERP_MARKET_ACCOUNT_SIZE) {
|
|
1270
|
+
throw new Error(`perp market account must be at least ${PERP_MARKET_ACCOUNT_SIZE} bytes`);
|
|
1271
|
+
}
|
|
1272
|
+
const parsed = MarketAccountView.from_array(data);
|
|
1273
|
+
if (!parsed) throw new Error('perp market account data is malformed');
|
|
1274
|
+
return marketFromView(parsed);
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
export function parsePerpSeatArenaAccount(accountOrData: Account | Uint8Array): {
|
|
1278
|
+
market: PerpMarket;
|
|
1279
|
+
header: PerpArenaHeader;
|
|
1280
|
+
slots: PerpArenaSlots<PerpSeatEntry>;
|
|
1281
|
+
seats: PerpSeatEntry[];
|
|
1282
|
+
} {
|
|
1283
|
+
const data = accountData(accountOrData, 'perp seat arena account');
|
|
1284
|
+
if (data[0] !== PERP_MARKET_MAGIC) throw new Error('account is not a perp seat arena');
|
|
1285
|
+
if (data.length < PERP_SEAT_ARENA_ENTRIES_OFFSET) {
|
|
1286
|
+
throw new Error(`perp seat arena must be at least ${PERP_SEAT_ARENA_ENTRIES_OFFSET} bytes`);
|
|
1287
|
+
}
|
|
1288
|
+
const parsed = SeatArenaAccount.from_array(data);
|
|
1289
|
+
if (!parsed) throw new Error('perp seat arena account data is malformed');
|
|
1290
|
+
const { slots, entries: seats } = activeArenaSlots(parsed.get_entries_length(), (idx) => {
|
|
1291
|
+
const entry = parsed.get_entries_at(idx);
|
|
1292
|
+
return entry.get_non_nullable_reserved() === 0n ? null : seatEntryFromView(entry, idx + 1);
|
|
1293
|
+
});
|
|
1294
|
+
return {
|
|
1295
|
+
market: marketFromView(parsed.get_market()),
|
|
1296
|
+
header: arenaHeaderFromView(parsed.get_header()),
|
|
1297
|
+
slots,
|
|
1298
|
+
seats,
|
|
1299
|
+
};
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
export function parsePerpOrderArenaAccount(accountOrData: Account | Uint8Array): {
|
|
1303
|
+
header: PerpArenaHeader;
|
|
1304
|
+
slots: PerpArenaSlots<PerpOrderEntry>;
|
|
1305
|
+
orders: PerpOrderEntry[];
|
|
1306
|
+
} {
|
|
1307
|
+
const data = accountData(accountOrData, 'perp order arena account');
|
|
1308
|
+
const parsed = OrderArenaAccount.from_array(data);
|
|
1309
|
+
if (!parsed) throw new Error('perp order arena account data is malformed');
|
|
1310
|
+
const { slots, entries: orders } = activeArenaSlots(parsed.get_entries_length(), (idx) => {
|
|
1311
|
+
const entry = parsed.get_entries_at(idx);
|
|
1312
|
+
return entry.get_expiry() === 0n ? null : orderEntryFromView(entry, idx + 1);
|
|
1313
|
+
});
|
|
1314
|
+
return {
|
|
1315
|
+
header: arenaHeaderFromView(parsed.get_header()),
|
|
1316
|
+
slots,
|
|
1317
|
+
orders,
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
/** Preserve arena indexes while only decoding active entries. The generated
|
|
1322
|
+
ABI accessors own entry sizes, offsets, and activity marker reads. */
|
|
1323
|
+
function activeArenaSlots<T>(
|
|
1324
|
+
count: number,
|
|
1325
|
+
decode: (idx: number) => T | null,
|
|
1326
|
+
): { slots: PerpArenaSlots<T>; entries: T[] } {
|
|
1327
|
+
const slots: PerpArenaSlots<T> = new Array(count);
|
|
1328
|
+
const entries: T[] = [];
|
|
1329
|
+
for (let idx = 0; idx < count; idx++) {
|
|
1330
|
+
const entry = decode(idx);
|
|
1331
|
+
if (entry === null) continue;
|
|
1332
|
+
slots[idx] = { index: idx + 1, active: true, entry };
|
|
1333
|
+
entries.push(entry);
|
|
1334
|
+
}
|
|
1335
|
+
return { slots, entries };
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
|
|
1339
|
+
export function parsePerpCbookAccount(accountOrData: Account | Uint8Array): PerpCbook {
|
|
1340
|
+
const data = accountData(accountOrData, 'perp cbook account');
|
|
1341
|
+
const parsed = CbookAccount.from_array(data);
|
|
1342
|
+
if (!parsed) throw new Error('perp cbook account data is malformed');
|
|
1343
|
+
const header = parsed.get_header();
|
|
1344
|
+
return {
|
|
1345
|
+
bestLevelIndex: header.get_best_level_idx(),
|
|
1346
|
+
bestPriceInTicks: header.get_best_price_in_ticks(),
|
|
1347
|
+
levels: parsed.get_levels().map((level, idx) => cbookLevelFromView(level, idx)),
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
/** Rebuild the visible book from the order arena plus both cbooks. Orders
|
|
1352
|
+
on level account 0 are bids, on 1 asks. Prices are in ticks. */
|
|
1353
|
+
export function buildPerpOrderBookSnapshot(args: {
|
|
1354
|
+
orders: PerpOrderEntry[];
|
|
1355
|
+
bidsCbook: PerpCbook;
|
|
1356
|
+
asksCbook: PerpCbook;
|
|
1357
|
+
}): PerpOrderBookSnapshot {
|
|
1358
|
+
const bids: PerpOrderBookOrder[] = [];
|
|
1359
|
+
const asks: PerpOrderBookOrder[] = [];
|
|
1360
|
+
for (const order of args.orders) {
|
|
1361
|
+
if (order.levelAccountIndex === 0) bids.push(bookOrder(order, 'buy', args.bidsCbook));
|
|
1362
|
+
else if (order.levelAccountIndex === 1) asks.push(bookOrder(order, 'sell', args.asksCbook));
|
|
1363
|
+
}
|
|
1364
|
+
const bidLevels = groupByPrice(bids, 'buy');
|
|
1365
|
+
const askLevels = groupByPrice(asks, 'sell');
|
|
1366
|
+
return {
|
|
1367
|
+
bids: bidLevels,
|
|
1368
|
+
asks: askLevels,
|
|
1369
|
+
bestBid: bidLevels[0] ?? null,
|
|
1370
|
+
bestAsk: askLevels[0] ?? null,
|
|
1371
|
+
};
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
/** Orders that belong to one seat, walking its linked list. */
|
|
1375
|
+
export function perpSeatOrders(seat: PerpSeatEntry, arena: { slots: PerpArenaSlots<PerpOrderEntry> }): PerpOrderEntry[] {
|
|
1376
|
+
|
|
1377
|
+
const orders: PerpOrderEntry[] = [];
|
|
1378
|
+
let index = seat.headOrderEntryIndex;
|
|
1379
|
+
let guard = 0;
|
|
1380
|
+
while (index !== 0 && guard++ < arena.slots.length) {
|
|
1381
|
+
const slot = arena.slots[index - 1];
|
|
1382
|
+
if (!slot || !slot.active) break;
|
|
1383
|
+
orders.push(slot.entry);
|
|
1384
|
+
index = slot.entry.seatNextOrderEntryIndex;
|
|
1385
|
+
}
|
|
1386
|
+
return orders;
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
export function parsePerpEvent(data: Uint8Array): ParsedPerpEvent {
|
|
1390
|
+
const parsed = PerpEvent.from_array(data);
|
|
1391
|
+
if (!parsed) throw new Error('perp event data is malformed');
|
|
1392
|
+
const variant = parsed.payloadVariant();
|
|
1393
|
+
if (!variant) throw new Error('perp event type is unknown');
|
|
1394
|
+
const eventType = parsed.get_event_type();
|
|
1395
|
+
const payload = parsed.payload();
|
|
1396
|
+
const base = { eventType, variant: variant.name, payload: payload.bytes() };
|
|
1397
|
+
|
|
1398
|
+
switch (variant.name) {
|
|
1399
|
+
case 'seat_assigned': {
|
|
1400
|
+
const event = payload.asSeatAssigned();
|
|
1401
|
+
if (!event) throw new Error('perp seat_assigned event payload is malformed');
|
|
1402
|
+
return {
|
|
1403
|
+
...base,
|
|
1404
|
+
variant: 'seat_assigned',
|
|
1405
|
+
seatIndex: event.get_seat_idx(),
|
|
1406
|
+
seatAuthority: pubkeyViewToAddress(event.get_seat_authority()),
|
|
1407
|
+
market: pubkeyViewToAddress(event.get_market()),
|
|
1408
|
+
};
|
|
1409
|
+
}
|
|
1410
|
+
case 'order_cancelled': {
|
|
1411
|
+
const event = payload.asOrderCancelled();
|
|
1412
|
+
if (!event) throw new Error('perp order_cancelled event payload is malformed');
|
|
1413
|
+
return {
|
|
1414
|
+
...base,
|
|
1415
|
+
variant: 'order_cancelled',
|
|
1416
|
+
seatIndex: event.get_seat_idx(),
|
|
1417
|
+
side: eventSideFromValue(event.get_side()),
|
|
1418
|
+
orderType: orderTypeFromValue(event.get_order_type()),
|
|
1419
|
+
price: event.get_price(),
|
|
1420
|
+
quantity: event.get_qty(),
|
|
1421
|
+
clientId: bytesFromView(event.get_client_id()),
|
|
1422
|
+
market: pubkeyViewToAddress(event.get_market()),
|
|
1423
|
+
seatAuthority: pubkeyViewToAddress(event.get_seat_authority()),
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
case 'market_created': {
|
|
1427
|
+
const event = payload.asMarketCreated();
|
|
1428
|
+
if (!event) throw new Error('perp market_created event payload is malformed');
|
|
1429
|
+
return {
|
|
1430
|
+
...base,
|
|
1431
|
+
variant: 'market_created',
|
|
1432
|
+
lotSize: event.get_lot_size(),
|
|
1433
|
+
tickSize: event.get_tick_size(),
|
|
1434
|
+
priceCap: event.get_price_cap(),
|
|
1435
|
+
maxPositionLots: event.get_max_position_lots(),
|
|
1436
|
+
quoteMint: pubkeyViewToAddress(event.get_quote_mint()),
|
|
1437
|
+
marketAuthority: pubkeyViewToAddress(event.get_market_authority()),
|
|
1438
|
+
market: pubkeyViewToAddress(event.get_market()),
|
|
1439
|
+
orderArena: pubkeyViewToAddress(event.get_order_arena()),
|
|
1440
|
+
bidsCbook: pubkeyViewToAddress(event.get_bids_cbook()),
|
|
1441
|
+
asksCbook: pubkeyViewToAddress(event.get_asks_cbook()),
|
|
1442
|
+
quoteVault: pubkeyViewToAddress(event.get_quote_vault()),
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
case 'order_filled': {
|
|
1446
|
+
const event = payload.asOrderFilled();
|
|
1447
|
+
if (!event) throw new Error('perp order_filled event payload is malformed');
|
|
1448
|
+
return {
|
|
1449
|
+
...base,
|
|
1450
|
+
variant: 'order_filled',
|
|
1451
|
+
takerSeatIndex: event.get_taker_seat_idx(),
|
|
1452
|
+
makerSeatIndex: event.get_maker_seat_idx(),
|
|
1453
|
+
takerSide: eventSideFromValue(event.get_taker_side()),
|
|
1454
|
+
price: event.get_price(),
|
|
1455
|
+
quantity: event.get_qty(),
|
|
1456
|
+
makerOrderId: event.get_maker_order_id(),
|
|
1457
|
+
makerClientId: bytesFromView(event.get_maker_client_id()),
|
|
1458
|
+
takerLongLots: event.get_taker_long_lots(),
|
|
1459
|
+
takerShortLots: event.get_taker_short_lots(),
|
|
1460
|
+
makerLongLots: event.get_maker_long_lots(),
|
|
1461
|
+
makerShortLots: event.get_maker_short_lots(),
|
|
1462
|
+
market: pubkeyViewToAddress(event.get_market()),
|
|
1463
|
+
takerSeatAuthority: pubkeyViewToAddress(event.get_taker_seat_authority()),
|
|
1464
|
+
makerSeatAuthority: pubkeyViewToAddress(event.get_maker_seat_authority()),
|
|
1465
|
+
};
|
|
1466
|
+
}
|
|
1467
|
+
case 'order_posted': {
|
|
1468
|
+
const event = payload.asOrderPosted();
|
|
1469
|
+
if (!event) throw new Error('perp order_posted event payload is malformed');
|
|
1470
|
+
return {
|
|
1471
|
+
...base,
|
|
1472
|
+
variant: 'order_posted',
|
|
1473
|
+
seatIndex: event.get_seat_idx(),
|
|
1474
|
+
side: eventSideFromValue(event.get_side()),
|
|
1475
|
+
orderType: orderTypeFromValue(event.get_order_type()),
|
|
1476
|
+
price: event.get_price(),
|
|
1477
|
+
quantity: event.get_qty(),
|
|
1478
|
+
orderId: event.get_order_id(),
|
|
1479
|
+
clientId: bytesFromView(event.get_client_id()),
|
|
1480
|
+
market: pubkeyViewToAddress(event.get_market()),
|
|
1481
|
+
seatAuthority: pubkeyViewToAddress(event.get_seat_authority()),
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
case 'order_entry_removed': {
|
|
1485
|
+
const event = payload.asOrderEntryRemoved();
|
|
1486
|
+
if (!event) throw new Error('perp order_entry_removed event payload is malformed');
|
|
1487
|
+
return {
|
|
1488
|
+
...base,
|
|
1489
|
+
variant: 'order_entry_removed',
|
|
1490
|
+
seatIndex: event.get_seat_idx(),
|
|
1491
|
+
side: eventSideFromValue(event.get_side()),
|
|
1492
|
+
reason: removalReasonFromValue(event.get_reason()),
|
|
1493
|
+
price: event.get_price(),
|
|
1494
|
+
quantity: event.get_qty(),
|
|
1495
|
+
orderId: event.get_order_id(),
|
|
1496
|
+
clientId: bytesFromView(event.get_client_id()),
|
|
1497
|
+
market: pubkeyViewToAddress(event.get_market()),
|
|
1498
|
+
seatAuthority: pubkeyViewToAddress(event.get_seat_authority()),
|
|
1499
|
+
};
|
|
1500
|
+
}
|
|
1501
|
+
case 'order_modified': {
|
|
1502
|
+
const event = payload.asOrderModified();
|
|
1503
|
+
if (!event) throw new Error('perp order_modified event payload is malformed');
|
|
1504
|
+
return {
|
|
1505
|
+
...base,
|
|
1506
|
+
variant: 'order_modified',
|
|
1507
|
+
seatIndex: event.get_seat_idx(),
|
|
1508
|
+
side: eventSideFromValue(event.get_side()),
|
|
1509
|
+
price: event.get_price(),
|
|
1510
|
+
quantity: event.get_qty(),
|
|
1511
|
+
orderId: event.get_order_id(),
|
|
1512
|
+
clientId: bytesFromView(event.get_client_id()),
|
|
1513
|
+
expirationTime: event.get_exp_time(),
|
|
1514
|
+
market: pubkeyViewToAddress(event.get_market()),
|
|
1515
|
+
seatAuthority: pubkeyViewToAddress(event.get_seat_authority()),
|
|
1516
|
+
};
|
|
1517
|
+
}
|
|
1518
|
+
case 'token_deposit':
|
|
1519
|
+
case 'token_withdraw': {
|
|
1520
|
+
const event = variant.name === 'token_deposit' ? payload.asTokenDeposit() : payload.asTokenWithdraw();
|
|
1521
|
+
if (!event) throw new Error(`perp ${variant.name} event payload is malformed`);
|
|
1522
|
+
return {
|
|
1523
|
+
...base,
|
|
1524
|
+
variant: variant.name,
|
|
1525
|
+
seatIndex: event.get_seat_idx(),
|
|
1526
|
+
amount: event.get_amount(),
|
|
1527
|
+
quantityQuote: event.get_quantity_quote(),
|
|
1528
|
+
longLots: event.get_long_lots(),
|
|
1529
|
+
shortLots: event.get_short_lots(),
|
|
1530
|
+
market: pubkeyViewToAddress(event.get_market()),
|
|
1531
|
+
seatAuthority: pubkeyViewToAddress(event.get_seat_authority()),
|
|
1532
|
+
wallet: pubkeyViewToAddress(event.get_wallet()),
|
|
1533
|
+
vault: pubkeyViewToAddress(event.get_vault()),
|
|
1534
|
+
};
|
|
1535
|
+
}
|
|
1536
|
+
case 'liquidation': {
|
|
1537
|
+
const event = payload.asLiquidation();
|
|
1538
|
+
if (!event) throw new Error('perp liquidation event payload is malformed');
|
|
1539
|
+
return {
|
|
1540
|
+
...base,
|
|
1541
|
+
variant: 'liquidation',
|
|
1542
|
+
market: pubkeyViewToAddress(event.get_market()),
|
|
1543
|
+
liquidator: pubkeyViewToAddress(event.get_liquidator()),
|
|
1544
|
+
target: pubkeyViewToAddress(event.get_target()),
|
|
1545
|
+
liquidatorSeatIndex: event.get_liquidator_seat_idx(),
|
|
1546
|
+
targetSeatIndex: event.get_target_seat_idx(),
|
|
1547
|
+
lots: event.get_lots(),
|
|
1548
|
+
markPrice: event.get_mark_price(),
|
|
1549
|
+
fee: event.get_fee(),
|
|
1550
|
+
badDebt: event.get_bad_debt(),
|
|
1551
|
+
targetQuoteAfter: event.get_target_quote_after(),
|
|
1552
|
+
liquidatorQuoteAfter: event.get_liquidator_quote_after(),
|
|
1553
|
+
targetSide: liquidationSideFromValue(event.get_side()),
|
|
1554
|
+
};
|
|
1555
|
+
}
|
|
1556
|
+
case 'market_status':
|
|
1557
|
+
case 'exchange_initialized':
|
|
1558
|
+
case 'exchange_status':
|
|
1559
|
+
case 'exchange_admin':
|
|
1560
|
+
case 'market_exchange_status':
|
|
1561
|
+
return { ...base, variant: variant.name };
|
|
1562
|
+
default:
|
|
1563
|
+
throw new Error('perp event type is unsupported');
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
|
|
1568
|
+
export function assertPerpSeatIndex(value: number, label = 'seatIndex'): number {
|
|
1569
|
+
if (!Number.isSafeInteger(value) || value < 1 || value >= PERP_NULL_INDEX) {
|
|
1570
|
+
throw new Error(`${label} must be an integer between 1 and ${PERP_NULL_INDEX - 1}`);
|
|
1571
|
+
}
|
|
1572
|
+
return value;
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
/* Internals *****************************************************************/
|
|
1576
|
+
|
|
1577
|
+
function createTokenTransferInstruction(
|
|
1578
|
+
variant: 'token_deposit' | 'token_withdraw',
|
|
1579
|
+
args: PerpTokenTransferArgs,
|
|
1580
|
+
): InstructionData {
|
|
1581
|
+
return async (context) => {
|
|
1582
|
+
assertU64(args.amount, 'amount');
|
|
1583
|
+
const payload = new TokenTransferInstructionBuilder()
|
|
1584
|
+
.set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
|
|
1585
|
+
.set_token_program_idx(accountIndex(context, args.tokenProgramAccountBytes))
|
|
1586
|
+
.set_reserved0([0, 0, 0, 0])
|
|
1587
|
+
.set_amount(args.amount)
|
|
1588
|
+
.set_from_account_idx(accountIndex(context, args.fromAccountBytes))
|
|
1589
|
+
.set_to_account_idx(accountIndex(context, args.toAccountBytes))
|
|
1590
|
+
.set_reserved1([0, 0, 0, 0])
|
|
1591
|
+
.build();
|
|
1592
|
+
return buildPerpInstruction(variant, payload);
|
|
1593
|
+
};
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
function buildPerpInstruction(variant: PerpInstructionVariant, payload: Uint8Array): Uint8Array {
|
|
1597
|
+
const builder = new PerpInstructionBuilder();
|
|
1598
|
+
builder.payload().select(variant).writePayload(payload).finish();
|
|
1599
|
+
return builder.build();
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
function liquidationSideFromValue(value: number): 'long' | 'short' {
|
|
1603
|
+
if (value === 0) return 'long';
|
|
1604
|
+
if (value === 1) return 'short';
|
|
1605
|
+
throw new Error(`unknown perp liquidation side ${value}`);
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1608
|
+
/** Every parser goes through here, so an arena with the market magic but an
|
|
1609
|
+
older, shorter header (whose margin fields decode as nonsense) fails to
|
|
1610
|
+
parse instead of yielding a market nothing can margin against. */
|
|
1611
|
+
function marketFromView(view: MarketAccountView): PerpMarket {
|
|
1612
|
+
return assertPerpMarketHeader({
|
|
1613
|
+
magic: view.get_magic(),
|
|
1614
|
+
statusFlags: view.get_status_flags(),
|
|
1615
|
+
exchangeStatusFlags: view.get_exchange_status_flags(),
|
|
1616
|
+
lotSize: view.get_lot_size(),
|
|
1617
|
+
tickSize: view.get_tick_size(),
|
|
1618
|
+
nextOrderId: view.get_next_order_id(),
|
|
1619
|
+
priceCap: view.get_price_cap(),
|
|
1620
|
+
maxPositionLots: view.get_max_position_lots(),
|
|
1621
|
+
openInterestLots: view.get_open_interest_lots(),
|
|
1622
|
+
badDebt: view.get_bad_debt(),
|
|
1623
|
+
orderArena: pubkeyViewToAddress(view.get_order_entry_pubkey()),
|
|
1624
|
+
bidsCbook: pubkeyViewToAddress(view.get_bids_cbook_pubkey()),
|
|
1625
|
+
asksCbook: pubkeyViewToAddress(view.get_asks_cbook_pubkey()),
|
|
1626
|
+
quoteVault: pubkeyViewToAddress(view.get_quote_vault_pubkey()),
|
|
1627
|
+
marketAuthority: pubkeyViewToAddress(view.get_market_authority_pubkey()),
|
|
1628
|
+
oracleFeed: pubkeyViewToAddress(view.get_oracle_feed_pubkey()),
|
|
1629
|
+
markNum: view.get_mark_num(),
|
|
1630
|
+
markDen: view.get_mark_den(),
|
|
1631
|
+
initialMarginBps: view.get_initial_margin_bps(),
|
|
1632
|
+
maintenanceMarginBps: view.get_maintenance_margin_bps(),
|
|
1633
|
+
liquidationFeeBps: view.get_liquidation_fee_bps(),
|
|
1634
|
+
oracleExponent: view.get_oracle_exponent(),
|
|
1635
|
+
maxMarkAgeNs: view.get_max_mark_age_ns(),
|
|
1636
|
+
});
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
/** 1 <= maintenance < initial <= 10000, liquidationFeeBps <= 10000, markNum and markDen > 0. */
|
|
1640
|
+
function assertPerpMarketHeader(market: PerpMarket): PerpMarket {
|
|
1641
|
+
const { initialMarginBps: initial, maintenanceMarginBps: maintenance, liquidationFeeBps: fee, markNum, markDen } = market;
|
|
1642
|
+
const problem = !(initial >= 1 && initial <= PERP_BPS_DENOMINATOR)
|
|
1643
|
+
? `initialMarginBps ${initial} is not in 1..${PERP_BPS_DENOMINATOR}`
|
|
1644
|
+
: !(maintenance >= 1 && maintenance < initial)
|
|
1645
|
+
? `maintenanceMarginBps ${maintenance} is not in 1..${initial - 1}`
|
|
1646
|
+
: fee > PERP_BPS_DENOMINATOR
|
|
1647
|
+
? `liquidationFeeBps ${fee} is above ${PERP_BPS_DENOMINATOR}`
|
|
1648
|
+
: markDen <= 0n
|
|
1649
|
+
? `markDen ${markDen} is not positive`
|
|
1650
|
+
: markNum <= 0n
|
|
1651
|
+
? `markNum ${markNum} is not positive`
|
|
1652
|
+
: null;
|
|
1653
|
+
if (problem) throw new Error(`perp market header is not a margined market: ${problem}`);
|
|
1654
|
+
return market;
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
|
|
1658
|
+
function arenaHeaderFromView(view: SeatArenaHeader | OrderArenaHeader): PerpArenaHeader {
|
|
1659
|
+
return { nextEntryIndex: view.get_next_entry_idx(), freeMagic: view.get_free_magic() };
|
|
1660
|
+
}
|
|
1661
|
+
|
|
1662
|
+
function seatEntryFromView(view: SeatEntryView, seatIndex: number): PerpSeatEntry {
|
|
1663
|
+
return {
|
|
1664
|
+
seatIndex,
|
|
1665
|
+
seatAuthority: pubkeyViewToAddress(view.get_seat_authority_pubkey()),
|
|
1666
|
+
quantityQuote: view.get_quantity_quote(),
|
|
1667
|
+
longLots: view.get_long_lots(),
|
|
1668
|
+
shortLots: view.get_short_lots(),
|
|
1669
|
+
openBidLots: view.get_open_bid_lots(),
|
|
1670
|
+
openAskLots: view.get_open_ask_lots(),
|
|
1671
|
+
headOrderEntryIndex: view.get_head_order_entry_idx(),
|
|
1672
|
+
entryNotional: view.get_entry_notional(),
|
|
1673
|
+
openBidNotional: view.get_open_bid_notional(),
|
|
1674
|
+
openAskNotional: view.get_open_ask_notional(),
|
|
1675
|
+
};
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
function orderEntryFromView(view: OrderEntryView, orderEntryIndex: number): PerpOrderEntry {
|
|
1679
|
+
const seatPtrs = view.get_seat_ptrs();
|
|
1680
|
+
const levelPtrs = view.get_level_ptrs();
|
|
1681
|
+
return {
|
|
1682
|
+
orderEntryIndex,
|
|
1683
|
+
seatNextOrderEntryIndex: bitField(seatPtrs, 0n, 20n),
|
|
1684
|
+
seatPreviousOrderEntryIndex: bitField(seatPtrs, 20n, 40n),
|
|
1685
|
+
seatIndex: bitField(seatPtrs, 40n, 60n),
|
|
1686
|
+
levelNextOrderEntryIndex: bitField(levelPtrs, 0n, 20n),
|
|
1687
|
+
levelPreviousOrderEntryIndex: bitField(levelPtrs, 20n, 40n),
|
|
1688
|
+
levelIndex: bitField(levelPtrs, 40n, 60n),
|
|
1689
|
+
levelAccountIndex: bitField(levelPtrs, 60n, 64n),
|
|
1690
|
+
quantityInLots: view.get_qty_in_lots(),
|
|
1691
|
+
orderId: view.get_order_id(),
|
|
1692
|
+
clientId: bytesFromView(view.get_client_id()),
|
|
1693
|
+
expirationTime: view.get_expiry(),
|
|
1694
|
+
};
|
|
1695
|
+
}
|
|
1696
|
+
|
|
1697
|
+
function bookOrder(order: PerpOrderEntry, side: PerpOrderSide, cbook: PerpCbook): PerpOrderBookOrder {
|
|
1698
|
+
return {
|
|
1699
|
+
side,
|
|
1700
|
+
priceInTicks: priceForCbookLevel(order.levelIndex, side, cbook),
|
|
1701
|
+
quantityInLots: order.quantityInLots,
|
|
1702
|
+
orderId: order.orderId,
|
|
1703
|
+
orderEntryIndex: order.orderEntryIndex,
|
|
1704
|
+
seatIndex: order.seatIndex,
|
|
1705
|
+
clientId: order.clientId,
|
|
1706
|
+
expirationTime: order.expirationTime,
|
|
1707
|
+
};
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
function priceForCbookLevel(levelIndex: number, side: PerpOrderSide, cbook: PerpCbook): bigint {
|
|
1711
|
+
const levelCount = cbook.levels.length;
|
|
1712
|
+
if (levelCount === 0 || cbook.bestPriceInTicks === PERP_CBOOK_EMPTY_PRICE_IN_TICKS) {
|
|
1713
|
+
throw new Error(`cannot derive perp ${side} price from an empty cbook`);
|
|
1714
|
+
}
|
|
1715
|
+
if (!Number.isInteger(levelIndex) || levelIndex < 0 || levelIndex >= levelCount) {
|
|
1716
|
+
throw new Error(`perp ${side} level index ${levelIndex} is outside cbook level count ${levelCount}`);
|
|
1717
|
+
}
|
|
1718
|
+
const distance = levelIndex >= cbook.bestLevelIndex
|
|
1719
|
+
? levelIndex - cbook.bestLevelIndex
|
|
1720
|
+
: levelCount - cbook.bestLevelIndex + levelIndex;
|
|
1721
|
+
const cbookPriceInTicks = cbook.bestPriceInTicks + BigInt(distance);
|
|
1722
|
+
return side === 'buy' ? PERP_CBOOK_MAX_PRICE_IN_TICKS - cbookPriceInTicks : cbookPriceInTicks;
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
function u64le(value: bigint): Uint8Array {
|
|
1726
|
+
assertU64(value, 'value');
|
|
1727
|
+
const bytes = new Uint8Array(8);
|
|
1728
|
+
new DataView(bytes.buffer).setBigUint64(0, value, true);
|
|
1729
|
+
return bytes;
|
|
1730
|
+
}
|
|
1731
|
+
|
|
1732
|
+
function u16le(value: number): Uint8Array {
|
|
1733
|
+
assertU16(value, 'value');
|
|
1734
|
+
const bytes = new Uint8Array(2);
|
|
1735
|
+
new DataView(bytes.buffer).setUint16(0, value, true);
|
|
1736
|
+
return bytes;
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
|
|
1740
|
+
function ceilDiv(numerator: bigint, denominator: bigint): bigint {
|
|
1741
|
+
if (denominator <= 0n) throw new Error('division by a non-positive denominator');
|
|
1742
|
+
if (numerator <= 0n) return -((-numerator) / denominator);
|
|
1743
|
+
return (numerator + denominator - 1n) / denominator;
|
|
1744
|
+
}
|
|
1745
|
+
|
|
1746
|
+
function maxBig(a: bigint, b: bigint): bigint {
|
|
1747
|
+
return a > b ? a : b;
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
function assertBps(value: number, label: string): number {
|
|
1751
|
+
if (!Number.isInteger(value) || value < 0 || value > Number(PERP_BPS_DENOMINATOR)) {
|
|
1752
|
+
throw new Error(`${label} must be an integer between 0 and ${PERP_BPS_DENOMINATOR}`);
|
|
1753
|
+
}
|
|
1754
|
+
return value;
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
/** 1 <= maintenance < initial <= 10000, liquidation fee <= 10000 (market create validation). */
|
|
1758
|
+
function assertMarginParams(params: PerpMarginParams): void {
|
|
1759
|
+
assertBps(params.initialMarginBps, 'initialMarginBps');
|
|
1760
|
+
assertBps(params.maintenanceMarginBps, 'maintenanceMarginBps');
|
|
1761
|
+
assertBps(params.liquidationFeeBps, 'liquidationFeeBps');
|
|
1762
|
+
if (params.maintenanceMarginBps < 1 || params.maintenanceMarginBps >= params.initialMarginBps) {
|
|
1763
|
+
throw new Error('maintenanceMarginBps must satisfy 1 <= maintenance < initialMarginBps');
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
function assertOracleParams(params: PerpOracleParams): void {
|
|
1768
|
+
assertU64(params.markNum, 'markNum');
|
|
1769
|
+
assertU64(params.markDen, 'markDen');
|
|
1770
|
+
if (params.markNum === 0n) throw new Error('markNum must be positive');
|
|
1771
|
+
if (params.markDen === 0n) throw new Error('markDen must be positive');
|
|
1772
|
+
assertU64(params.maxMarkAgeNs, 'maxMarkAgeNs');
|
|
1773
|
+
if (!Number.isInteger(params.oracleExponent) || params.oracleExponent < -0x80000000 || params.oracleExponent > 0x7fffffff) {
|
|
1774
|
+
throw new Error('oracleExponent must be a 32-bit integer');
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
async function sha256(...parts: Uint8Array[]): Promise<Uint8Array> {
|
|
1779
|
+
const size = parts.reduce((total, part) => total + part.length, 0);
|
|
1780
|
+
const joined = new Uint8Array(size);
|
|
1781
|
+
let offset = 0;
|
|
1782
|
+
for (const part of parts) {
|
|
1783
|
+
joined.set(part, offset);
|
|
1784
|
+
offset += part.length;
|
|
1785
|
+
}
|
|
1786
|
+
const digest = await globalThis.crypto.subtle.digest('SHA-256', joined);
|
|
1787
|
+
return new Uint8Array(digest);
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
function minBig(a: bigint, b: bigint): bigint {
|
|
1791
|
+
return a < b ? a : b;
|
|
1792
|
+
}
|
|
1793
|
+
|