@thru/programs 0.4.1 → 0.4.2

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.
Files changed (58) hide show
  1. package/dist/abi-manager/index.cjs +39 -2
  2. package/dist/abi-manager/index.cjs.map +1 -1
  3. package/dist/abi-manager/index.js +2 -2
  4. package/dist/amm/index.cjs +39 -2
  5. package/dist/amm/index.cjs.map +1 -1
  6. package/dist/amm/index.js +1 -1
  7. package/dist/bootstrap-addresses/index.cjs +41 -2
  8. package/dist/bootstrap-addresses/index.cjs.map +1 -1
  9. package/dist/bootstrap-addresses/index.d.cts +8 -1
  10. package/dist/bootstrap-addresses/index.d.ts +8 -1
  11. package/dist/bootstrap-addresses/index.js +1 -1
  12. package/dist/{chunk-TRPUGPZJ.js → chunk-2FFCNXCE.js} +58 -5
  13. package/dist/chunk-2FFCNXCE.js.map +1 -0
  14. package/dist/{chunk-QCJFKBAS.js → chunk-I3DLOUB4.js} +3 -3
  15. package/dist/{chunk-QCJFKBAS.js.map → chunk-I3DLOUB4.js.map} +1 -1
  16. package/dist/clob/index.cjs +41 -2
  17. package/dist/clob/index.cjs.map +1 -1
  18. package/dist/clob/index.d.cts +7 -1
  19. package/dist/clob/index.d.ts +7 -1
  20. package/dist/clob/index.js +3 -2
  21. package/dist/clob/index.js.map +1 -1
  22. package/dist/deploy/index.cjs +39 -2
  23. package/dist/deploy/index.cjs.map +1 -1
  24. package/dist/deploy/index.js +3 -3
  25. package/dist/oracle/index.cjs +39 -2
  26. package/dist/oracle/index.cjs.map +1 -1
  27. package/dist/oracle/index.js +1 -1
  28. package/dist/passkey-manager/index.cjs +42 -5
  29. package/dist/passkey-manager/index.cjs.map +1 -1
  30. package/dist/passkey-manager/index.js +1 -1
  31. package/dist/perp/index.cjs +1785 -162
  32. package/dist/perp/index.cjs.map +1 -1
  33. package/dist/perp/index.d.cts +558 -13
  34. package/dist/perp/index.d.ts +558 -13
  35. package/dist/perp/index.js +1749 -163
  36. package/dist/perp/index.js.map +1 -1
  37. package/dist/ratelimit/index.cjs +4757 -0
  38. package/dist/ratelimit/index.cjs.map +1 -0
  39. package/dist/ratelimit/index.d.cts +171 -0
  40. package/dist/ratelimit/index.d.ts +171 -0
  41. package/dist/ratelimit/index.js +4527 -0
  42. package/dist/ratelimit/index.js.map +1 -0
  43. package/package.json +7 -2
  44. package/src/bootstrap-addresses/index.test.ts +17 -0
  45. package/src/bootstrap-addresses/index.ts +12 -0
  46. package/src/clob/index.ts +7 -0
  47. package/src/perp/abi/thru/program/perp/types.ts +1949 -149
  48. package/src/perp/index.test.ts +189 -3
  49. package/src/perp/index.ts +316 -3
  50. package/src/ratelimit/abi/thru/program/ratelimit/types.ts +5448 -0
  51. package/src/ratelimit/accounts.ts +105 -0
  52. package/src/ratelimit/constants.ts +49 -0
  53. package/src/ratelimit/derivation.ts +93 -0
  54. package/src/ratelimit/index.test.ts +185 -0
  55. package/src/ratelimit/index.ts +30 -0
  56. package/src/ratelimit/instructions.ts +244 -0
  57. package/tsup.config.ts +1 -0
  58. package/dist/chunk-TRPUGPZJ.js.map +0 -1
package/src/perp/index.ts CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  accountData,
9
9
  accountIndex,
