@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.
Files changed (123) hide show
  1. package/README.md +9 -0
  2. package/dist/abi-manager/index.cjs +154 -33
  3. package/dist/abi-manager/index.cjs.map +1 -1
  4. package/dist/abi-manager/index.d.cts +1 -1
  5. package/dist/abi-manager/index.d.ts +1 -1
  6. package/dist/abi-manager/index.js +3 -2
  7. package/dist/amm/index.cjs +81 -47
  8. package/dist/amm/index.cjs.map +1 -1
  9. package/dist/amm/index.js +2 -3
  10. package/dist/amm/index.js.map +1 -1
  11. package/dist/bootstrap-addresses/index.cjs +58 -20
  12. package/dist/bootstrap-addresses/index.cjs.map +1 -1
  13. package/dist/bootstrap-addresses/index.d.cts +38 -19
  14. package/dist/bootstrap-addresses/index.d.ts +38 -19
  15. package/dist/bootstrap-addresses/index.js +2 -3
  16. package/dist/{chunk-6IC6CO5S.js → chunk-2NNQJFKS.js} +5 -4
  17. package/dist/chunk-2NNQJFKS.js.map +1 -0
  18. package/dist/chunk-4F54VFIH.js +58 -0
  19. package/dist/chunk-4F54VFIH.js.map +1 -0
  20. package/dist/{chunk-BNYDH4ZP.js → chunk-A2BWZE2D.js} +12 -10
  21. package/dist/chunk-A2BWZE2D.js.map +1 -0
  22. package/dist/{chunk-7DRJVAYI.js → chunk-A44ZPXY6.js} +5 -58
  23. package/dist/chunk-A44ZPXY6.js.map +1 -0
  24. package/dist/{chunk-YX7BLFQZ.js → chunk-JHINXDSG.js} +44 -5
  25. package/dist/chunk-JHINXDSG.js.map +1 -0
  26. package/dist/chunk-QGOAPK5X.js +174 -0
  27. package/dist/chunk-QGOAPK5X.js.map +1 -0
  28. package/dist/chunk-S3UTJHRO.js +77 -0
  29. package/dist/chunk-S3UTJHRO.js.map +1 -0
  30. package/dist/{chunk-CYG4PB65.js → chunk-ZOFTRAAH.js} +4 -4
  31. package/dist/{chunk-CYG4PB65.js.map → chunk-ZOFTRAAH.js.map} +1 -1
  32. package/dist/{chunk-ZHF2PH5H.js → chunk-ZP7A3GHV.js} +3 -4
  33. package/dist/chunk-ZP7A3GHV.js.map +1 -0
  34. package/dist/clob/index.cjs +380 -322
  35. package/dist/clob/index.cjs.map +1 -1
  36. package/dist/clob/index.d.cts +4 -3
  37. package/dist/clob/index.d.ts +4 -3
  38. package/dist/clob/index.js +36 -198
  39. package/dist/clob/index.js.map +1 -1
  40. package/dist/deploy/index.cjs +241 -169
  41. package/dist/deploy/index.cjs.map +1 -1
  42. package/dist/deploy/index.d.cts +5 -0
  43. package/dist/deploy/index.d.ts +5 -0
  44. package/dist/deploy/index.js +66 -37
  45. package/dist/deploy/index.js.map +1 -1
  46. package/dist/manager/index.cjs +15 -2
  47. package/dist/manager/index.cjs.map +1 -1
  48. package/dist/manager/index.d.cts +6 -79
  49. package/dist/manager/index.d.ts +6 -79
  50. package/dist/manager/index.js +2 -3
  51. package/dist/multicall/index.cjs +57 -23
  52. package/dist/multicall/index.cjs.map +1 -1
  53. package/dist/multicall/index.js +3 -4
  54. package/dist/oracle/index.cjs +64 -30
  55. package/dist/oracle/index.cjs.map +1 -1
  56. package/dist/oracle/index.d.cts +3 -39
  57. package/dist/oracle/index.d.ts +3 -39
  58. package/dist/oracle/index.js +2 -3
  59. package/dist/oracle/index.js.map +1 -1
  60. package/dist/orderbook-CEYM4N_S.d.cts +5 -0
  61. package/dist/orderbook-CEYM4N_S.d.ts +5 -0
  62. package/dist/passkey-manager/index.cjs +52 -18
  63. package/dist/passkey-manager/index.cjs.map +1 -1
  64. package/dist/passkey-manager/index.js +2 -3
  65. package/dist/passkey-manager/index.js.map +1 -1
  66. package/dist/perp/index.cjs +16750 -0
  67. package/dist/perp/index.cjs.map +1 -0
  68. package/dist/perp/index.d.cts +4577 -0
  69. package/dist/perp/index.d.ts +4577 -0
  70. package/dist/perp/index.js +16244 -0
  71. package/dist/perp/index.js.map +1 -0
  72. package/dist/token/index.js +2 -1
  73. package/dist/types-5XmDprcB.d.ts +81 -0
  74. package/dist/types-Cpi7Ibs2.d.cts +81 -0
  75. package/dist/types-T4cL02K7.d.cts +39 -0
  76. package/dist/types-T4cL02K7.d.ts +39 -0
  77. package/dist/uploader/index.cjs +46 -8
  78. package/dist/uploader/index.cjs.map +1 -1
  79. package/dist/uploader/index.d.cts +2 -1
  80. package/dist/uploader/index.d.ts +2 -1
  81. package/dist/uploader/index.js +2 -2
  82. package/package.json +7 -2
  83. package/src/abi-manager/constants.ts +2 -1
  84. package/src/abi-manager/index.test.ts +2 -2
  85. package/src/bootstrap-addresses/index.test.ts +70 -18
  86. package/src/bootstrap-addresses/index.ts +56 -19
  87. package/src/clob/index.ts +67 -201
  88. package/src/deploy/accounts.ts +7 -3
  89. package/src/deploy/chain.ts +1 -1
  90. package/src/deploy/constants.ts +3 -4
  91. package/src/deploy/deploy.test.ts +11 -10
  92. package/src/deploy/inspection.ts +3 -2
  93. package/src/deploy/types.ts +5 -0
  94. package/src/deploy/uploader.ts +5 -4
  95. package/src/deploy/workflows.test.ts +74 -5
  96. package/src/deploy/workflows.ts +55 -17
  97. package/src/manager/constants.ts +14 -2
  98. package/src/manager/derivation.ts +3 -3
  99. package/src/manager/index.test.ts +3 -3
  100. package/src/manager/index.ts +3 -0
  101. package/src/manager/types.ts +1 -1
  102. package/src/multicall/index.test.ts +1 -1
  103. package/src/passkey-manager/validate.test.ts +1 -1
  104. package/src/perp/abi/thru/common/primitives/types.ts +2428 -0
  105. package/src/perp/abi/thru/program/perp/types.ts +16813 -0
  106. package/src/perp/index.test.ts +822 -0
  107. package/src/perp/index.ts +1793 -0
  108. package/src/uploader/constants.ts +5 -4
  109. package/src/uploader/index.test.ts +2 -2
  110. package/src/uploader/index.ts +1 -0
  111. package/src/utils/helpers.ts +1 -1
  112. package/src/utils/orderbook.test.ts +86 -0
  113. package/src/utils/orderbook.ts +214 -0
  114. package/tsup.config.ts +1 -0
  115. package/dist/chunk-6IC6CO5S.js.map +0 -1
  116. package/dist/chunk-7DHFYBRW.js +0 -51
  117. package/dist/chunk-7DHFYBRW.js.map +0 -1
  118. package/dist/chunk-7DRJVAYI.js.map +0 -1
  119. package/dist/chunk-BNYDH4ZP.js.map +0 -1
  120. package/dist/chunk-VNTPD4AR.js +0 -37
  121. package/dist/chunk-VNTPD4AR.js.map +0 -1
  122. package/dist/chunk-YX7BLFQZ.js.map +0 -1
  123. package/dist/chunk-ZHF2PH5H.js.map +0 -1
