@thru/programs 0.3.16 → 0.3.18
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/dist/abi-manager/index.cjs +1 -1
- package/dist/abi-manager/index.cjs.map +1 -1
- package/dist/abi-manager/index.js +2 -2
- package/dist/amm/index.cjs +235 -28
- package/dist/amm/index.cjs.map +1 -1
- package/dist/amm/index.d.cts +34 -6
- package/dist/amm/index.d.ts +34 -6
- package/dist/amm/index.js +238 -31
- package/dist/amm/index.js.map +1 -1
- package/dist/bootstrap-addresses/index.cjs.map +1 -1
- package/dist/bootstrap-addresses/index.js +3 -3
- package/dist/chunk-4F54VFIH.js +58 -0
- package/dist/chunk-4F54VFIH.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-VNTPD4AR.js → chunk-FHYZQ5R3.js} +3 -3
- package/dist/{chunk-VNTPD4AR.js.map → chunk-FHYZQ5R3.js.map} +1 -1
- package/dist/{chunk-BNYDH4ZP.js → chunk-FQDO6J6E.js} +3 -3
- package/dist/{chunk-BNYDH4ZP.js.map → chunk-FQDO6J6E.js.map} +1 -1
- package/dist/{chunk-ZHF2PH5H.js → chunk-IGZZOZ73.js} +4 -4
- package/dist/{chunk-ZHF2PH5H.js.map → chunk-IGZZOZ73.js.map} +1 -1
- package/dist/{chunk-CYG4PB65.js → chunk-NMPO53TW.js} +4 -4
- package/dist/{chunk-CYG4PB65.js.map → chunk-NMPO53TW.js.map} +1 -1
- package/dist/{chunk-7DHFYBRW.js → chunk-O2ONVSHW.js} +3 -3
- package/dist/{chunk-7DHFYBRW.js.map → chunk-O2ONVSHW.js.map} +1 -1
- package/dist/{chunk-YX7BLFQZ.js → chunk-PRU4KGQO.js} +3 -3
- package/dist/chunk-PRU4KGQO.js.map +1 -0
- package/dist/chunk-Q6762F4G.js +174 -0
- package/dist/chunk-Q6762F4G.js.map +1 -0
- package/dist/{chunk-6IC6CO5S.js → chunk-UPB725FV.js} +3 -3
- package/dist/{chunk-6IC6CO5S.js.map → chunk-UPB725FV.js.map} +1 -1
- package/dist/clob/index.cjs +328 -304
- 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 +37 -198
- package/dist/clob/index.js.map +1 -1
- package/dist/deploy/index.cjs +1 -1
- package/dist/deploy/index.cjs.map +1 -1
- package/dist/deploy/index.js +7 -7
- package/dist/manager/index.cjs +1 -1
- package/dist/manager/index.cjs.map +1 -1
- package/dist/manager/index.d.cts +2 -79
- package/dist/manager/index.d.ts +2 -79
- package/dist/manager/index.js +3 -3
- package/dist/multicall/index.cjs.map +1 -1
- package/dist/multicall/index.js +4 -4
- 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 +3 -3
- package/dist/orderbook-CEYM4N_S.d.cts +5 -0
- package/dist/orderbook-CEYM4N_S.d.ts +5 -0
- package/dist/passkey-manager/index.cjs.map +1 -1
- package/dist/passkey-manager/index.js +3 -3
- package/dist/perp/index.cjs +16740 -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 +16245 -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 +1 -1
- package/dist/uploader/index.cjs.map +1 -1
- package/dist/uploader/index.js +2 -2
- package/package.json +7 -2
- package/src/amm/abi/thru/program/amm/types.ts +282 -23
- package/src/amm/index.test.ts +93 -3
- package/src/amm/index.ts +18 -1
- package/src/clob/index.ts +67 -201
- 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/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-7DRJVAYI.js.map +0 -1
- package/dist/chunk-YX7BLFQZ.js.map +0 -1
|
@@ -0,0 +1,822 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
import { Pubkey, deriveAddress, deriveProgramAddress } from '@thru/sdk';
|
|
4
|
+
import type { Thru } from '@thru/sdk/client';
|
|
5
|
+
import { BOOTSTRAP_PROGRAM_ADDRESSES } from '../bootstrap-addresses';
|
|
6
|
+
import type { OracleFeed } from '../oracle/types';
|
|
7
|
+
import {
|
|
8
|
+
PERP_BPS_DENOMINATOR,
|
|
9
|
+
PERP_DEFAULT_MARKET_RECORD_INDEX,
|
|
10
|
+
PERP_EVENT_LIQUIDATION,
|
|
11
|
+
PERP_INSTRUCTION_LIQUIDATE,
|
|
12
|
+
PERP_INSTRUCTION_MARKET_CREATE,
|
|
13
|
+
PERP_INSTRUCTION_MARKET_RECORD,
|
|
14
|
+
PERP_INSTRUCTION_MARKET_SET_ORACLE,
|
|
15
|
+
PERP_MARKET_ACCOUNT_SIZE,
|
|
16
|
+
PERP_MARKET_MAGIC,
|
|
17
|
+
PERP_NULL_ACCOUNT_INDEX,
|
|
18
|
+
PERP_ORDER_ARENA_ENTRIES_OFFSET,
|
|
19
|
+
PERP_ORDER_ENTRY_SIZE,
|
|
20
|
+
PERP_PROGRAM_ADDRESS,
|
|
21
|
+
PERP_SEAT_ARENA_ENTRIES_OFFSET,
|
|
22
|
+
PERP_SEAT_ENTRY_SIZE,
|
|
23
|
+
PERP_SEAT_MANAGER_RESERVED_SIZE,
|
|
24
|
+
createPerpLiquidateInstruction,
|
|
25
|
+
createPerpMarketCreateInstruction,
|
|
26
|
+
createPerpMarketRecordInstruction,
|
|
27
|
+
createPerpMarketSetOracleInstruction,
|
|
28
|
+
derivePerpMarketAccounts,
|
|
29
|
+
parsePerpEvent,
|
|
30
|
+
parsePerpMarketAccount,
|
|
31
|
+
parsePerpOrderArenaAccount,
|
|
32
|
+
parsePerpSeatArenaAccount,
|
|
33
|
+
perpAverageEntryPrice,
|
|
34
|
+
perpBankruptcyPrice,
|
|
35
|
+
perpCanPostOrder,
|
|
36
|
+
perpEquity,
|
|
37
|
+
perpFreeCollateral,
|
|
38
|
+
perpInitialMargin,
|
|
39
|
+
perpIsLiquidatable,
|
|
40
|
+
perpLeverageBps,
|
|
41
|
+
perpLiquidationPreview,
|
|
42
|
+
perpLiquidationPrice,
|
|
43
|
+
perpMaintenanceMargin,
|
|
44
|
+
perpMarkFraction,
|
|
45
|
+
perpMarkFromFeed,
|
|
46
|
+
perpMarkPrice,
|
|
47
|
+
perpMarketAccountAddresses,
|
|
48
|
+
perpMarketReadOnlyAddresses,
|
|
49
|
+
perpMaxBuyLots,
|
|
50
|
+
perpMaxLeverage,
|
|
51
|
+
perpMaxSellLots,
|
|
52
|
+
perpNotional,
|
|
53
|
+
perpOrderInitialMargin,
|
|
54
|
+
perpCeilBps,
|
|
55
|
+
perpSeatOrders,
|
|
56
|
+
perpSideMarginNotional,
|
|
57
|
+
perpUnrealizedPnl,
|
|
58
|
+
type PerpMarginSeat,
|
|
59
|
+
type PerpMarket,
|
|
60
|
+
type PerpSeatEntry,
|
|
61
|
+
} from './index';
|
|
62
|
+
|
|
63
|
+
/* Fixtures ******************************************************************/
|
|
64
|
+
|
|
65
|
+
const thru = { helpers: { deriveAddress, deriveProgramAddress } } as unknown as Thru;
|
|
66
|
+
|
|
67
|
+
function key(id: number): Uint8Array {
|
|
68
|
+
const bytes = new Uint8Array(32);
|
|
69
|
+
bytes[0] = id;
|
|
70
|
+
bytes[31] = 0xa0 + id;
|
|
71
|
+
return bytes;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function address(id: number): string {
|
|
75
|
+
return Pubkey.from(key(id)).toThruFmt();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function context(indexes: Array<[Uint8Array, number]>) {
|
|
79
|
+
return {
|
|
80
|
+
getAccountIndex(pubkey: Uint8Array): number {
|
|
81
|
+
for (const [candidate, index] of indexes) {
|
|
82
|
+
if (candidate.length === pubkey.length && candidate.every((byte, i) => byte === pubkey[i])) return index;
|
|
83
|
+
}
|
|
84
|
+
throw new Error('missing account');
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Writes the 320 byte market_t at its documented offsets. */
|
|
90
|
+
|
|
91
|
+
function marketBytes(): Uint8Array {
|
|
92
|
+
const data = new Uint8Array(PERP_MARKET_ACCOUNT_SIZE);
|
|
93
|
+
const view = new DataView(data.buffer);
|
|
94
|
+
data[0] = PERP_MARKET_MAGIC;
|
|
95
|
+
data[1] = 0x02; /* status_flags: post only */
|
|
96
|
+
data[2] = 0x01; /* exchange_status_flags: paused */
|
|
97
|
+
view.setBigUint64(8, 1n, true); /* lot_size */
|
|
98
|
+
view.setBigUint64(16, 1_000n, true); /* tick_size */
|
|
99
|
+
view.setBigUint64(24, 77n, true); /* next_order_id */
|
|
100
|
+
view.setBigUint64(32, 200_000_000n, true); /* price_cap */
|
|
101
|
+
view.setBigUint64(40, 1_000_000n, true); /* max_position_lots */
|
|
102
|
+
view.setBigUint64(48, 10n, true); /* open_interest_lots */
|
|
103
|
+
view.setBigUint64(56, 123n, true); /* bad_debt */
|
|
104
|
+
data.set(key(1), 64); /* order_entry_pubkey */
|
|
105
|
+
data.set(key(2), 96); /* bids_cbook_pubkey */
|
|
106
|
+
data.set(key(3), 128); /* asks_cbook_pubkey */
|
|
107
|
+
data.set(key(4), 160); /* quote_vault_pubkey */
|
|
108
|
+
data.set(key(5), 192); /* market_authority_pubkey */
|
|
109
|
+
data.set(key(6), 224); /* oracle_feed_pubkey */
|
|
110
|
+
view.setBigUint64(256, 100_000n, true); /* mark_num */
|
|
111
|
+
view.setBigUint64(264, 1n, true); /* mark_den */
|
|
112
|
+
view.setUint32(272, 250, true); /* initial_margin_bps */
|
|
113
|
+
view.setUint32(276, 125, true); /* maintenance_margin_bps */
|
|
114
|
+
view.setUint32(280, 100, true); /* liquidation_fee_bps */
|
|
115
|
+
view.setInt32(284, -8, true); /* oracle_exponent */
|
|
116
|
+
view.setBigUint64(288, 60_000_000_000n, true); /* max_mark_age_ns */
|
|
117
|
+
return data;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Writes a seat_entry_t at its documented offsets. */
|
|
121
|
+
function seatBytes(seat: {
|
|
122
|
+
authority: Uint8Array;
|
|
123
|
+
quantityQuote: bigint;
|
|
124
|
+
longLots: bigint;
|
|
125
|
+
shortLots: bigint;
|
|
126
|
+
openBidLots: bigint;
|
|
127
|
+
openAskLots: bigint;
|
|
128
|
+
headOrderEntryIndex: number;
|
|
129
|
+
entryNotional: bigint;
|
|
130
|
+
openBidNotional: bigint;
|
|
131
|
+
openAskNotional: bigint;
|
|
132
|
+
active: boolean;
|
|
133
|
+
}): Uint8Array {
|
|
134
|
+
const data = new Uint8Array(PERP_SEAT_ENTRY_SIZE);
|
|
135
|
+
const view = new DataView(data.buffer);
|
|
136
|
+
data.set(seat.authority, 0);
|
|
137
|
+
view.setBigUint64(32, seat.quantityQuote, true);
|
|
138
|
+
view.setBigUint64(40, seat.longLots, true);
|
|
139
|
+
view.setBigUint64(48, seat.shortLots, true);
|
|
140
|
+
view.setBigUint64(56, seat.openBidLots, true);
|
|
141
|
+
view.setBigUint64(64, seat.openAskLots, true);
|
|
142
|
+
view.setUint32(72, seat.headOrderEntryIndex, true);
|
|
143
|
+
view.setBigUint64(80, seat.entryNotional, true);
|
|
144
|
+
view.setBigUint64(88, seat.openBidNotional, true);
|
|
145
|
+
view.setBigUint64(96, seat.openAskNotional, true);
|
|
146
|
+
view.setBigUint64(120, seat.active ? 1n : 0n, true); /* non_nullable_reserved */
|
|
147
|
+
return data;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function seatArenaBytes(seats: Uint8Array[]): Uint8Array {
|
|
151
|
+
const data = new Uint8Array(PERP_SEAT_ARENA_ENTRIES_OFFSET + seats.length * PERP_SEAT_ENTRY_SIZE);
|
|
152
|
+
data.set(marketBytes(), 0);
|
|
153
|
+
const view = new DataView(data.buffer);
|
|
154
|
+
/* Arena header entry at SEATS_MANAGER_RESERVED_SIZE: reserved0[116], next_entry_idx u32, free_magic u64 */
|
|
155
|
+
view.setUint32(PERP_SEAT_MANAGER_RESERVED_SIZE + 116, seats.length + 1, true);
|
|
156
|
+
view.setBigUint64(PERP_SEAT_MANAGER_RESERVED_SIZE + 120, 0n, true);
|
|
157
|
+
seats.forEach((seat, index) => data.set(seat, PERP_SEAT_ARENA_ENTRIES_OFFSET + index * PERP_SEAT_ENTRY_SIZE));
|
|
158
|
+
return data;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Writes an order_entry_t at its documented offsets; expiry 0 = free slot. */
|
|
162
|
+
function orderBytes(order: {
|
|
163
|
+
seatNext: number;
|
|
164
|
+
seatPrev: number;
|
|
165
|
+
seatIndex: number;
|
|
166
|
+
levelIndex: number;
|
|
167
|
+
levelAccountIndex: number;
|
|
168
|
+
quantityInLots: bigint;
|
|
169
|
+
orderId: bigint;
|
|
170
|
+
expiry: bigint;
|
|
171
|
+
}): Uint8Array {
|
|
172
|
+
const data = new Uint8Array(PERP_ORDER_ENTRY_SIZE);
|
|
173
|
+
const view = new DataView(data.buffer);
|
|
174
|
+
const seatPtrs = BigInt(order.seatNext) | (BigInt(order.seatPrev) << 20n) | (BigInt(order.seatIndex) << 40n);
|
|
175
|
+
const levelPtrs = (BigInt(order.levelIndex) << 40n) | (BigInt(order.levelAccountIndex) << 60n);
|
|
176
|
+
view.setBigUint64(0, seatPtrs, true);
|
|
177
|
+
view.setBigUint64(8, levelPtrs, true);
|
|
178
|
+
view.setBigUint64(16, order.quantityInLots, true);
|
|
179
|
+
view.setBigUint64(24, order.orderId, true);
|
|
180
|
+
data.fill(order.orderId === 0n ? 0 : Number(order.orderId & 0xffn), 40, 56); /* client_id */
|
|
181
|
+
view.setBigInt64(56, order.expiry, true);
|
|
182
|
+
return data;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function orderArenaBytes(orders: Uint8Array[]): Uint8Array {
|
|
186
|
+
const data = new Uint8Array(PERP_ORDER_ARENA_ENTRIES_OFFSET + orders.length * PERP_ORDER_ENTRY_SIZE);
|
|
187
|
+
const view = new DataView(data.buffer);
|
|
188
|
+
/* 8 reserved bytes, then the header: reserved0[52], next_entry_idx u32, free_magic u64 */
|
|
189
|
+
view.setUint32(8 + 52, orders.length + 1, true);
|
|
190
|
+
view.setBigUint64(8 + 56, 0n, true);
|
|
191
|
+
orders.forEach((order, index) => data.set(order, PERP_ORDER_ARENA_ENTRIES_OFFSET + index * PERP_ORDER_ENTRY_SIZE));
|
|
192
|
+
return data;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const FREE_ORDER = orderBytes({ seatNext: 0, seatPrev: 0, seatIndex: 0, levelIndex: 0, levelAccountIndex: 0, quantityInLots: 0n, orderId: 0n, expiry: 0n });
|
|
196
|
+
|
|
197
|
+
/* Worked example: 20x market (IM 500 bps, MM 250 bps), long 10 lots bought
|
|
198
|
+
at 85,000,000 atoms with 50,000,000 atoms of collateral. */
|
|
199
|
+
const MARKET: PerpMarket = {
|
|
200
|
+
magic: PERP_MARKET_MAGIC,
|
|
201
|
+
statusFlags: 0,
|
|
202
|
+
exchangeStatusFlags: 0,
|
|
203
|
+
lotSize: 1n,
|
|
204
|
+
tickSize: 1_000n,
|
|
205
|
+
nextOrderId: 1n,
|
|
206
|
+
priceCap: 200_000_000n,
|
|
207
|
+
maxPositionLots: 1_000_000n,
|
|
208
|
+
openInterestLots: 10n,
|
|
209
|
+
badDebt: 0n,
|
|
210
|
+
orderArena: address(1),
|
|
211
|
+
bidsCbook: address(2),
|
|
212
|
+
asksCbook: address(3),
|
|
213
|
+
quoteVault: address(4),
|
|
214
|
+
marketAuthority: address(5),
|
|
215
|
+
oracleFeed: address(6),
|
|
216
|
+
markNum: 1_000n,
|
|
217
|
+
markDen: 1n,
|
|
218
|
+
initialMarginBps: 500,
|
|
219
|
+
maintenanceMarginBps: 250,
|
|
220
|
+
liquidationFeeBps: 100,
|
|
221
|
+
oracleExponent: -8,
|
|
222
|
+
maxMarkAgeNs: 0n,
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const ENTRY = 85_000_000n;
|
|
226
|
+
const LOTS = 10n;
|
|
227
|
+
const COLLATERAL = 50_000_000n;
|
|
228
|
+
|
|
229
|
+
function seat(overrides: Partial<PerpMarginSeat> = {}): PerpMarginSeat {
|
|
230
|
+
return {
|
|
231
|
+
quantityQuote: COLLATERAL,
|
|
232
|
+
longLots: LOTS,
|
|
233
|
+
shortLots: 0n,
|
|
234
|
+
openBidLots: 0n,
|
|
235
|
+
openAskLots: 0n,
|
|
236
|
+
entryNotional: LOTS * ENTRY,
|
|
237
|
+
openBidNotional: 0n,
|
|
238
|
+
openAskNotional: 0n,
|
|
239
|
+
...overrides,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const shortSeat = (overrides: Partial<PerpMarginSeat> = {}) => seat({ longLots: 0n, shortLots: LOTS, ...overrides });
|
|
244
|
+
|
|
245
|
+
const ceilBps = (amount: bigint, bps: bigint) => (amount * bps + PERP_BPS_DENOMINATOR - 1n) / PERP_BPS_DENOMINATOR;
|
|
246
|
+
const minLots = (a: bigint, b: bigint) => (a < b ? a : b);
|
|
247
|
+
|
|
248
|
+
/* Tests *********************************************************************/
|
|
249
|
+
|
|
250
|
+
describe('perp account parsers', () => {
|
|
251
|
+
it('parses the 320 byte market account', () => {
|
|
252
|
+
const market = parsePerpMarketAccount(marketBytes());
|
|
253
|
+
expect(market).toEqual<PerpMarket>({
|
|
254
|
+
magic: PERP_MARKET_MAGIC,
|
|
255
|
+
statusFlags: 2,
|
|
256
|
+
exchangeStatusFlags: 1,
|
|
257
|
+
lotSize: 1n,
|
|
258
|
+
tickSize: 1_000n,
|
|
259
|
+
nextOrderId: 77n,
|
|
260
|
+
priceCap: 200_000_000n,
|
|
261
|
+
maxPositionLots: 1_000_000n,
|
|
262
|
+
openInterestLots: 10n,
|
|
263
|
+
badDebt: 123n,
|
|
264
|
+
orderArena: address(1),
|
|
265
|
+
bidsCbook: address(2),
|
|
266
|
+
asksCbook: address(3),
|
|
267
|
+
quoteVault: address(4),
|
|
268
|
+
marketAuthority: address(5),
|
|
269
|
+
oracleFeed: address(6),
|
|
270
|
+
markNum: 100_000n,
|
|
271
|
+
markDen: 1n,
|
|
272
|
+
initialMarginBps: 250,
|
|
273
|
+
maintenanceMarginBps: 125,
|
|
274
|
+
liquidationFeeBps: 100,
|
|
275
|
+
oracleExponent: -8,
|
|
276
|
+
maxMarkAgeNs: 60_000_000_000n,
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
it('rejects a short (224 byte) market', () => {
|
|
281
|
+
expect(() => parsePerpMarketAccount(marketBytes().subarray(0, 224))).toThrow(/320 bytes/);
|
|
282
|
+
expect(() => parsePerpMarketAccount(new Uint8Array(320))).toThrow(/not a perp market/);
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
it('rejects a header whose margin fields are not a margined market', () => {
|
|
286
|
+
const withHeader = (patch: (view: DataView) => void) => {
|
|
287
|
+
const data = marketBytes();
|
|
288
|
+
patch(new DataView(data.buffer));
|
|
289
|
+
return data;
|
|
290
|
+
};
|
|
291
|
+
expect(() => parsePerpMarketAccount(withHeader((view) => view.setUint32(272, 0, true)))).toThrow(/initialMarginBps 0/);
|
|
292
|
+
expect(() => parsePerpMarketAccount(withHeader((view) => view.setUint32(272, 10_001, true)))).toThrow(/initialMarginBps 10001/);
|
|
293
|
+
expect(() => parsePerpMarketAccount(withHeader((view) => view.setUint32(276, 250, true)))).toThrow(/maintenanceMarginBps 250 is not in 1\.\.249/);
|
|
294
|
+
expect(() => parsePerpMarketAccount(withHeader((view) => view.setUint32(276, 0, true)))).toThrow(/maintenanceMarginBps 0/);
|
|
295
|
+
expect(() => parsePerpMarketAccount(withHeader((view) => view.setUint32(280, 10_001, true)))).toThrow(/liquidationFeeBps 10001/);
|
|
296
|
+
expect(() => parsePerpMarketAccount(withHeader((view) => view.setBigUint64(256, 0n, true)))).toThrow(/markNum 0/);
|
|
297
|
+
expect(() => parsePerpMarketAccount(withHeader((view) => view.setBigUint64(264, 0n, true)))).toThrow(/markDen 0/);
|
|
298
|
+
/* the boundary values pass */
|
|
299
|
+
expect(parsePerpMarketAccount(withHeader((view) => {
|
|
300
|
+
view.setUint32(272, 10_000, true);
|
|
301
|
+
view.setUint32(276, 9_999, true);
|
|
302
|
+
view.setUint32(280, 10_000, true);
|
|
303
|
+
})).initialMarginBps).toBe(10_000);
|
|
304
|
+
/* an arena with the market magic but a header without margin fields is rejected too */
|
|
305
|
+
const legacy = seatArenaBytes([]);
|
|
306
|
+
legacy.fill(0, 256, PERP_MARKET_ACCOUNT_SIZE);
|
|
307
|
+
expect(() => parsePerpSeatArenaAccount(legacy)).toThrow(/not a margined market/);
|
|
308
|
+
expect(() => parsePerpMarketAccount(legacy)).toThrow(/not a margined market/);
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
it('parses seats starting at byte 640 of the arena with the notional fields', () => {
|
|
313
|
+
expect(PERP_SEAT_MANAGER_RESERVED_SIZE).toBe(512);
|
|
314
|
+
expect(PERP_SEAT_ARENA_ENTRIES_OFFSET).toBe(640);
|
|
315
|
+
const arena = parsePerpSeatArenaAccount(
|
|
316
|
+
seatArenaBytes([
|
|
317
|
+
seatBytes({
|
|
318
|
+
authority: key(10),
|
|
319
|
+
quantityQuote: 50_000_000n,
|
|
320
|
+
longLots: 10n,
|
|
321
|
+
shortLots: 0n,
|
|
322
|
+
openBidLots: 2n,
|
|
323
|
+
openAskLots: 3n,
|
|
324
|
+
headOrderEntryIndex: 7,
|
|
325
|
+
entryNotional: 850_000_000n,
|
|
326
|
+
openBidNotional: 168_000_000n,
|
|
327
|
+
openAskNotional: 258_000_000n,
|
|
328
|
+
active: true,
|
|
329
|
+
}),
|
|
330
|
+
seatBytes({
|
|
331
|
+
authority: key(11),
|
|
332
|
+
quantityQuote: 0n,
|
|
333
|
+
longLots: 0n,
|
|
334
|
+
shortLots: 0n,
|
|
335
|
+
openBidLots: 0n,
|
|
336
|
+
openAskLots: 0n,
|
|
337
|
+
headOrderEntryIndex: 0,
|
|
338
|
+
entryNotional: 0n,
|
|
339
|
+
openBidNotional: 0n,
|
|
340
|
+
openAskNotional: 0n,
|
|
341
|
+
active: false,
|
|
342
|
+
}),
|
|
343
|
+
]),
|
|
344
|
+
);
|
|
345
|
+
expect(arena.market.oracleFeed).toBe(address(6));
|
|
346
|
+
expect(arena.header.nextEntryIndex).toBe(3);
|
|
347
|
+
/* slots is sparse: the free seat is a hole, not a decoded entry */
|
|
348
|
+
expect(arena.slots.length).toBe(2);
|
|
349
|
+
expect(0 in arena.slots).toBe(true);
|
|
350
|
+
expect(1 in arena.slots).toBe(false);
|
|
351
|
+
expect(arena.slots[0]).toEqual({ index: 1, active: true, entry: arena.seats[0] });
|
|
352
|
+
expect(arena.slots[1]).toBeUndefined();
|
|
353
|
+
expect(arena.slots.map((slot) => slot?.index)).toEqual([1, undefined]);
|
|
354
|
+
expect(arena.seats).toEqual<PerpSeatEntry[]>([
|
|
355
|
+
{
|
|
356
|
+
seatIndex: 1,
|
|
357
|
+
seatAuthority: address(10),
|
|
358
|
+
quantityQuote: 50_000_000n,
|
|
359
|
+
longLots: 10n,
|
|
360
|
+
shortLots: 0n,
|
|
361
|
+
openBidLots: 2n,
|
|
362
|
+
openAskLots: 3n,
|
|
363
|
+
headOrderEntryIndex: 7,
|
|
364
|
+
entryNotional: 850_000_000n,
|
|
365
|
+
openBidNotional: 168_000_000n,
|
|
366
|
+
openAskNotional: 258_000_000n,
|
|
367
|
+
},
|
|
368
|
+
]);
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
it('decodes active order slots only and keeps arena indexes for the seat list walk', () => {
|
|
372
|
+
expect(PERP_ORDER_ARENA_ENTRIES_OFFSET).toBe(72);
|
|
373
|
+
const arena = parsePerpOrderArenaAccount(
|
|
374
|
+
orderArenaBytes([
|
|
375
|
+
FREE_ORDER, /* slot 1 */
|
|
376
|
+
orderBytes({ seatNext: 4, seatPrev: 0, seatIndex: 1, levelIndex: 3, levelAccountIndex: 0, quantityInLots: 5n, orderId: 11n, expiry: 9_000n }), /* slot 2 */
|
|
377
|
+
FREE_ORDER, /* slot 3 */
|
|
378
|
+
orderBytes({ seatNext: 0, seatPrev: 2, seatIndex: 1, levelIndex: 7, levelAccountIndex: 1, quantityInLots: 6n, orderId: 12n, expiry: 9_000n }), /* slot 4 */
|
|
379
|
+
orderBytes({ seatNext: 0, seatPrev: 0, seatIndex: 2, levelIndex: 1, levelAccountIndex: 0, quantityInLots: 7n, orderId: 13n, expiry: -1n }), /* slot 5 */
|
|
380
|
+
]),
|
|
381
|
+
);
|
|
382
|
+
expect(arena.header.nextEntryIndex).toBe(6);
|
|
383
|
+
expect(arena.slots.length).toBe(5);
|
|
384
|
+
expect([0, 1, 2, 3, 4].map((idx) => idx in arena.slots)).toEqual([false, true, false, true, true]);
|
|
385
|
+
expect(arena.orders.map((order) => order.orderEntryIndex)).toEqual([2, 4, 5]);
|
|
386
|
+
expect(arena.orders[0]).toMatchObject({
|
|
387
|
+
orderEntryIndex: 2,
|
|
388
|
+
seatNextOrderEntryIndex: 4,
|
|
389
|
+
seatPreviousOrderEntryIndex: 0,
|
|
390
|
+
seatIndex: 1,
|
|
391
|
+
levelIndex: 3,
|
|
392
|
+
levelAccountIndex: 0,
|
|
393
|
+
quantityInLots: 5n,
|
|
394
|
+
orderId: 11n,
|
|
395
|
+
expirationTime: 9_000n,
|
|
396
|
+
});
|
|
397
|
+
expect(arena.orders[1].clientId).toEqual(new Uint8Array(16).fill(12));
|
|
398
|
+
expect(arena.orders[2].expirationTime).toBe(-1n);
|
|
399
|
+
expect(arena.slots[3]!.entry).toBe(arena.orders[1]);
|
|
400
|
+
const seat = { headOrderEntryIndex: 2 } as PerpSeatEntry;
|
|
401
|
+
expect(perpSeatOrders(seat, arena).map((order) => order.orderEntryIndex)).toEqual([2, 4]);
|
|
402
|
+
expect(perpSeatOrders({ headOrderEntryIndex: 5 } as PerpSeatEntry, arena).map((order) => order.orderId)).toEqual([13n]);
|
|
403
|
+
/* a head pointing at a free slot or past the arena yields nothing */
|
|
404
|
+
expect(perpSeatOrders({ headOrderEntryIndex: 3 } as PerpSeatEntry, arena)).toEqual([]);
|
|
405
|
+
expect(perpSeatOrders({ headOrderEntryIndex: 9 } as PerpSeatEntry, arena)).toEqual([]);
|
|
406
|
+
expect(perpSeatOrders({ headOrderEntryIndex: 0 } as PerpSeatEntry, arena)).toEqual([]);
|
|
407
|
+
});
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
describe('perp margin math', () => {
|
|
412
|
+
it('computes the mark from the feed price', () => {
|
|
413
|
+
expect(perpMarkPrice(8_500_000_000_000n, { priceCap: 200_000_000n, markNum: 1n, markDen: 100_000n })).toBe(85_000_000n);
|
|
414
|
+
expect(perpMarkPrice(85_000n, { priceCap: 200_000_000n, markNum: 1_000n, markDen: 1n })).toBe(85_000_000n);
|
|
415
|
+
/* clamped to the cap */
|
|
416
|
+
expect(perpMarkPrice(300_000n, { priceCap: 200_000_000n, markNum: 1_000n, markDen: 1n })).toBe(200_000_000n);
|
|
417
|
+
expect(() => perpMarkPrice(1n, { priceCap: 200_000_000n, markNum: 1n, markDen: 1_000n })).toThrow(/zero/);
|
|
418
|
+
expect(() => perpMarkPrice(1n, { priceCap: 200_000_000n, markNum: 0n, markDen: 1n })).toThrow(/markNum/);
|
|
419
|
+
expect(() => perpMarkPrice(1n, { priceCap: 200_000_000n, markNum: 1n, markDen: 0n })).toThrow(/markDen/);
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
it('takes the mark from a price feed with the market exponent only', () => {
|
|
423
|
+
const common = { maxStalenessNs: 0n, lastUpdateNs: 0n, adminAddress: address(1), reporterAddress: address(2), feedName: 'BTC/USD' };
|
|
424
|
+
const feed: OracleFeed = { kind: 'price', common, price: 85_000n, maxVarianceBps: 0, exponent: -8 };
|
|
425
|
+
expect(perpMarkFromFeed(feed, MARKET)).toBe(85_000_000n);
|
|
426
|
+
expect(() => perpMarkFromFeed({ ...feed, exponent: -6 }, MARKET)).toThrow(/"BTC\/USD" exponent -6 differs from the market's -8/);
|
|
427
|
+
expect(() => perpMarkFromFeed({ kind: 'boolean', common, value: true }, MARKET)).toThrow(/boolean feed, not a price feed/);
|
|
428
|
+
expect(() => perpMarkFromFeed({ ...feed, price: 0n }, MARKET)).toThrow(/zero/);
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
it('mark fraction is 10^(quoteDecimals - baseDecimals + exponent) as an integer fraction', () => {
|
|
432
|
+
/* USDC (6) / BTC lots of 0.001 (3) with a -8 feed: 10^-5 */
|
|
433
|
+
expect(perpMarkFraction(6, 3, -8)).toEqual({ markNum: 1n, markDen: 100_000n });
|
|
434
|
+
expect(perpMarkFraction(9, 3, -6)).toEqual({ markNum: 1n, markDen: 1n });
|
|
435
|
+
expect(perpMarkFraction(9, 0, -6)).toEqual({ markNum: 1_000n, markDen: 1n });
|
|
436
|
+
expect(perpMarkFraction(6, 3, 0)).toEqual({ markNum: 1_000n, markDen: 1n });
|
|
437
|
+
/* round trip against the program's mark: 85,000 * 10^-8 USD/coin in atoms */
|
|
438
|
+
const fraction = perpMarkFraction(6, 3, -8);
|
|
439
|
+
expect(perpMarkPrice(8_500_000_000_000n, { ...fraction, priceCap: 10n ** 12n })).toBe(85_000_000n);
|
|
440
|
+
expect(() => perpMarkFraction(6.5, 3, -8)).toThrow(/quoteDecimals/);
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
it('max leverage is floor(10000 / initialMarginBps)', () => {
|
|
444
|
+
expect(perpMaxLeverage(500)).toBe(20);
|
|
445
|
+
expect(perpMaxLeverage(250)).toBe(40);
|
|
446
|
+
expect(perpMaxLeverage(300)).toBe(33);
|
|
447
|
+
expect(perpMaxLeverage(10_000)).toBe(1);
|
|
448
|
+
expect(perpMaxLeverage(1)).toBe(10_000);
|
|
449
|
+
expect(() => perpMaxLeverage(0)).toThrow(/initialMarginBps/);
|
|
450
|
+
expect(() => perpMaxLeverage(10_001)).toThrow(/initialMarginBps/);
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
it('lists the market accounts a transaction carries', () => {
|
|
454
|
+
expect(PERP_DEFAULT_MARKET_RECORD_INDEX).toBe(1);
|
|
455
|
+
const market = { seatArena: 's', orderArena: 'o', bidsCbook: 'b', asksCbook: 'a', quoteVault: 'q' };
|
|
456
|
+
expect(perpMarketAccountAddresses(market)).toEqual(['s', 'o', 'b', 'a']);
|
|
457
|
+
expect(perpMarketReadOnlyAddresses({ exchangeMeta: 'e', oracleFeed: 'f' })).toEqual(['e', 'f']);
|
|
458
|
+
const bytes = { seatArena: key(1), orderArena: key(2), bidsCbook: key(3), asksCbook: key(4) };
|
|
459
|
+
expect(perpMarketAccountAddresses(bytes)).toEqual([key(1), key(2), key(3), key(4)]);
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
it('long 10 lots at 85,000,000 with 50,000,000 collateral at the entry mark', () => {
|
|
463
|
+
|
|
464
|
+
const mark = ENTRY;
|
|
465
|
+
const s = seat();
|
|
466
|
+
expect(perpNotional(MARKET, LOTS, mark)).toBe(850_000_000n);
|
|
467
|
+
expect(perpUnrealizedPnl(MARKET, s, mark)).toBe(0n);
|
|
468
|
+
expect(perpEquity(MARKET, s, mark)).toBe(50_000_000n);
|
|
469
|
+
expect(perpInitialMargin(MARKET, s, mark)).toBe(42_500_000n); /* 5% of 850,000,000 */
|
|
470
|
+
expect(perpMaintenanceMargin(MARKET, s, mark)).toBe(21_250_000n); /* 2.5% */
|
|
471
|
+
expect(perpFreeCollateral(MARKET, s, mark)).toBe(7_500_000n);
|
|
472
|
+
expect(perpLeverageBps(MARKET, s, mark)).toBe(170_000n); /* 17x */
|
|
473
|
+
expect(perpAverageEntryPrice(MARKET, s)).toBe(ENTRY);
|
|
474
|
+
expect(perpIsLiquidatable(MARKET, s, mark)).toBe(false);
|
|
475
|
+
/* free 7.5M buys one more lot (4.25M initial margin each); selling can
|
|
476
|
+
close all 10 plus open one */
|
|
477
|
+
expect(perpMaxBuyLots(MARKET, s, mark, mark)).toBe(1n);
|
|
478
|
+
expect(perpMaxSellLots(MARKET, s, mark, mark)).toBe(11n);
|
|
479
|
+
expect(perpCanPostOrder(MARKET, s, 'buy', 1n, mark, mark)).toBe(true);
|
|
480
|
+
expect(perpCanPostOrder(MARKET, s, 'buy', 2n, mark, mark)).toBe(false);
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
it('mark moves: equity, free and liquidation', () => {
|
|
484
|
+
const s = seat();
|
|
485
|
+
/* up 1,000,000: +10,000,000 pnl */
|
|
486
|
+
expect(perpUnrealizedPnl(MARKET, s, 86_000_000n)).toBe(10_000_000n);
|
|
487
|
+
expect(perpEquity(MARKET, s, 86_000_000n)).toBe(60_000_000n);
|
|
488
|
+
expect(perpFreeCollateral(MARKET, s, 86_000_000n)).toBe(60_000_000n - 43_000_000n);
|
|
489
|
+
/* down 1,000,000: -10,000,000 pnl, free negative but not liquidatable */
|
|
490
|
+
expect(perpEquity(MARKET, s, 84_000_000n)).toBe(40_000_000n);
|
|
491
|
+
expect(perpFreeCollateral(MARKET, s, 84_000_000n)).toBe(40_000_000n - 42_000_000n);
|
|
492
|
+
expect(perpMaxBuyLots(MARKET, s, 84_000_000n, 84_000_000n)).toBe(0n);
|
|
493
|
+
expect(perpMaxSellLots(MARKET, s, 84_000_000n, 84_000_000n)).toBe(10n);
|
|
494
|
+
expect(perpIsLiquidatable(MARKET, s, 84_000_000n)).toBe(false);
|
|
495
|
+
/* resting orders that grow the position consume free through their notional */
|
|
496
|
+
const withOrders = seat({ openBidLots: 1n, openBidNotional: 84_000_000n });
|
|
497
|
+
expect(perpInitialMargin(MARKET, withOrders, ENTRY)).toBe(42_500_000n + 4_200_000n);
|
|
498
|
+
expect(perpFreeCollateral(MARKET, withOrders, ENTRY)).toBe(3_300_000n);
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
it('nets resting orders against the position they would reduce', () => {
|
|
502
|
+
expect(perpSideMarginNotional(0n, 0n, 0n)).toBe(0n);
|
|
503
|
+
expect(perpSideMarginNotional(10n, 850_000_000n, 10n)).toBe(0n);
|
|
504
|
+
expect(perpSideMarginNotional(10n, 850_000_000n, 12n)).toBe(0n);
|
|
505
|
+
expect(perpSideMarginNotional(10n, 850_000_000n, 0n)).toBe(850_000_000n);
|
|
506
|
+
expect(perpSideMarginNotional(12n, 267_720n, 10n)).toBe(44_620n); /* ceil(267720 * 2 / 12) */
|
|
507
|
+
/* a long of 10 lots with free exactly 0 can still post a 10-lot close */
|
|
508
|
+
const tight = seat({ quantityQuote: 42_500_000n }); /* equity 42.5M = im_position at the entry mark */
|
|
509
|
+
expect(perpFreeCollateral(MARKET, tight, ENTRY)).toBe(0n);
|
|
510
|
+
expect(perpCanPostOrder(MARKET, tight, 'sell', 10n, ENTRY, ENTRY)).toBe(true);
|
|
511
|
+
expect(perpCanPostOrder(MARKET, tight, 'sell', 11n, ENTRY, ENTRY)).toBe(false);
|
|
512
|
+
expect(perpCanPostOrder(MARKET, tight, 'buy', 1n, ENTRY, ENTRY)).toBe(false);
|
|
513
|
+
const closing = seat({ quantityQuote: 42_500_000n, openAskLots: 10n, openAskNotional: 850_000_000n });
|
|
514
|
+
expect(perpOrderInitialMargin(MARKET, closing)).toBe(0n);
|
|
515
|
+
expect(perpFreeCollateral(MARKET, closing, ENTRY)).toBe(0n);
|
|
516
|
+
/* an 11-lot close charges margin on the one excess lot only: ceil(935M * 1 / 11) = 85M -> 5% = 4.25M */
|
|
517
|
+
const over = seat({ openAskLots: 11n, openAskNotional: 11n * ENTRY });
|
|
518
|
+
expect(perpOrderInitialMargin(MARKET, over)).toBe(4_250_000n);
|
|
519
|
+
expect(perpFreeCollateral(MARKET, over, ENTRY)).toBe(7_500_000n - 4_250_000n);
|
|
520
|
+
expect(perpMaxSellLots(MARKET, seat(), ENTRY, ENTRY)).toBe(11n);
|
|
521
|
+
/* pro rata across two ask prices: 6 @ 110 + 6 @ 120 on a 10-lot long,
|
|
522
|
+
margined notional = ceil(267720 * 2 / 12) = 44620 */
|
|
523
|
+
const pro = seat({ longLots: 10n, entryNotional: 10n * 100n * 100n, openAskLots: 12n, openAskNotional: 267_720n });
|
|
524
|
+
expect(perpSideMarginNotional(pro.openAskLots, pro.openAskNotional, minLots(pro.openAskLots, pro.longLots))).toBe(44_620n);
|
|
525
|
+
expect(perpOrderInitialMargin(MARKET, pro)).toBe(ceilBps(44_620n, 500n));
|
|
526
|
+
/* bids net against a short the same way */
|
|
527
|
+
const shortWithBids = shortSeat({ openBidLots: 4n, openBidNotional: 4n * ENTRY });
|
|
528
|
+
expect(perpOrderInitialMargin(MARKET, shortWithBids)).toBe(0n);
|
|
529
|
+
const shortOverBids = shortSeat({ openBidLots: 12n, openBidNotional: 12n * ENTRY });
|
|
530
|
+
expect(perpOrderInitialMargin(MARKET, shortOverBids)).toBe(perpCeilBps(2n * ENTRY, 500));
|
|
531
|
+
});
|
|
532
|
+
|
|
533
|
+
it('liquidation price is the highest mark at which a long is liquidatable', () => {
|
|
534
|
+
const s = seat();
|
|
535
|
+
/* m* = 10000 * (850,000,000 - 50,000,000) / (10 * 9750) = 82,051,282.05 */
|
|
536
|
+
const price = perpLiquidationPrice(MARKET, s);
|
|
537
|
+
expect(price).toBe(82_051_282n);
|
|
538
|
+
expect(perpIsLiquidatable(MARKET, s, price!)).toBe(true);
|
|
539
|
+
expect(perpIsLiquidatable(MARKET, s, price! + 1n)).toBe(false);
|
|
540
|
+
expect(perpEquity(MARKET, s, price!)).toBe(20_512_820n);
|
|
541
|
+
expect(perpMaintenanceMargin(MARKET, s, price!)).toBe(20_512_821n);
|
|
542
|
+
/* bankruptcy: ceil((850,000,000 - 50,000,000) / 10) */
|
|
543
|
+
expect(perpBankruptcyPrice(MARKET, s)).toBe(80_000_000n);
|
|
544
|
+
expect(perpEquity(MARKET, s, 80_000_000n)).toBe(0n);
|
|
545
|
+
/* a fully collateralized long cannot be liquidated by a price move */
|
|
546
|
+
expect(perpLiquidationPrice(MARKET, seat({ quantityQuote: 850_000_000n }))).toBeNull();
|
|
547
|
+
expect(perpBankruptcyPrice(MARKET, seat({ quantityQuote: 850_000_000n }))).toBe(0n);
|
|
548
|
+
});
|
|
549
|
+
|
|
550
|
+
it('liquidation price is the lowest mark at which a short is liquidatable', () => {
|
|
551
|
+
const s = shortSeat();
|
|
552
|
+
/* m* = 10000 * (850,000,000 + 50,000,000) / (10 * 10250) = 87,804,878.04 */
|
|
553
|
+
const price = perpLiquidationPrice(MARKET, s);
|
|
554
|
+
expect(price).toBe(87_804_879n);
|
|
555
|
+
expect(perpIsLiquidatable(MARKET, s, price!)).toBe(true);
|
|
556
|
+
expect(perpIsLiquidatable(MARKET, s, price! - 1n)).toBe(false);
|
|
557
|
+
expect(perpUnrealizedPnl(MARKET, s, 84_000_000n)).toBe(10_000_000n);
|
|
558
|
+
/* bankruptcy: floor((850,000,000 + 50,000,000) / 10) */
|
|
559
|
+
expect(perpBankruptcyPrice(MARKET, s)).toBe(90_000_000n);
|
|
560
|
+
expect(perpEquity(MARKET, s, 90_000_000n)).toBe(0n);
|
|
561
|
+
/* threshold above the cap: the clamped mark can never liquidate it */
|
|
562
|
+
expect(perpLiquidationPrice({ ...MARKET, priceCap: 87_000_000n }, s)).toBeNull();
|
|
563
|
+
expect(perpBankruptcyPrice({ ...MARKET, priceCap: 87_000_000n }, s)).toBe(87_000_000n);
|
|
564
|
+
expect(perpMaxBuyLots(MARKET, s, ENTRY, ENTRY)).toBe(11n);
|
|
565
|
+
expect(perpMaxSellLots(MARKET, s, ENTRY, ENTRY)).toBe(1n);
|
|
566
|
+
});
|
|
567
|
+
|
|
568
|
+
it('flat seats have no position derived values', () => {
|
|
569
|
+
const flat = seat({ longLots: 0n, entryNotional: 0n });
|
|
570
|
+
expect(perpUnrealizedPnl(MARKET, flat, ENTRY)).toBe(0n);
|
|
571
|
+
expect(perpLiquidationPrice(MARKET, flat)).toBeNull();
|
|
572
|
+
expect(perpBankruptcyPrice(MARKET, flat)).toBeNull();
|
|
573
|
+
expect(perpLeverageBps(MARKET, flat, ENTRY)).toBeNull();
|
|
574
|
+
expect(perpAverageEntryPrice(MARKET, flat)).toBeNull();
|
|
575
|
+
expect(perpIsLiquidatable(MARKET, flat, 1n)).toBe(false);
|
|
576
|
+
expect(perpLiquidationPreview(MARKET, flat, ENTRY)).toBeNull();
|
|
577
|
+
/* the whole collateral buys 50,000,000 / ceil(85,000,000 * 0.05) = 11 lots */
|
|
578
|
+
expect(perpMaxBuyLots(MARKET, flat, ENTRY, ENTRY)).toBe(11n);
|
|
579
|
+
expect(perpMaxSellLots(MARKET, flat, ENTRY, ENTRY)).toBe(11n);
|
|
580
|
+
/* the position limit binds first when free is plentiful */
|
|
581
|
+
expect(perpMaxBuyLots({ ...MARKET, maxPositionLots: 5n }, flat, ENTRY, ENTRY)).toBe(5n);
|
|
582
|
+
});
|
|
583
|
+
|
|
584
|
+
it('previews a liquidation at the mark clamped to bankruptcy', () => {
|
|
585
|
+
const s = seat();
|
|
586
|
+
/* mark below bankruptcy: transfer at the bankruptcy price, target keeps nothing */
|
|
587
|
+
const gap = perpLiquidationPreview(MARKET, s, 79_000_000n)!;
|
|
588
|
+
expect(gap).toEqual({ side: 'long', lots: LOTS, price: 80_000_000n, fee: 0n, targetQuoteAfter: 0n });
|
|
589
|
+
/* mark between liquidation and bankruptcy: fee 1% of notional capped by what is left */
|
|
590
|
+
const mark = 81_000_000n;
|
|
591
|
+
const preview = perpLiquidationPreview(MARKET, s, mark)!;
|
|
592
|
+
expect(preview.price).toBe(mark);
|
|
593
|
+
const quoteAfterClose = COLLATERAL + perpUnrealizedPnl(MARKET, s, mark); /* 10,000,000 */
|
|
594
|
+
expect(quoteAfterClose).toBe(10_000_000n);
|
|
595
|
+
expect(preview.fee).toBe((850_000_000n - 40_000_000n) / 100n); /* 8,100,000 */
|
|
596
|
+
expect(preview.targetQuoteAfter).toBe(quoteAfterClose - preview.fee);
|
|
597
|
+
/* ceil_bps matches the reference helper for the margin figures */
|
|
598
|
+
expect(perpInitialMargin(MARKET, s, mark)).toBe(ceilBps(810_000_000n, 500n));
|
|
599
|
+
});
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
describe('perp instruction builders', () => {
|
|
603
|
+
const seatArena = key(21);
|
|
604
|
+
const orderArena = key(22);
|
|
605
|
+
const bids = key(23);
|
|
606
|
+
const asks = key(24);
|
|
607
|
+
const exchangeMeta = key(25);
|
|
608
|
+
const authority = key(26);
|
|
609
|
+
const oracle = key(27);
|
|
610
|
+
const ctx = context([
|
|
611
|
+
[seatArena, 1],
|
|
612
|
+
[orderArena, 2],
|
|
613
|
+
[bids, 3],
|
|
614
|
+
[asks, 4],
|
|
615
|
+
[exchangeMeta, 5],
|
|
616
|
+
[authority, 6],
|
|
617
|
+
[oracle, 7],
|
|
618
|
+
]);
|
|
619
|
+
|
|
620
|
+
it('market record carries the oracle feed index at offset 24 (0xffff when absent)', async () => {
|
|
621
|
+
const base = {
|
|
622
|
+
marketRecordIndex: 1,
|
|
623
|
+
seatArenaAccountBytes: seatArena,
|
|
624
|
+
orderArenaAccountBytes: orderArena,
|
|
625
|
+
bidsCbookAccountBytes: bids,
|
|
626
|
+
asksCbookAccountBytes: asks,
|
|
627
|
+
seatAuthorityAccountBytes: authority,
|
|
628
|
+
seatIndex: 3,
|
|
629
|
+
exchangeMetaAccountBytes: exchangeMeta,
|
|
630
|
+
};
|
|
631
|
+
const withOracle = await createPerpMarketRecordInstruction({ ...base, oracleFeedAccountBytes: oracle })(ctx);
|
|
632
|
+
expect(withOracle.length).toBe(32);
|
|
633
|
+
expect(withOracle[0]).toBe(PERP_INSTRUCTION_MARKET_RECORD);
|
|
634
|
+
expect(withOracle[1]).toBe(1);
|
|
635
|
+
const view = new DataView(withOracle.buffer, withOracle.byteOffset);
|
|
636
|
+
expect(view.getUint16(2, true)).toBe(1);
|
|
637
|
+
expect(view.getUint32(12, true)).toBe(3);
|
|
638
|
+
expect(view.getUint16(24, true)).toBe(7);
|
|
639
|
+
expect([...withOracle.subarray(26)]).toEqual([0, 0, 0, 0, 0, 0]);
|
|
640
|
+
const without = await createPerpMarketRecordInstruction(base)(ctx);
|
|
641
|
+
expect(new DataView(without.buffer, without.byteOffset).getUint16(24, true)).toBe(PERP_NULL_ACCOUNT_INDEX);
|
|
642
|
+
});
|
|
643
|
+
|
|
644
|
+
it('liquidate is 8 bytes with the target seat at offset 4', async () => {
|
|
645
|
+
const bytes = await createPerpLiquidateInstruction({ marketRecordIndex: 1, targetSeatIndex: 42 })(ctx);
|
|
646
|
+
expect([...bytes]).toEqual([PERP_INSTRUCTION_LIQUIDATE, 1, 0, 0, 42, 0, 0, 0]);
|
|
647
|
+
await expect(createPerpLiquidateInstruction({ marketRecordIndex: 1, targetSeatIndex: 0 })(ctx)).rejects.toThrow(/targetSeatIndex/);
|
|
648
|
+
});
|
|
649
|
+
|
|
650
|
+
it('market set oracle is 40 bytes', async () => {
|
|
651
|
+
const args = {
|
|
652
|
+
marketRecordIndex: 1,
|
|
653
|
+
oracleFeedAccountBytes: oracle,
|
|
654
|
+
oracleExponent: -8,
|
|
655
|
+
markNum: 1n,
|
|
656
|
+
markDen: 100_000n,
|
|
657
|
+
maxMarkAgeNs: 5n,
|
|
658
|
+
};
|
|
659
|
+
await expect(createPerpMarketSetOracleInstruction({ ...args, markNum: 0n })(ctx)).rejects.toThrow(/markNum/);
|
|
660
|
+
const bytes = await createPerpMarketSetOracleInstruction(args)(ctx);
|
|
661
|
+
expect(bytes.length).toBe(40);
|
|
662
|
+
expect(bytes[0]).toBe(PERP_INSTRUCTION_MARKET_SET_ORACLE);
|
|
663
|
+
expect(bytes[1]).toBe(1);
|
|
664
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset);
|
|
665
|
+
expect(view.getUint16(2, true)).toBe(7);
|
|
666
|
+
expect(view.getInt32(4, true)).toBe(-8);
|
|
667
|
+
expect(view.getBigUint64(8, true)).toBe(1n);
|
|
668
|
+
expect(view.getBigUint64(16, true)).toBe(100_000n);
|
|
669
|
+
expect(view.getBigUint64(24, true)).toBe(5n);
|
|
670
|
+
expect(view.getBigUint64(32, true)).toBe(0n);
|
|
671
|
+
});
|
|
672
|
+
|
|
673
|
+
it('market create is 112 bytes plus proofs with the margin params at offset 72', async () => {
|
|
674
|
+
const tokenProgram = key(30);
|
|
675
|
+
const quoteMint = key(31);
|
|
676
|
+
const quoteVault = key(32);
|
|
677
|
+
const createCtx = context([
|
|
678
|
+
[tokenProgram, 1],
|
|
679
|
+
[exchangeMeta, 2],
|
|
680
|
+
[quoteMint, 3],
|
|
681
|
+
[seatArena, 4],
|
|
682
|
+
[orderArena, 5],
|
|
683
|
+
[bids, 6],
|
|
684
|
+
[asks, 7],
|
|
685
|
+
[quoteVault, 8],
|
|
686
|
+
[authority, 9],
|
|
687
|
+
[oracle, 10],
|
|
688
|
+
]);
|
|
689
|
+
const args = {
|
|
690
|
+
marketRecordIndex: 1,
|
|
691
|
+
tokenProgramAccountBytes: tokenProgram,
|
|
692
|
+
exchangeMetaAccountBytes: exchangeMeta,
|
|
693
|
+
quoteMintAccountBytes: quoteMint,
|
|
694
|
+
lotSize: 1n,
|
|
695
|
+
tickSize: 1_000n,
|
|
696
|
+
priceCap: 200_000_000n,
|
|
697
|
+
maxPositionLots: 1_000_000n,
|
|
698
|
+
oracleFeedAccountBytes: oracle,
|
|
699
|
+
initialMarginBps: 250,
|
|
700
|
+
maintenanceMarginBps: 125,
|
|
701
|
+
liquidationFeeBps: 100,
|
|
702
|
+
markNum: 1n,
|
|
703
|
+
markDen: 100_000n,
|
|
704
|
+
oracleExponent: -8,
|
|
705
|
+
maxMarkAgeNs: 0n,
|
|
706
|
+
seatArenaAccountBytes: seatArena,
|
|
707
|
+
orderArenaAccountBytes: orderArena,
|
|
708
|
+
bidsCbookAccountBytes: bids,
|
|
709
|
+
asksCbookAccountBytes: asks,
|
|
710
|
+
quoteVaultAccountBytes: quoteVault,
|
|
711
|
+
marketAuthorityAccountBytes: authority,
|
|
712
|
+
seatArenaStateProof: Uint8Array.of(1, 2, 3),
|
|
713
|
+
orderArenaStateProof: Uint8Array.of(4),
|
|
714
|
+
bidsCbookStateProof: Uint8Array.of(5, 6),
|
|
715
|
+
asksCbookStateProof: new Uint8Array(0),
|
|
716
|
+
quoteVaultStateProof: Uint8Array.of(7),
|
|
717
|
+
};
|
|
718
|
+
const bytes = await createPerpMarketCreateInstruction(args)(createCtx);
|
|
719
|
+
expect(bytes.length).toBe(112 + 3 + 1 + 2 + 0 + 1);
|
|
720
|
+
expect(bytes[0]).toBe(PERP_INSTRUCTION_MARKET_CREATE);
|
|
721
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset);
|
|
722
|
+
expect(view.getUint16(72, true)).toBe(10); /* oracle_feed_account_idx */
|
|
723
|
+
expect(view.getUint16(74, true)).toBe(250);
|
|
724
|
+
expect(view.getUint16(76, true)).toBe(125);
|
|
725
|
+
expect(view.getUint16(78, true)).toBe(100);
|
|
726
|
+
expect(view.getBigUint64(80, true)).toBe(1n);
|
|
727
|
+
expect(view.getBigUint64(88, true)).toBe(100_000n);
|
|
728
|
+
expect(view.getInt32(96, true)).toBe(-8);
|
|
729
|
+
expect(view.getUint32(100, true)).toBe(0);
|
|
730
|
+
expect(view.getBigUint64(104, true)).toBe(0n);
|
|
731
|
+
expect([...bytes.subarray(112)]).toEqual([1, 2, 3, 4, 5, 6, 7]);
|
|
732
|
+
await expect(createPerpMarketCreateInstruction({ ...args, maintenanceMarginBps: 250 })(createCtx)).rejects.toThrow(/maintenance/);
|
|
733
|
+
await expect(createPerpMarketCreateInstruction({ ...args, markNum: 0n })(createCtx)).rejects.toThrow(/markNum/);
|
|
734
|
+
await expect(createPerpMarketCreateInstruction({ ...args, markDen: 0n })(createCtx)).rejects.toThrow(/markDen/);
|
|
735
|
+
});
|
|
736
|
+
});
|
|
737
|
+
|
|
738
|
+
describe('perp market derivation', () => {
|
|
739
|
+
it('hashes initial_margin_bps as a trailing little-endian u16', async () => {
|
|
740
|
+
const authority = address(40);
|
|
741
|
+
const quoteMint = address(41);
|
|
742
|
+
const tokenProgram = BOOTSTRAP_PROGRAM_ADDRESSES.token;
|
|
743
|
+
const accounts = await derivePerpMarketAccounts({
|
|
744
|
+
thru,
|
|
745
|
+
tokenProgramAddress: tokenProgram,
|
|
746
|
+
marketAuthorityAddress: authority,
|
|
747
|
+
quoteMintAddress: quoteMint,
|
|
748
|
+
lotSize: 1n,
|
|
749
|
+
tickSize: 1_000n,
|
|
750
|
+
priceCap: 200_000_000n,
|
|
751
|
+
initialMarginBps: 250,
|
|
752
|
+
});
|
|
753
|
+
const u64 = (value: bigint) => {
|
|
754
|
+
const bytes = Buffer.alloc(8);
|
|
755
|
+
bytes.writeBigUInt64LE(value);
|
|
756
|
+
return bytes;
|
|
757
|
+
};
|
|
758
|
+
const base = createHash('sha256')
|
|
759
|
+
.update(key(40))
|
|
760
|
+
.update(u64(1n))
|
|
761
|
+
.update(u64(1_000n))
|
|
762
|
+
.update(u64(200_000_000n))
|
|
763
|
+
.update(key(41))
|
|
764
|
+
.update(Buffer.from([250 & 0xff, 250 >> 8]))
|
|
765
|
+
.digest();
|
|
766
|
+
const unique = (id: string) => createHash('sha256').update(base).update(id).digest();
|
|
767
|
+
const pda = (id: string) => deriveProgramAddress({ programAddress: PERP_PROGRAM_ADDRESS, seed: new Uint8Array(unique(id)), ephemeral: false }).address;
|
|
768
|
+
expect(accounts.seatArena.address).toBe(pda('s'));
|
|
769
|
+
expect(accounts.orderArena.address).toBe(pda('o'));
|
|
770
|
+
expect(accounts.bidsCbook.address).toBe(pda('b'));
|
|
771
|
+
expect(accounts.asksCbook.address).toBe(pda('a'));
|
|
772
|
+
const other = await derivePerpMarketAccounts({
|
|
773
|
+
thru,
|
|
774
|
+
tokenProgramAddress: tokenProgram,
|
|
775
|
+
marketAuthorityAddress: authority,
|
|
776
|
+
quoteMintAddress: quoteMint,
|
|
777
|
+
lotSize: 1n,
|
|
778
|
+
tickSize: 1_000n,
|
|
779
|
+
priceCap: 200_000_000n,
|
|
780
|
+
initialMarginBps: 400,
|
|
781
|
+
});
|
|
782
|
+
expect(other.seatArena.address).not.toBe(accounts.seatArena.address);
|
|
783
|
+
});
|
|
784
|
+
});
|
|
785
|
+
|
|
786
|
+
describe('perp events', () => {
|
|
787
|
+
it('parses the liquidation event (type 15)', () => {
|
|
788
|
+
const data = new Uint8Array(8 + 96 + 8 + 48 + 8);
|
|
789
|
+
const view = new DataView(data.buffer);
|
|
790
|
+
view.setBigUint64(0, BigInt(PERP_EVENT_LIQUIDATION), true);
|
|
791
|
+
data.set(key(50), 8); /* market */
|
|
792
|
+
data.set(key(51), 40); /* liquidator */
|
|
793
|
+
data.set(key(52), 72); /* target */
|
|
794
|
+
view.setUint32(104, 2, true); /* liquidator_seat_idx */
|
|
795
|
+
view.setUint32(108, 5, true); /* target_seat_idx */
|
|
796
|
+
view.setBigUint64(112, 10n, true); /* lots */
|
|
797
|
+
view.setBigUint64(120, 81_000_000n, true); /* mark_price */
|
|
798
|
+
view.setBigUint64(128, 8_100_000n, true); /* fee */
|
|
799
|
+
view.setBigUint64(136, 0n, true); /* bad_debt */
|
|
800
|
+
view.setBigUint64(144, 1_900_000n, true); /* target_quote_after */
|
|
801
|
+
view.setBigUint64(152, 108_100_000n, true); /* liquidator_quote_after */
|
|
802
|
+
data[160] = 0; /* side: target was long */
|
|
803
|
+
const event = parsePerpEvent(data);
|
|
804
|
+
expect(event.variant).toBe('liquidation');
|
|
805
|
+
if (event.variant !== 'liquidation') throw new Error('unreachable');
|
|
806
|
+
expect(event.market).toBe(address(50));
|
|
807
|
+
expect(event.liquidator).toBe(address(51));
|
|
808
|
+
expect(event.target).toBe(address(52));
|
|
809
|
+
expect(event.liquidatorSeatIndex).toBe(2);
|
|
810
|
+
expect(event.targetSeatIndex).toBe(5);
|
|
811
|
+
expect(event.lots).toBe(10n);
|
|
812
|
+
expect(event.markPrice).toBe(81_000_000n);
|
|
813
|
+
expect(event.fee).toBe(8_100_000n);
|
|
814
|
+
expect(event.badDebt).toBe(0n);
|
|
815
|
+
expect(event.targetQuoteAfter).toBe(1_900_000n);
|
|
816
|
+
expect(event.liquidatorQuoteAfter).toBe(108_100_000n);
|
|
817
|
+
expect(event.targetSide).toBe('long');
|
|
818
|
+
data[160] = 1;
|
|
819
|
+
const short = parsePerpEvent(data);
|
|
820
|
+
expect(short.variant === 'liquidation' && short.targetSide).toBe('short');
|
|
821
|
+
});
|
|
822
|
+
});
|