10
10
  assertU16,
11
+ assertU32,
11
12
  type AccountLookupContext,
12
13
  type InstructionData,
13
14
  } from '../utils/helpers';
@@ -59,10 +60,13 @@ import {
59
60
  ExchangeMetaAccount,
60
61
  ExchangeSetAdminInstructionBuilder,
61
62
  ExchangeSetStatusInstructionBuilder,
63
+ FundingUpdateInstructionBuilder,
62
64
  LiquidateInstructionBuilder,
63
65
  MarketAccount as MarketAccountView,
64
66
  MarketCreateInstructionBuilder,
65
67
  MarketRecordInstructionBuilder,
68
+ MarketSetFundingInstructionBuilder,
69
+ SettleFundingInstructionBuilder,
66
70
  MarketSetOracleInstructionBuilder,
67
71
  MarketSetStatusInstructionBuilder,
68
72
  ModifyOrderEntryInstructionBuilder,
@@ -101,7 +105,13 @@ export * from './abi/thru/program/perp/types';
101
105
  liquidatable = has a position and equity < mm_position
102
106
 
103
107
  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
108
+ more than its collateral leaves market.bad_debt.
109
+
110
+ Funding (Lighter's model) moves quote between longs and shorts every hour
111
+ through a cumulative index per lot; seats settle lazily, and the program
112
+ settles a seat before it reads its equity. The margin functions below take
113
+ a settled seat: pass a seat through perpSettleFunding first (a no-op on a
114
+ market without funding). The demo deployment on
105
115
  Alphanet is not a bootstrap program: it is managed by the deployer's key
106
116
  under PERP_PROGRAM_SEED. */
107
117
 
@@ -125,6 +135,9 @@ export const PERP_INSTRUCTION_EXCHANGE_RECOVER_ADMIN = 14;
125
135
  export const PERP_INSTRUCTION_MARKET_SET_EXCHANGE_STATUS = 15;
126
136
  export const PERP_INSTRUCTION_LIQUIDATE = 0x10;
127
137
  export const PERP_INSTRUCTION_MARKET_SET_ORACLE = 0x11;
138
+ export const PERP_INSTRUCTION_FUNDING_UPDATE = 0x12;
139
+ export const PERP_INSTRUCTION_MARKET_SET_FUNDING = 0x13;
140
+ export const PERP_INSTRUCTION_SETTLE_FUNDING = 0x14;
128
141
  /** Market record slot the demo tooling uses for its single market per transaction. */
129
142
  export const PERP_DEFAULT_MARKET_RECORD_INDEX = 1;
130
143
 
@@ -143,6 +156,10 @@ export const PERP_ERR_ORACLE_STALE = -213n;
143
156
  export const PERP_ERR_INVALID_MARGIN_PARAMS = -214n;
144
157
  export const PERP_ERR_NOT_LIQUIDATABLE = -215n;
145
158
  export const PERP_ERR_SELF_LIQUIDATION = -216n;
159
+ export const PERP_ERR_FUNDING_DISABLED = -217n;
160
+ export const PERP_ERR_INVALID_FUNDING_PARAMS = -218n;
161
+ /** funding_update shared its transaction with an instruction that could move the book. */
162
+ export const PERP_ERR_FUNDING_UPDATE_NOT_ALONE = -219n;
146
163
  export const PERP_ERR_INSUFFICIENT_COLLATERAL = -403n;
147
164
  export const PERP_ERR_INSUFFICIENT_FUNDS_QUOTE = -401n;
148
165
 
@@ -161,6 +178,7 @@ export const PERP_EVENT_EXCHANGE_STATUS = 12;
161
178
  export const PERP_EVENT_EXCHANGE_ADMIN = 13;
162
179
  export const PERP_EVENT_MARKET_EXCHANGE_STATUS = 14;
163
180
  export const PERP_EVENT_LIQUIDATION = 15;
181
+ export const PERP_EVENT_FUNDING_ROUND = 16;
164
182
 
165
183
  export const PERP_BPS_DENOMINATOR = 10_000n;
166
184
 
@@ -191,7 +209,17 @@ export const PERP_MODIFY_FLAG_HAS_CLIENT_ID = 1 << 1;
191
209
  export const PERP_MODIFY_FLAG_HAS_ORDER_ID = 1 << 2;
192
210
 
193
211
  export const PERP_MARKET_MAGIC = 0x79;
194
- export const PERP_MARKET_ACCOUNT_SIZE = 320;
212
+ export const PERP_MARKET_ACCOUNT_SIZE = 448;
213
+
214
+ /* Funding: mirrors thru-perps/tn_perp_program/utils/funding.h. Rates are integer ticks of 1e-6. */
215
+ export const PERP_FUNDING_RATE_TICK = 1_000_000n;
216
+ export const PERP_FUNDING_SAMPLE_NS = 60_000_000_000n;
217
+ export const PERP_FUNDING_ROUND_NS = 3_600_000_000_000n;
218
+ export const PERP_FUNDING_PREMIUM_DIVISOR = 60n;
219
+ export const PERP_FUNDING_HOURS_PER_RATE = 8n;
220
+ export const PERP_FUNDING_PARAM_MAX = 1_000_000;
221
+ export const PERP_FUNDING_MULTIPLIER_ONE = 100;
222
+ export const PERP_FUNDING_PREMIUM_MAX = 1_000_000n;
195
223
  /** The seat arena's header entry starts here; seat index 1 follows it. */
196
224
  export const PERP_SEAT_MANAGER_RESERVED_SIZE = 512;
197
225
  export const PERP_EXCHANGE_META_ACCOUNT_SIZE = 96;
@@ -232,7 +260,10 @@ type PerpInstructionVariant =
232
260
  | 'exchange_recover_admin'
233
261
  | 'market_set_exchange_status'
234
262
  | 'liquidate'
235
- | 'market_set_oracle';
263
+ | 'market_set_oracle'
264
+ | 'funding_update'
265
+ | 'market_set_funding'
266
+ | 'settle_funding';
236
267
 
237
268
  export type PerpOrderSide = OrderSide;
238
269
  export type PerpOrderType = OrderType;
@@ -372,6 +403,46 @@ export interface PerpMarketSetOracleArgs extends PerpOracleParams {
372
403
  oracleFeedAccountBytes: Uint8Array;
373
404
  }
374
405
 
406
+ export interface PerpFundingUpdateArgs {
407
+ marketRecordIndex: number;
408
+ }
409
+
410
+ export interface PerpSettleFundingArgs {
411
+ marketRecordIndex: number;
412
+ /** The seat to settle (any seat: settle_funding is permissionless). */
413
+ targetSeatIndex: number;
414
+ }
415
+
416
+ /** Rates in ticks of 1e-6 per 8 hours (Lighter's units: 100 = 0.01%). */
417
+ export interface PerpFundingParams {
418
+ interestRate: number;
419
+ clampSmall: number;
420
+ clampBig: number;
421
+ /** 0 disables funding; 1..100 scales the premium (100 = 1x). */
422
+ premiumMultiplier: number;
423
+ /** Quote atoms walked into each side of the book for the impact prices. */
424
+ impactNotional: bigint;
425
+ }
426
+
427
+ export interface PerpMarketSetFundingArgs extends PerpFundingParams {
428
+ marketRecordIndex: number;
429
+ }
430
+
431
+ /** A market's funding state. */
432
+ export interface PerpFunding extends PerpFundingParams {
433
+ /** Cumulative funding per lot, quote atoms * PERP_FUNDING_RATE_TICK (signed). */
434
+ index: bigint;
435
+ /** Net quote atoms the market collected from settlements. */
436
+ balance: bigint;
437
+ lastRoundNs: bigint;
438
+ lastSampleNs: bigint;
439
+ /** Premium samples of the current hour, ticks. */
440
+ premiumSum: bigint;
441
+ sampleCount: number;
442
+ /** Hourly rate of the last round, ticks; positive: longs pay. */
443
+ rate: bigint;
444
+ }
445
+
375
446
  export interface PerpMarket {
376
447
  magic: number;
377
448
  statusFlags: number;
@@ -397,6 +468,8 @@ export interface PerpMarket {
397
468
  liquidationFeeBps: number;
398
469
  oracleExponent: number;
399
470
  maxMarkAgeNs: bigint;
471
+ /** Optional so callers can build markets without funding (funding off). */
472
+ funding?: PerpFunding;
400
473
  }
401
474
 
402
475
  export interface PerpExchangeMeta {
@@ -440,6 +513,10 @@ export interface PerpSeatEntry {
440
513
  /** Sum of lots * lotSize * price over resting bids / asks. */
441
514
  openBidNotional: bigint;
442
515
  openAskNotional: bigint;
516
+ /** The market's funding index at the seat's last settlement. */
517
+ fundingSnapshot?: bigint;
518
+ /** Sub-atom funding credit carried to the next settlement, [0, 1e6). */
519
+ fundingCarry?: number;
443
520
  }
444
521
 
445
522
  export interface PerpOrderEntry {
@@ -622,6 +699,18 @@ export type ParsedPerpEvent =
622
699
  /** Side of the target's position before the transfer. */
623
700
  targetSide: 'long' | 'short';
624
701
  })
702
+ | (ParsedPerpEventBase & {
703
+ variant: 'funding_round';
704
+ market: string;
705
+ /** Hourly rate, ticks of 1e-6; positive: longs pay. */
706
+ rate: bigint;
707
+ premiumSum: bigint;
708
+ sampleCount: number;
709
+ /** Oracle index the round priced at, quote atoms per base atom. */
710
+ indexPrice: bigint;
711
+ fundingIndex: bigint;
712
+ roundNs: bigint;
713
+ })
625
714
  | (ParsedPerpEventBase & {
626
715
  variant:
627
716
  | 'market_status'
@@ -872,6 +961,128 @@ export function perpMaxSellLots(market: PerpMarginMarket, seat: PerpMarginSeat,
872
961
  return seat.longLots + minBig(capacity, affordableLots(market, seat, price, mark));
873
962
  }
874
963
 
964
+ /* Funding (bigint exact): mirrors thru-perps/tn_perp_program/utils/funding.h */
965
+
966
+ export type PerpFundingSeat = PerpMarginSeat & Pick<PerpSeatEntry, 'fundingSnapshot' | 'fundingCarry'>;
967
+
968
+ export function perpFundingEnabled(market: Pick<PerpMarket, 'funding'>): boolean {
969
+ return (market.funding?.premiumMultiplier ?? 0) !== 0;
970
+ }
971
+
972
+ /** The hourly rate (ticks) a round turns premiumSum into. */
973
+ export function perpFundingHourlyRate(
974
+ premiumSum: bigint,
975
+ params: Pick<PerpFundingParams, 'interestRate' | 'clampSmall' | 'clampBig' | 'premiumMultiplier'>,
976
+ ): bigint {
977
+ const one = BigInt(PERP_FUNDING_MULTIPLIER_ONE);
978
+ const multiplier = BigInt(params.premiumMultiplier);
979
+ const avg = ((premiumSum / PERP_FUNDING_PREMIUM_DIVISOR) * multiplier) / one;
980
+ const small = (BigInt(params.clampSmall) * multiplier) / one;
981
+ const big = BigInt(params.clampBig);
982
+ const r8 = clampBig(avg + clampBig(BigInt(params.interestRate) - avg, -small, small), -big, big);
983
+ return r8 / PERP_FUNDING_HOURS_PER_RATE;
984
+ }
985
+
986
+ /** One premium sample (ticks); a zero impact price counts as the index.
987
+ Mirrors thru-perps/tn_perp_program/utils/funding.h. */
988
+ export function perpFundingPremiumSample(index: bigint, impactBid: bigint, impactAsk: bigint): bigint {
989
+ if (index <= 0n) return 0n;
990
+ const bid = impactBid > 0n ? impactBid : index;
991
+ const ask = impactAsk > 0n ? impactAsk : index;
992
+ const above = bid > index ? bid - index : 0n;
993
+ const below = ask < index ? index - ask : 0n;
994
+ return clampBig(((above - below) * PERP_FUNDING_RATE_TICK) / index, -PERP_FUNDING_PREMIUM_MAX, PERP_FUNDING_PREMIUM_MAX);
995
+ }
996
+
997
+ /** Why market_set_funding would reject params, or null. */
998
+ export function perpFundingParamsProblem(
999
+ market: Pick<PerpMarket, 'initialMarginBps' | 'maintenanceMarginBps'>,
1000
+ params: PerpFundingParams,
1001
+ ): string | null {
1002
+ const { interestRate, clampSmall, clampBig: big, premiumMultiplier, impactNotional } = params;
1003
+ if (!Number.isInteger(premiumMultiplier) || premiumMultiplier < 0 || premiumMultiplier > PERP_FUNDING_MULTIPLIER_ONE) {
1004
+ return `premiumMultiplier must be 0 (off) or 1..${PERP_FUNDING_MULTIPLIER_ONE}`;
1005
+ }
1006
+ if (premiumMultiplier === 0) return null;
1007
+ if (impactNotional <= 0n) return 'impactNotional must be positive';
1008
+ for (const [label, value] of [['interestRate', interestRate], ['clampSmall', clampSmall], ['clampBig', big]] as const) {
1009
+ if (!Number.isInteger(value) || value < 0 || value > PERP_FUNDING_PARAM_MAX) return `${label} must be 0..${PERP_FUNDING_PARAM_MAX}`;
1010
+ }
1011
+ const gapTicks = (market.initialMarginBps - market.maintenanceMarginBps) * 100;
1012
+ const hourlyCap = Math.floor(big / Number(PERP_FUNDING_HOURS_PER_RATE));
1013
+ if (hourlyCap > gapTicks) {
1014
+ return `clampBig / ${PERP_FUNDING_HOURS_PER_RATE} (${hourlyCap} ticks per hour) exceeds the initial - maintenance margin gap (${gapTicks} ticks)`;
1015
+ }
1016
+ return null;
1017
+ }
1018
+
1019
+ /** The largest clampBig the market's margins allow: one hour at the cap
1020
+ moves a seat by at most the initial - maintenance margin gap. */
1021
+ export function perpFundingMaxClampBig(market: Pick<PerpMarket, 'initialMarginBps' | 'maintenanceMarginBps'>): number {
1022
+ const gapTicks = Math.max(market.initialMarginBps - market.maintenanceMarginBps, 0) * 100;
1023
+ return Math.min(gapTicks * Number(PERP_FUNDING_HOURS_PER_RATE), PERP_FUNDING_PARAM_MAX);
1024
+ }
1025
+
1026
+ /** Block time (ns) of the next hour boundary: the earliest the next round runs. */
1027
+ export function perpNextFundingRoundNs(funding: Pick<PerpFunding, 'lastRoundNs'>): bigint {
1028
+ return (funding.lastRoundNs / PERP_FUNDING_ROUND_NS + 1n) * PERP_FUNDING_ROUND_NS;
1029
+ }
1030
+
1031
+ export function perpFundingRoundDue(funding: Pick<PerpFunding, 'lastRoundNs'>, nowNs: bigint): boolean {
1032
+ return nowNs / PERP_FUNDING_ROUND_NS > funding.lastRoundNs / PERP_FUNDING_ROUND_NS;
1033
+ }
1034
+
1035
+ export function perpFundingSampleDue(funding: Pick<PerpFunding, 'lastSampleNs'>, nowNs: bigint): boolean {
1036
+ return nowNs / PERP_FUNDING_SAMPLE_NS > funding.lastSampleNs / PERP_FUNDING_SAMPLE_NS;
1037
+ }
1038
+
1039
+ /** Unsettled funding credit plus carry, quote atoms * 1e6 (positive: receives). */
1040
+ export function perpSeatFundingCredit(market: Pick<PerpMarket, 'funding'>, seat: PerpFundingSeat): bigint {
1041
+ const index = market.funding?.index ?? 0n;
1042
+ const net = seat.longLots - seat.shortLots;
1043
+ return BigInt(seat.fundingCarry ?? 0) - net * (index - (seat.fundingSnapshot ?? 0n));
1044
+ }
1045
+
1046
+ export interface PerpFundingSettlement<T> {
1047
+ /** The seat as the program sees it after settling. */
1048
+ seat: T;
1049
+ /** Atoms paid to the seat (negative: charged). */
1050
+ paid: bigint;
1051
+ /** Part of a charge that neither the collateral nor the position (a
1052
+ short's entry proceeds) could cover, written off as bad debt. */
1053
+ badDebt: bigint;
1054
+ }
1055
+
1056
+ /** Settles the seat's funding exactly as the program does before it reads a
1057
+ seat's equity. Pure: returns a settled copy. */
1058
+ export function perpSettleFunding<T extends PerpFundingSeat>(
1059
+ market: Pick<PerpMarket, 'funding'>,
1060
+ seat: T,
1061
+ ): PerpFundingSettlement<T & Required<Pick<PerpSeatEntry, 'fundingSnapshot' | 'fundingCarry'>>> {
1062
+ const index = market.funding?.index ?? 0n;
1063
+ const credit = perpSeatFundingCredit(market, seat);
1064
+ const paid = floorDiv(credit, PERP_FUNDING_RATE_TICK);
1065
+ const carry = credit - paid * PERP_FUNDING_RATE_TICK;
1066
+ let quantityQuote = seat.quantityQuote + paid;
1067
+ let entryNotional = seat.entryNotional;
1068
+ let badDebt = 0n;
1069
+ if (quantityQuote < 0n) {
1070
+ /* The shortfall comes out of the open position: a long's cost basis
1071
+ rises, a short's entry proceeds fall; only what a short's entry
1072
+ cannot absorb is written off. */
1073
+ const shortfall = -quantityQuote;
1074
+ quantityQuote = 0n;
1075
+ if (seat.longLots > 0n) {
1076
+ entryNotional += shortfall;
1077
+ } else {
1078
+ const absorbed = seat.shortLots > 0n ? minBig(shortfall, entryNotional) : 0n;
1079
+ entryNotional -= absorbed;
1080
+ badDebt = shortfall - absorbed;
1081
+ }
1082
+ }
1083
+ return { seat: { ...seat, quantityQuote, entryNotional, fundingSnapshot: index, fundingCarry: Number(carry) }, paid, badDebt };
1084
+ }
1085
+
875
1086
  function affordableLots(market: PerpMarginMarket, seat: PerpMarginSeat, price: bigint, mark: bigint): bigint {
876
1087
  const perLot = perpLotInitialMargin(market, price);
877
1088
  const free = maxBig(perpFreeCollateral(market, seat, mark), 0n);
@@ -1066,6 +1277,13 @@ export function createPerpMarketRecordInstruction(args: PerpMarketRecordArgs): I
1066
1277
  };
1067
1278
  }
1068
1279
 
1280
+ /** State units a market_create transaction must request. The runtime charges
1281
+ ceil((64 + data_sz) / 4096) per new account, and market_create creates five:
1282
+ the seat arena (128640 bytes: 32), the order arena (64072 bytes: 16), the
1283
+ bids and asks cbooks (96 bytes: 1 each) and the quote vault token account
1284
+ (73 bytes: 1). Requesting fewer fails with SU_EXHAUSTED. */
1285
+ export const PERP_MARKET_CREATE_STATE_UNITS = 51;
1286
+
1069
1287
  /** The named market authority must authorize the transaction. */
1070
1288
  export function createPerpMarketCreateInstruction(args: PerpMarketCreateArgs): InstructionData {
1071
1289
  return async (context) => {
@@ -1222,6 +1440,56 @@ export function createPerpMarketSetOracleInstruction(args: PerpMarketSetOracleAr
1222
1440
  };
1223
1441
  }
1224
1442
 
1443
+ /** Permissionless funding crank: runs a due hourly round and a due premium
1444
+ sample of the record's market (the record needs the oracle feed, not a
1445
+ seat). A call with nothing due changes nothing. */
1446
+ export function createPerpFundingUpdateInstruction(args: PerpFundingUpdateArgs): InstructionData {
1447
+ return async () => {
1448
+ const payload = new FundingUpdateInstructionBuilder()
1449
+ .set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
1450
+ .set_reserved0(0)
1451
+ .set_reserved1(0)
1452
+ .build();
1453
+ return buildPerpInstruction('funding_update', payload);
1454
+ };
1455
+ }
1456
+
1457
+ /** Permissionless: settles one seat's funding, so a seat that never trades
1458
+ still pays what it owes. Several may follow one market record, and they
1459
+ may share a transaction with funding_update (no book instruction may). */
1460
+ export function createPerpSettleFundingInstruction(args: PerpSettleFundingArgs): InstructionData {
1461
+ const targetSeatIndex = assertPerpSeatIndex(args.targetSeatIndex, 'targetSeatIndex');
1462
+ return async () => {
1463
+ const payload = new SettleFundingInstructionBuilder()
1464
+ .set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
1465
+ .set_reserved0(0)
1466
+ .set_target_seat_idx(targetSeatIndex)
1467
+ .build();
1468
+ return buildPerpInstruction('settle_funding', payload);
1469
+ };
1470
+ }
1471
+
1472
+ /** Market authority only: sets the funding parameters (premiumMultiplier 0
1473
+ disables funding). Validated as the program does: see
1474
+ perpFundingParamsProblem. */
1475
+ export function createPerpMarketSetFundingInstruction(args: PerpMarketSetFundingArgs): InstructionData {
1476
+ for (const label of ['interestRate', 'clampSmall', 'clampBig', 'premiumMultiplier'] as const) assertU32(args[label], label);
1477
+ assertU64(args.impactNotional, 'impactNotional');
1478
+ return async () => {
1479
+ const payload = new MarketSetFundingInstructionBuilder()
1480
+ .set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
1481
+ .set_reserved0(0)
1482
+ .set_interest_rate(args.interestRate)
1483
+ .set_clamp_small(args.clampSmall)
1484
+ .set_clamp_big(args.clampBig)
1485
+ .set_premium_multiplier(args.premiumMultiplier)
1486
+ .set_reserved1(0)
1487
+ .set_impact_notional(args.impactNotional)
1488
+ .build();
1489
+ return buildPerpInstruction('market_set_funding', payload);
1490
+ };
1491
+ }
1492
+
1225
1493
  /** The perp entrypoint accepts several instructions concatenated in one
1226
1494
  payload; every trading instruction is preceded by a market_record. */
1227
1495
  export function concatPerpInstructions(...instructions: InstructionData[]): InstructionData {
@@ -1553,6 +1821,21 @@ export function parsePerpEvent(data: Uint8Array): ParsedPerpEvent {
1553
1821
  targetSide: liquidationSideFromValue(event.get_side()),
1554
1822
  };
1555
1823
  }
1824
+ case 'funding_round': {
1825
+ const event = payload.asFundingRound();
1826
+ if (!event) throw new Error('perp funding_round event payload is malformed');
1827
+ return {
1828
+ ...base,
1829
+ variant: 'funding_round',
1830
+ market: pubkeyViewToAddress(event.get_market()),
1831
+ rate: event.get_rate(),
1832
+ premiumSum: event.get_premium_sum(),
1833
+ sampleCount: event.get_sample_cnt(),
1834
+ indexPrice: event.get_index_price(),
1835
+ fundingIndex: joinI128(event.get_funding_index_lo(), event.get_funding_index_hi()),
1836
+ roundNs: event.get_round_ns(),
1837
+ };
1838
+ }
1556
1839
  case 'market_status':
1557
1840
  case 'exchange_initialized':
1558
1841
  case 'exchange_status':
@@ -1633,9 +1916,28 @@ function marketFromView(view: MarketAccountView): PerpMarket {
1633
1916
  liquidationFeeBps: view.get_liquidation_fee_bps(),
1634
1917
  oracleExponent: view.get_oracle_exponent(),
1635
1918
  maxMarkAgeNs: view.get_max_mark_age_ns(),
1919
+ funding: {
1920
+ index: joinI128(view.get_funding_index_lo(), view.get_funding_index_hi()),
1921
+ balance: view.get_funding_balance(),
1922
+ lastRoundNs: view.get_funding_last_round_ns(),
1923
+ lastSampleNs: view.get_funding_last_sample_ns(),
1924
+ premiumSum: view.get_funding_premium_sum(),
1925
+ sampleCount: view.get_funding_sample_cnt(),
1926
+ rate: view.get_funding_rate(),
1927
+ interestRate: view.get_funding_interest_rate(),
1928
+ clampSmall: view.get_funding_clamp_small(),
1929
+ clampBig: view.get_funding_clamp_big(),
1930
+ premiumMultiplier: view.get_funding_premium_multiplier(),
1931
+ impactNotional: view.get_funding_impact_notional(),
1932
+ },
1636
1933
  });
1637
1934
  }
1638
1935
 
1936
+ /** A signed 128-bit value stored as two little-endian u64 words. */
1937
+ function joinI128(lo: bigint, hi: bigint): bigint {
1938
+ return BigInt.asIntN(128, (hi << 64n) | lo);
1939
+ }
1940
+
1639
1941
  /** 1 <= maintenance < initial <= 10000, liquidationFeeBps <= 10000, markNum and markDen > 0. */
1640
1942
  function assertPerpMarketHeader(market: PerpMarket): PerpMarket {
1641
1943
  const { initialMarginBps: initial, maintenanceMarginBps: maintenance, liquidationFeeBps: fee, markNum, markDen } = market;
@@ -1672,6 +1974,8 @@ function seatEntryFromView(view: SeatEntryView, seatIndex: number): PerpSeatEntr
1672
1974
  entryNotional: view.get_entry_notional(),
1673
1975
  openBidNotional: view.get_open_bid_notional(),
1674
1976
  openAskNotional: view.get_open_ask_notional(),
1977
+ fundingSnapshot: joinI128(view.get_funding_snapshot_lo(), view.get_funding_snapshot_hi()),
1978
+ fundingCarry: view.get_funding_carry(),
1675
1979
  };
1676
1980
  }
1677
1981
 
@@ -1787,6 +2091,15 @@ async function sha256(...parts: Uint8Array[]): Promise<Uint8Array> {
1787
2091
  return new Uint8Array(digest);
1788
2092
  }
1789
2093
 
2094
+ function floorDiv(numerator: bigint, denominator: bigint): bigint {
2095
+ const quotient = numerator / denominator;
2096
+ return numerator % denominator !== 0n && numerator < 0n !== denominator < 0n ? quotient - 1n : quotient;
2097
+ }
2098
+
2099
+ function clampBig(value: bigint, low: bigint, high: bigint): bigint {
2100
+ return value < low ? low : value > high ? high : value;
2101
+ }
2102
+
1790
2103
  function minBig(a: bigint, b: bigint): bigint {
1791
2104
  return a < b ? a : b;
1792
2105
  }