package/src/clob/index.ts CHANGED
@@ -1,12 +1,51 @@
1
1
  import { Pubkey, deriveProgramAddress } from '@thru/sdk';
2
- import { encodeAddress } from '@thru/sdk/helpers';
3
2
  import type { Account } from '@thru/sdk';
4
3
  import { BOOTSTRAP_PROGRAM_ADDRESSES } from '../bootstrap-addresses';
4
+ import { accountData, accountIndex } from '../utils/helpers';
5
+ import {
6
+ CLIENT_ID_SIZE,
7
+ EVENT_REMOVE_REASON_EVICTED,
8
+ EVENT_REMOVE_REASON_EXPIRED,
9
+ EVENT_REMOVE_REASON_FILLED,
10
+ EVENT_REMOVE_REASON_USER,
11
+ EVENT_SIDE_BUY,
12
+ EVENT_SIDE_SELL,
13
+ ORDER_FLAG_BUY,
14
+ ORDER_FLAG_HAS_CLIENT_ID,
15
+ ORDER_TYPE_ALO,
16
+ ORDER_TYPE_FOK,
17
+ ORDER_TYPE_GTC,
18
+ ORDER_TYPE_IOC,
19
+ ORDER_TYPE_MTL,
20
+ STATUS_FLAG_DEPOSITS_FROZEN,
21
+ STATUS_FLAG_MASK,
22
+ STATUS_FLAG_PAUSED,
23
+ STATUS_FLAG_POST_ONLY,
24
+ STATUS_FLAG_WITHDRAWALS_FROZEN,
25
+ assertClientId,
26
+ assertStatusFlags,
27
+ assertU64,
28
+ assertU8,
29
+ buildModifyOrderMetadata,
30
+ bitField,
31
+ bytesFromView,
32
+ cbookLevelFromView,
33
+ eventSideFromValue,
34
+ fixedSeed,
35
+ groupByPrice,
36
+ optionalAccountIndex,
37
+ orderFlags,
38
+ orderTypeFromValue,
39
+ pubkeyViewToAddress,
40
+ removalReasonFromValue,
41
+ type OrderRemovalReason,
42
+ type OrderSide,
43
+ type OrderType,
44
+ } from '../utils/orderbook';
5
45
  import {
6
46
  ArenaHeader,
7
47
  CbookAccount,
8
48
  CbookHeader,
9
- CbookLevel,
10
49
  ClobEvent,
11
50
  ClobInstructionBuilder,
12
51
  CreateOrderEntryInstructionBuilder,
@@ -139,35 +178,33 @@ export const CLOB_EVENT_EXCHANGE_STATUS = 12;
139
178
  export const CLOB_EVENT_EXCHANGE_ADMIN = 13;
140
179
  export const CLOB_EVENT_MARKET_EXCHANGE_STATUS = 14;
141
180
 
142
- export const CLOB_EVENT_SIDE_BUY = 0;
143
- export const CLOB_EVENT_SIDE_SELL = 1;
181
+ /* Book, flag and event encodings shared with the perp program (utils/orderbook). */
182
+ export const CLOB_EVENT_SIDE_BUY = EVENT_SIDE_BUY;
183
+ export const CLOB_EVENT_SIDE_SELL = EVENT_SIDE_SELL;
144
184
  export const CLOB_EVENT_TOKEN_SIDE_BASE = 0;
145
185
  export const CLOB_EVENT_TOKEN_SIDE_QUOTE = 1;
146
- export const CLOB_EVENT_REMOVE_REASON_FILLED = 0;
147
- export const CLOB_EVENT_REMOVE_REASON_EXPIRED = 1;
148
- export const CLOB_EVENT_REMOVE_REASON_EVICTED = 2;
149
- export const CLOB_EVENT_REMOVE_REASON_USER = 3;
150
-
151
- export const CLOB_STATUS_FLAG_PAUSED = 1 << 0;
152
- export const CLOB_STATUS_FLAG_POST_ONLY = 1 << 1;
153
- export const CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN = 1 << 2;
154
- export const CLOB_STATUS_FLAG_DEPOSITS_FROZEN = 1 << 3;
155
- export const CLOB_STATUS_FLAG_MASK =
156
- CLOB_STATUS_FLAG_PAUSED |
157
- CLOB_STATUS_FLAG_POST_ONLY |
158
- CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN |
159
- CLOB_STATUS_FLAG_DEPOSITS_FROZEN;
186
+ export const CLOB_EVENT_REMOVE_REASON_FILLED = EVENT_REMOVE_REASON_FILLED;
187
+ export const CLOB_EVENT_REMOVE_REASON_EXPIRED = EVENT_REMOVE_REASON_EXPIRED;
188
+ export const CLOB_EVENT_REMOVE_REASON_EVICTED = EVENT_REMOVE_REASON_EVICTED;
189
+ export const CLOB_EVENT_REMOVE_REASON_USER = EVENT_REMOVE_REASON_USER;
190
+
191
+ export const CLOB_STATUS_FLAG_PAUSED = STATUS_FLAG_PAUSED;
192
+ export const CLOB_STATUS_FLAG_POST_ONLY = STATUS_FLAG_POST_ONLY;
193
+ export const CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN = STATUS_FLAG_WITHDRAWALS_FROZEN;
194
+ export const CLOB_STATUS_FLAG_DEPOSITS_FROZEN = STATUS_FLAG_DEPOSITS_FROZEN;
195
+ export const CLOB_STATUS_FLAG_MASK = STATUS_FLAG_MASK;
196
+
160
197
 
161
198
  export const CLOB_PROGRAM_ADDRESS = BOOTSTRAP_PROGRAM_ADDRESSES.clob;
162
199
 
163
- export const CLOB_ORDER_TYPE_GTC = 0;
164
- export const CLOB_ORDER_TYPE_MTL = 1;
165
- export const CLOB_ORDER_TYPE_ALO = 2;
166
- export const CLOB_ORDER_TYPE_IOC = 3;
167
- export const CLOB_ORDER_TYPE_FOK = 4;
200
+ export const CLOB_ORDER_TYPE_GTC = ORDER_TYPE_GTC;
201
+ export const CLOB_ORDER_TYPE_MTL = ORDER_TYPE_MTL;
202
+ export const CLOB_ORDER_TYPE_ALO = ORDER_TYPE_ALO;
203
+ export const CLOB_ORDER_TYPE_IOC = ORDER_TYPE_IOC;
204
+ export const CLOB_ORDER_TYPE_FOK = ORDER_TYPE_FOK;
168
205
 
169
- export const CLOB_ORDER_FLAG_BUY = 1 << 0;
170
- export const CLOB_ORDER_FLAG_HAS_CLIENT_ID = 1 << 6;
206
+ export const CLOB_ORDER_FLAG_BUY = ORDER_FLAG_BUY;
207
+ export const CLOB_ORDER_FLAG_HAS_CLIENT_ID = ORDER_FLAG_HAS_CLIENT_ID;
171
208
  export const CLOB_MODIFY_FLAG_FAIL_IF_OUT_OF_RANGE = 1 << 0;
172
209
  export const CLOB_MODIFY_FLAG_HAS_CLIENT_ID = 1 << 1;
173
210
  export const CLOB_MODIFY_FLAG_HAS_ORDER_ID = 1 << 2;
@@ -188,7 +225,7 @@ export const CLOB_CBOOK_LEVEL_SIZE = 8;
188
225
  export const CLOB_CBOOK_MAX_SIZE = ((1 << 24) - CLOB_CBOOK_HEADER_SIZE) / CLOB_CBOOK_LEVEL_SIZE;
189
226
  export const CLOB_CBOOK_EMPTY_PRICE_IN_TICKS = (1n << 64n) - 1n;
190
227
  export const CLOB_CBOOK_MAX_PRICE_IN_TICKS = CLOB_CBOOK_EMPTY_PRICE_IN_TICKS - 2n - BigInt(CLOB_CBOOK_MAX_SIZE);
191
- export const CLOB_CLIENT_ID_SIZE = 16;
228
+ export const CLOB_CLIENT_ID_SIZE = CLIENT_ID_SIZE;
192
229
  export const CLOB_SEATLESS_SEAT_IDX = 1;
193
230
  export const CLOB_NULL_INDEX = 0xfffff;
194
231
 
@@ -208,8 +245,8 @@ type ClobInstructionVariant =
208
245
  | 'exchange_recover_admin'
209
246
  | 'market_set_exchange_status';
210
247
 
211
- export type ClobOrderSide = 'buy' | 'sell';
212
- export type ClobOrderType = 'gtc' | 'mtl' | 'alo' | 'ioc' | 'fok';
248
+ export type ClobOrderSide = OrderSide;
249
+ export type ClobOrderType = OrderType;
213
250
 
214
251
  export type AccountLookupContext = {
215
252
  getAccountIndex: (pubkey: Uint8Array) => number;
@@ -422,7 +459,8 @@ export interface ClobOrderBookSnapshot {
422
459
 
423
460
 
424
461
  export type ClobTokenSide = 'base' | 'quote';
425
- export type ClobOrderRemovalReason = 'filled' | 'expired' | 'evicted' | 'user';
462
+ export type ClobOrderRemovalReason = OrderRemovalReason;
463
+
426
464
 
427
465
  export interface ParsedClobEventBase {
428
466
  eventType: bigint;
@@ -1114,20 +1152,6 @@ export function encodeOrderFlags(args: {
1114
1152
  return orderFlags(args);
1115
1153
  }
1116
1154
 
1117
- function buildModifyOrderMetadata(args: ModifyOrderArgs): Uint8Array {
1118
- const metadata = new Uint8Array((args.clientId ? CLOB_CLIENT_ID_SIZE : 0) + (args.orderId !== undefined ? 8 : 0));
1119
- let offset = 0;
1120
- if (args.clientId) {
1121
- metadata.set(assertClientId(args.clientId), offset);
1122
- offset += CLOB_CLIENT_ID_SIZE;
1123
- }
1124
- if (args.orderId !== undefined) {
1125
- assertU64(args.orderId, 'orderId');
1126
- new DataView(metadata.buffer).setBigUint64(offset, args.orderId, true);
1127
- }
1128
- return metadata;
1129
- }
1130
-
1131
1155
  function createTokenTransferInstruction(
1132
1156
  variant: 'token_deposit' | 'token_withdraw',
1133
1157
  args: TokenTransferArgs
@@ -1153,31 +1177,6 @@ function buildClobInstruction(variant: ClobInstructionVariant, payload: Uint8Arr
1153
1177
  return builder.build();
1154
1178
  }
1155
1179
 
1156
- function orderFlags(args: {
1157
- side: ClobOrderSide;
1158
- orderType?: ClobOrderType;
1159
- clientId?: Uint8Array;
1160
- discardAfterMatch?: boolean;
1161
- failIfOutsideBook?: boolean;
1162
- }): number {
1163
- let flags = args.side === 'buy' ? CLOB_ORDER_FLAG_BUY : 0;
1164
- flags |= orderTypeValue(args.orderType ?? 'gtc') << 1;
1165
- if (args.discardAfterMatch) flags |= 1 << 4;
1166
- if (args.failIfOutsideBook) flags |= 1 << 5;
1167
- if (args.clientId) flags |= CLOB_ORDER_FLAG_HAS_CLIENT_ID;
1168
- return flags;
1169
- }
1170
-
1171
- function orderTypeValue(orderType: ClobOrderType): number {
1172
- switch (orderType) {
1173
- case 'gtc': return CLOB_ORDER_TYPE_GTC;
1174
- case 'mtl': return CLOB_ORDER_TYPE_MTL;
1175
- case 'alo': return CLOB_ORDER_TYPE_ALO;
1176
- case 'ioc': return CLOB_ORDER_TYPE_IOC;
1177
- case 'fok': return CLOB_ORDER_TYPE_FOK;
1178
- }
1179
- }
1180
-
1181
1180
  function marketFromView(view: MarketAccountView): ClobMarket {
1182
1181
  return {
1183
1182
  magic: view.get_magic(),
@@ -1239,14 +1238,6 @@ function orderEntryFromView(view: OrderEntryView, orderEntryIndex: number): Clob
1239
1238
  };
1240
1239
  }
1241
1240
 
1242
- function cbookLevelFromView(view: CbookLevel, levelIndex: number): ClobCbookLevel {
1243
- return {
1244
- levelIndex,
1245
- headOrderEntryIndex: view.get_head_entry_idx(),
1246
- tailOrderEntryIndex: view.get_tail_entry_idx(),
1247
- };
1248
- }
1249
-
1250
1241
  function normalizeBookOrder(
1251
1242
  order: ClobOrderBookOrder | ClobOrderEntry,
1252
1243
  side: ClobOrderSide,
@@ -1266,30 +1257,6 @@ function normalizeBookOrder(
1266
1257
  };
1267
1258
  }
1268
1259
 
1269
- function groupByPrice(orders: ClobOrderBookOrder[], side: ClobOrderSide): ClobOrderBookLevel[] {
1270
- const levels = new Map<bigint, ClobOrderBookLevel>();
1271
- for (const order of orders) {
1272
- if (order.quantityInLots === 0n) continue;
1273
- const existing = levels.get(order.priceInTicks);
1274
- if (existing) {
1275
- existing.quantityInLots += order.quantityInLots;
1276
- existing.orders.push(order);
1277
- } else {
1278
- levels.set(order.priceInTicks, {
1279
- side,
1280
- priceInTicks: order.priceInTicks,
1281
- quantityInLots: order.quantityInLots,
1282
- orders: [order],
1283
- });
1284
- }
1285
- }
1286
- return [...levels.values()].sort((a, b) => {
1287
- if (a.priceInTicks === b.priceInTicks) return 0;
1288
- const asc = a.priceInTicks < b.priceInTicks ? -1 : 1;
1289
- return side === 'buy' ? -asc : asc;
1290
- });
1291
- }
1292
-
1293
1260
  function priceForLevel(
1294
1261
  levelIndex: number,
1295
1262
  side: ClobOrderSide,
@@ -1327,44 +1294,6 @@ function priceForCbookLevel(levelIndex: number, side: ClobOrderSide, cbook: Clob
1327
1294
  return side === 'buy' ? CLOB_CBOOK_MAX_PRICE_IN_TICKS - cbookPriceInTicks : cbookPriceInTicks;
1328
1295
  }
1329
1296
 
1330
- function accountData(accountOrData: Account | Uint8Array, label: string): Uint8Array {
1331
- const data = accountOrData instanceof Uint8Array ? accountOrData : accountOrData.data?.data;
1332
- if (!data) throw new Error(`${label} data is missing`);
1333
- return data;
1334
- }
1335
-
1336
- function fixedSeed(value: string): Uint8Array {
1337
- const bytes = new TextEncoder().encode(value);
1338
- if (bytes.length > 32) throw new Error('seed cannot exceed 32 bytes');
1339
- const seed = new Uint8Array(32);
1340
- seed.set(bytes);
1341
- return seed;
1342
- }
1343
-
1344
- function optionalAccountIndex(context: AccountLookupContext, pubkey?: Uint8Array): number {
1345
- return pubkey ? accountIndex(context, pubkey) : 0xffff;
1346
- }
1347
-
1348
- function accountIndex(context: AccountLookupContext, pubkey: Uint8Array): number {
1349
- const index = context.getAccountIndex(pubkey);
1350
- return assertU16(index, 'account index');
1351
- }
1352
-
1353
- function assertU8(value: number, label: string): number {
1354
- if (!Number.isInteger(value) || value < 0 || value > 0xff) {
1355
- throw new Error(`${label} must be an integer between 0 and 255`);
1356
- }
1357
- return value;
1358
- }
1359
-
1360
- function assertStatusFlags(value: number): number {
1361
- const flags = assertU8(value, 'statusFlags');
1362
- if ((flags & ~CLOB_STATUS_FLAG_MASK) !== 0) {
1363
- throw new Error("statusFlags may only contain bits in mask 0x" + CLOB_STATUS_FLAG_MASK.toString(16));
1364
- }
1365
- return flags;
1366
- }
1367
-
1368
1297
  export function effectiveClobStatusFlags(
1369
1298
  exchangeStatusFlags: number,
1370
1299
  market: Pick<ClobMarket, 'statusFlags' | 'exchangeStatusFlags'>
@@ -1374,13 +1303,6 @@ export function effectiveClobStatusFlags(
1374
1303
  assertStatusFlags(market.exchangeStatusFlags);
1375
1304
  }
1376
1305
 
1377
- function assertU16(value: number, label: string): number {
1378
- if (!Number.isInteger(value) || value < 0 || value > 0xffff) {
1379
- throw new Error(`${label} must be an integer between 0 and 65535`);
1380
- }
1381
- return value;
1382
- }
1383
-
1384
1306
  export function assertClobActiveSeatIndex(value: number, label = 'seatIndex'): number {
1385
1307
  if (!Number.isSafeInteger(value) || value < 2 || value >= CLOB_NULL_INDEX) {
1386
1308
  throw new Error(`${label} must be an integer between 2 and ${CLOB_NULL_INDEX - 1}`);
@@ -1388,68 +1310,12 @@ export function assertClobActiveSeatIndex(value: number, label = 'seatIndex'): n
1388
1310
  return value;
1389
1311
  }
1390
1312
 
1391
- function assertU64(value: bigint, label: string): void {
1392
- if (value < 0n || value > 0xffffffffffffffffn) {
1393
- throw new Error(`${label} must be between 0 and 18446744073709551615`);
1394
- }
1395
- }
1396
-
1397
- function assertClientId(value: Uint8Array): Uint8Array {
1398
- if (value.length !== CLOB_CLIENT_ID_SIZE) {
1399
- throw new Error(`clientId must be ${CLOB_CLIENT_ID_SIZE} bytes`);
1400
- }
1401
- return value;
1402
- }
1403
-
1404
- function bitField(value: bigint, begin: bigint, end: bigint): number {
1405
- const mask = (1n << (end - begin)) - 1n;
1406
- return Number((value >> begin) & mask);
1407
- }
1408
-
1409
- function eventSideFromValue(value: number): ClobOrderSide {
1410
- if (value === CLOB_EVENT_SIDE_BUY) return 'buy';
1411
- if (value === CLOB_EVENT_SIDE_SELL) return 'sell';
1412
- throw new Error(`unknown CLOB event side: ${value}`);
1413
- }
1414
-
1415
1313
  function tokenSideFromValue(value: number): ClobTokenSide {
1416
1314
  if (value === CLOB_EVENT_TOKEN_SIDE_BASE) return 'base';
1417
1315
  if (value === CLOB_EVENT_TOKEN_SIDE_QUOTE) return 'quote';
1418
1316
  throw new Error(`unknown CLOB token side: ${value}`);
1419
1317
  }
1420
1318
 
1421
- function removalReasonFromValue(value: number): ClobOrderRemovalReason {
1422
- switch (value) {
1423
- case CLOB_EVENT_REMOVE_REASON_FILLED: return 'filled';
1424
- case CLOB_EVENT_REMOVE_REASON_EXPIRED: return 'expired';
1425
- case CLOB_EVENT_REMOVE_REASON_EVICTED: return 'evicted';
1426
- case CLOB_EVENT_REMOVE_REASON_USER: return 'user';
1427
- default: throw new Error(`unknown CLOB removal reason: ${value}`);
1428
- }
1429
- }
1430
-
1431
- function orderTypeFromValue(value: number): ClobOrderType {
1432
- switch (value) {
1433
- case CLOB_ORDER_TYPE_GTC: return 'gtc';
1434
- case CLOB_ORDER_TYPE_MTL: return 'mtl';
1435
- case CLOB_ORDER_TYPE_ALO: return 'alo';
1436
- case CLOB_ORDER_TYPE_IOC: return 'ioc';
1437
- case CLOB_ORDER_TYPE_FOK: return 'fok';
1438
- default: throw new Error(`unknown CLOB order type: ${value}`);
1439
- }
1440
- }
1441
-
1442
- function pubkeyViewToAddress(pubkey: unknown): string {
1443
- return encodeAddress(bytesFromView(pubkey));
1444
- }
1445
-
1446
- function bytesFromView(value: unknown): Uint8Array {
1447
- const buffer = (value as { buffer?: Uint8Array }).buffer;
1448
- if (buffer instanceof Uint8Array) return new Uint8Array(buffer);
1449
- if (value instanceof Pubkey) return value.toBytes();
1450
- throw new Error('generated view did not expose a byte buffer');
1451
- }
1452
-
1453
1319
  export * from './exchange';
1454
1320
  export * from './exchange-client';
1455
1321
  export * from './price';
@@ -79,15 +79,19 @@ function assertOwner(account: Account, owner: string, label: string): void {
79
79
  export function assertManagedProgramAccount(
80
80
  account: Account,
81
81
  label = "managed program account",
82
+ managerProgramAddress = MANAGER_PROGRAM_ADDRESS,
82
83
  ): void {
83
- assertOwner(account, MANAGER_PROGRAM_ADDRESS, label);
84
+ assertOwner(account, managerProgramAddress, label);
84
85
  if (!account.meta?.flags.isProgram) {
85
86
  throw new DeployError("VERIFICATION_FAILED", `${label} is not executable`);
86
87
  }
87
88
  }
88
89
 
89
- export function parseManagerMeta(account: Account): ParsedManagerMeta {
90
- assertOwner(account, MANAGER_PROGRAM_ADDRESS, "program metadata account");
90
+ export function parseManagerMeta(
91
+ account: Account,
92
+ managerProgramAddress = MANAGER_PROGRAM_ADDRESS,
93
+ ): ParsedManagerMeta {
94
+ assertOwner(account, managerProgramAddress, "program metadata account");
91
95
  try {
92
96
  const parsed = parseManagerProgramMeta(account);
93
97
  return {
@@ -83,7 +83,7 @@ export async function submitTransaction(
83
83
  header: {
84
84
  fee: 0n,
85
85
  computeUnits: transaction.computeUnits ?? 500_000_000,
86
- stateUnits: transaction.stateUnits ?? 5_000,
86
+ stateUnits: transaction.stateUnits ?? 1,
87
87
  memoryUnits: transaction.memoryUnits ?? 5_000,
88
88
  expiryAfter: transaction.expiryAfter ?? 10_000,
89
89
  },
@@ -1,4 +1,4 @@
1
- import { GENESIS_MULTICALL_PROGRAM_ADDRESS } from "../multicall";
1
+ import { MULTICALL_PROGRAM_ADDRESS } from "../multicall";
2
2
 
3
3
  export {
4
4
  MANAGER_META_SIZE,
@@ -13,10 +13,9 @@ export {
13
13
  ABI_STATE_FINALIZED,
14
14
  ABI_STATE_OPEN,
15
15
  } from "../abi-manager";
16
- /** Genesis Multicall remains a deployment dependency because managed
17
- * Multicall cannot be used to deploy itself. */
16
+ /** Bootstrap installs this binary through Manager without an ABI first. */
18
17
  export const DEPLOYMENT_MULTICALL_PROGRAM_ADDRESS =
19
- GENESIS_MULTICALL_PROGRAM_ADDRESS;
18
+ MULTICALL_PROGRAM_ADDRESS;
20
19
  export {
21
20
  UPLOADER_DEFAULT_CHUNK_SIZE as DEFAULT_CHUNK_SIZE,
22
21
  UPLOADER_MAX_CHUNK_SIZE as MAX_CHUNK_SIZE,
@@ -3,6 +3,7 @@ import { encodeAddress } from "@thru/sdk/helpers";
3
3
  import { describe, expect, it, vi } from "vitest";
4
4
  import { deriveProgramABIAddresses } from "../abi-manager";
5
5
  import { deriveManagedProgramAddresses } from "../manager";
6
+ import { BOOTSTRAP_PROGRAM_ADDRESSES } from "../bootstrap-addresses";
6
7
  import { deriveUploadAddresses } from "../uploader";
7
8
  import {
8
9
  parseABIAccount,
@@ -53,18 +54,18 @@ describe("deployment address derivation", () => {
53
54
  const program = deriveManagedProgramAddresses("nft");
54
55
  expect(program).toMatchObject({
55
56
  programMetaAccountAddress:
56
- "ta00Efqv-BVcX3MsYbqO9JN2arQVJEMg3xqQF2iy0H1TGV",
57
- programAccountAddress: "taAFaJ4ctkbuhYBl2FX6tmXGJZQgShIXt6TPrMw4-GOsv4",
57
+ "taJM9c0C5t2kaaNv_PyeVn6khHuwc-zeN39MUTW_yghOBU",
58
+ programAccountAddress: "tak_0Jtlh0y2hPHscfXkS1eXuEpPUB35xh5KqT5A2fR2ZE",
58
59
  });
59
60
  expect(
60
61
  deriveProgramABIAddresses(program.programAccountAddress),
61
62
  ).toMatchObject({
62
- abiMetaAccountAddress: "taTRXKKLkeKvK_XMkdqbMzcqR0cUY20PBwaluN8UKvkkGF",
63
- abiAccountAddress: "takDA1V6UYKs86PsY7tQjlGOeFkQhmaVCehzy1TylM0ufs",
63
+ abiMetaAccountAddress: "taUkpVSe_kjePfi1VuPEtdsOz8kZZy2tI6DABDju_W4arS",
64
+ abiAccountAddress: "taeecO6WARCvCL_fJz9WnGNlrQ1r-96I79A6m-en4krTNe",
64
65
  });
65
66
  expect(deriveUploadAddresses("nft_temporary")).toMatchObject({
66
- metaAccountAddress: "taF70vdExq-vx8VUoZBCcNayNbAsNktsrFd34CrRRa-U4_",
67
- bufferAccountAddress: "ta3qmTeqrBsvHKCX60S7ZZqfuOi-X59-FTeZ1UXCK3GtdX",
67
+ metaAccountAddress: "ta1WUSEixlsGSJ6qBFdur6lzwO_xOF0x1y70CiI_ju7Ifc",
68
+ bufferAccountAddress: "taIx7ja7eblEGbwJOrS4a1kikDTuQg_nYvu-2kKfC6aCIx",
68
69
  });
69
70
  });
70
71
 
@@ -80,11 +81,11 @@ describe("deployment address derivation", () => {
80
81
  });
81
82
 
82
83
  it("uses canonical built-in addresses", () => {
83
- expect(UPLOADER_PROGRAM_ADDRESS).toBe(address(2));
84
- expect(MANAGER_PROGRAM_ADDRESS).toBe(address(4));
85
- expect(DEPLOYMENT_MULTICALL_PROGRAM_ADDRESS).toBe(address(9));
84
+ expect(UPLOADER_PROGRAM_ADDRESS).toBe("taUPLMH5QYOAT4ktwQeO7DXAEKtqBhYehalNGf5BJFQDYq");
85
+ expect(MANAGER_PROGRAM_ADDRESS).toBe("taMGRmPoSTkUtF6UlmCIq58K8OYsnXshOMPdobxxHytqmu");
86
+ expect(DEPLOYMENT_MULTICALL_PROGRAM_ADDRESS).toBe(BOOTSTRAP_PROGRAM_ADDRESSES.multicall);
86
87
  expect(ABI_MANAGER_PROGRAM_ADDRESS).toBe(
87
- "taAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACrG7",
88
+ BOOTSTRAP_PROGRAM_ADDRESSES.abi_manager,
88
89
  );
89
90
  });
90
91
  });
@@ -37,6 +37,7 @@ export async function inspectProgramDeployment(
37
37
  const programAddresses = deriveManagedProgramAddresses(
38
38
  request.seed,
39
39
  ephemeral,
40
+ request.managerProgramAddress,
40
41
  );
41
42
  const abiAddresses = deriveProgramABIAddresses(
42
43
  programAddresses.programAccountAddress,
@@ -66,8 +67,8 @@ export async function inspectProgramDeployment(
66
67
  if (!metadataAccount || !programAccount) {
67
68
  program = absentPair(!!metadataAccount, !!programAccount);
68
69
  } else {
69
- const metadata = parseManagerMeta(metadataAccount);
70
- assertManagedProgramAccount(programAccount);
70
+ const metadata = parseManagerMeta(metadataAccount, request.managerProgramAddress);
71
+ assertManagedProgramAccount(programAccount, undefined, request.managerProgramAddress);
71
72
  const authorityAddress = Pubkey.from(metadata.authority).toThruFmt();
72
73
  if (request.authorityAddress !== undefined) {
73
74
  let expectedAuthority: Uint8Array;
@@ -32,6 +32,9 @@ export interface DeployProgressEvent {
32
32
 
33
33
  export interface DeploymentRequestBase {
34
34
  seed: string;
35
+ /** Parent Manager executable. Use root to upgrade the managed main Manager.
36
+ * Non-default parents support program binaries, not official ABI publication. */
37
+ managerProgramAddress?: string;
35
38
  signer: DeploymentSigner;
36
39
  client?: Thru;
37
40
  ephemeral?: boolean;
@@ -124,6 +127,8 @@ export type UpgradeProgramABIResult = ProgramABIMutationResult;
124
127
  export interface InspectProgramDeploymentRequest {
125
128
  client: Thru;
126
129
  seed: string;
130
+ /** Parent Manager executable used for derivation and ownership checks. */
131
+ managerProgramAddress?: string;
127
132
  ephemeral?: boolean;
128
133
  authorityAddress?: string;
129
134
  expectedProgramBytes?: Uint8Array;
@@ -214,7 +214,8 @@ export async function uploadArtifact(
214
214
  seed: upload.seed,
215
215
  }),
216
216
  computeUnits: 50_000 + upload.bytes.length * 2,
217
- stateUnits: 10_000,
217
+ // One metadata account plus the meta-inclusive buffer footprint.
218
+ stateUnits: 1 + Math.ceil((64 + upload.bytes.length) / 4096),
218
219
  memoryUnits: 10_000,
219
220
  expiryAfter: 10,
220
221
  },
@@ -314,7 +315,7 @@ export async function uploadArtifact(
314
315
  offset,
315
316
  }),
316
317
  computeUnits: 500_000_000,
317
- stateUnits: 5_000,
318
+ stateUnits: 1,
318
319
  memoryUnits: 5_000,
319
320
  expiryAfter: 10_000,
320
321
  },
@@ -414,7 +415,7 @@ export async function uploadArtifact(
414
415
  expectedHash: upload.hash,
415
416
  }),
416
417
  computeUnits: 50_000 + upload.bytes.length * 200,
417
- stateUnits: 5_000,
418
+ stateUnits: 1,
418
419
  memoryUnits: 5_000,
419
420
  expiryAfter: 10_000,
420
421
  },
@@ -497,7 +498,7 @@ export async function cleanupUpload(
497
498
  metaAccount: upload.addresses.metaAccountBytes,
498
499
  }),
499
500
  computeUnits: 50_000,
500
- stateUnits: 5_000,
501
+ stateUnits: 1,
501
502
  memoryUnits: 5_000,
502
503
  expiryAfter: 10_000,
503
504
  },
@@ -17,7 +17,8 @@ import {
17
17
  import { DeployError } from "./errors";
18
18
  import type { DeploymentTransaction } from "./chain";
19
19
  import type { PreparedUpload } from "./uploader";
20
- import { deployProgram, upgradeProgram } from "./workflows";
20
+ import { deployProgram, deployProgramABI, upgradeProgram, upgradeProgramABI } from "./workflows";
21
+ import { inspectProgramDeployment } from "./inspection";
21
22
 
22
23
  const mocks = vi.hoisted(() => ({
23
24
  submitTransaction: vi.fn(),
@@ -113,6 +114,7 @@ interface Harness {
113
114
  submitMode: "success" | "failure" | "unknown";
114
115
  wrongProgramReadback: boolean;
115
116
  duplicateTarget: boolean;
117
+ ownerOverride?: string;
116
118
  encoded?: Uint8Array;
117
119
  transaction?: DeploymentTransaction;
118
120
  };
@@ -148,12 +150,15 @@ function instructionContext(
148
150
  };
149
151
  }
150
152
 
151
- async function makeHarness(upgrade = false): Promise<Harness> {
153
+ async function makeHarness(
154
+ upgrade = false,
155
+ managerProgramAddress = MANAGER_PROGRAM_ADDRESS,
156
+ ): Promise<Harness> {
152
157
  const privateKey = new Uint8Array(32).fill(0x19);
153
158
  const localClient = createThruClient();
154
159
  const publicKey = await localClient.keys.fromPrivateKey(privateKey);
155
160
  const signer = { address: Pubkey.from(publicKey).toThruFmt(), privateKey };
156
- const program = deriveManagedProgramAddresses("workflow");
161
+ const program = deriveManagedProgramAddresses("workflow", false, managerProgramAddress);
157
162
  const abi = deriveProgramABIAddresses(program.programAccountAddress);
158
163
  const state: Harness["state"] = {
159
164
  committed: false,
@@ -195,7 +200,7 @@ async function makeHarness(upgrade = false): Promise<Harness> {
195
200
  program.programMetaAccountAddress,
196
201
  storedAccount(
197
202
  program.programMetaAccountAddress,
198
- MANAGER_PROGRAM_ADDRESS,
203
+ state.ownerOverride ?? managerProgramAddress,
199
204
  managerData,
200
205
  ),
201
206
  ],
@@ -203,7 +208,7 @@ async function makeHarness(upgrade = false): Promise<Harness> {
203
208
  program.programAccountAddress,
204
209
  storedAccount(
205
210
  program.programAccountAddress,
206
- MANAGER_PROGRAM_ADDRESS,
211
+ state.ownerOverride ?? managerProgramAddress,
207
212
  programBytes,
208
213
  true,
209
214
  ),
@@ -298,6 +303,70 @@ describe("deployment workflows", () => {
298
303
  );
299
304
  });
300
305
 
306
+ const rootManager = Pubkey.from(Uint8Array.from([...new Uint8Array(31), 1])).toThruFmt();
307
+
308
+ it.each([false, true])("supports root-managed binary operations (upgrade=%s)", async (upgrade) => {
309
+ const harness = await makeHarness(upgrade, rootManager);
310
+ const operation = upgrade ? upgradeProgram : deployProgram;
311
+ const result = await operation({
312
+ seed: "workflow", managerProgramAddress: rootManager,
313
+ signer: harness.signer, client: harness.client, program: image(0x33),
314
+ });
315
+ expect(result.programAccountAddress).toBe(harness.program.programAccountAddress);
316
+ expect(result.programMetaAccountAddress).toBe(harness.program.programMetaAccountAddress);
317
+ expect(result.programVersion).toBe(upgrade ? 6n : 0n);
318
+ expect(mocks.submitTransaction).toHaveBeenCalledOnce();
319
+ expect(harness.state.transaction?.program).toBe(rootManager);
320
+ expect(harness.state.encoded?.[0]).toBe(upgrade ? 2 : 0);
321
+ await expect(inspectProgramDeployment({
322
+ client: harness.client, seed: "workflow", managerProgramAddress: rootManager,
323
+ authorityAddress: harness.signer.address, expectedProgramBytes: image(0x33),
324
+ })).resolves.toMatchObject({
325
+ programAccountAddress: harness.program.programAccountAddress,
326
+ program: { status: "present", bytesMatch: true, version: upgrade ? 6n : 0n },
327
+ });
328
+ });
329
+
330
+ it("rejects another Manager's ownership even with the expected authority", async () => {
331
+ const harness = await makeHarness(true, rootManager);
332
+ harness.state.ownerOverride = MANAGER_PROGRAM_ADDRESS;
333
+ const request = {
334
+ seed: "workflow", managerProgramAddress: rootManager,
335
+ signer: harness.signer, client: harness.client, program: image(0x33),
336
+ };
337
+ await expect(upgradeProgram(request)).rejects.toMatchObject({ code: "VERIFICATION_FAILED" });
338
+ await expect(inspectProgramDeployment(request)).rejects.toMatchObject({ code: "VERIFICATION_FAILED" });
339
+ expect(mocks.uploadArtifact).not.toHaveBeenCalled();
340
+ expect(mocks.submitTransaction).not.toHaveBeenCalled();
341
+ });
342
+
343
+ it.each([deployProgram, upgradeProgram, deployProgramABI, upgradeProgramABI])(
344
+ "rejects unsupported official ABI operations under root before uploading",
345
+ async (operation) => {
346
+ const harness = await makeHarness(true, rootManager);
347
+ await expect(operation({
348
+ seed: "workflow", managerProgramAddress: rootManager,
349
+ signer: harness.signer, client: harness.client,
350
+ program: image(0x33), abi: ABI_BYTES,
351
+ })).rejects.toMatchObject({ code: "INVALID_INPUT" });
352
+ expect(mocks.uploadArtifact).not.toHaveBeenCalled();
353
+ expect(mocks.submitTransaction).not.toHaveBeenCalled();
354
+ },
355
+ );
356
+
357
+ it.each(["not-an-address", Pubkey.from(new Uint8Array(32)).toThruFmt()])(
358
+ "rejects an invalid parent before resolving the signer",
359
+ async (managerProgramAddress) => {
360
+ const harness = await makeHarness();
361
+ await expect(deployProgram({
362
+ seed: "workflow", managerProgramAddress,
363
+ signer: harness.signer, client: harness.client, program: image(0x33),
364
+ })).rejects.toMatchObject({ code: "INVALID_INPUT" });
365
+ expect(harness.client.keys.fromPrivateKey).not.toHaveBeenCalled();
366
+ expect(mocks.uploadArtifact).not.toHaveBeenCalled();
367
+ },
368
+ );
369
+
301
370
  it("commits a program plus ABI in one ordered multicall and reports cleanup warnings", async () => {
302
371
  const harness = await makeHarness();
303
372
  mocks.cleanupUpload.mockImplementation(