@trinaryex/sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1608 @@
1
+ import { Transaction as e } from "@mysten/sui/transactions";
2
+ import { bcs as t } from "@mysten/sui/bcs";
3
+ import { z as n } from "zod";
4
+ //#region \0rolldown/runtime.js
5
+ var r = Object.defineProperty, i = (e, t) => {
6
+ let n = {};
7
+ for (var i in e) r(n, i, {
8
+ get: e[i],
9
+ enumerable: !0
10
+ });
11
+ return t || r(n, Symbol.toStringTag, { value: "Module" }), n;
12
+ }, a = "https://api.trinary.exchange", o = "0x6", s = {
13
+ triexbook: "0x291b9da738dffedd18d7c5049e5e6792270202e03f3c9d9db4c7097670bf6eb2",
14
+ triexRegistry: "0x14a58f254b8243bf3f74c057d81cc310498b3d0fe3781650ad58405d7e5f17e4",
15
+ multicoin: "0x99a4c039477ac7e7affcb5a5609dd23c29ab69e9436e740d94a4e168c2506cfb",
16
+ warehouseReceipts: "0x0c9d4414aa12eaa1ebf9d32437c1e6403fbf941ffcdca5b9ca16d1769313417e",
17
+ credCoinType: "0xfbcbd9155669e157ce3999e073930b4c4b67255c3cf88d0d80c76342a31e6710::cred::CRED",
18
+ world: "0x8b8a46ed766fa1358ce7c5c51f6a164b13d627a63e45343f69ed0ba0446c1aa1",
19
+ worldOriginal: "0x8b8a46ed766fa1358ce7c5c51f6a164b13d627a63e45343f69ed0ba0446c1aa1",
20
+ clock: "0x6"
21
+ }, c = { testnet: s };
22
+ function l(e = "testnet", t) {
23
+ return {
24
+ ...c[e],
25
+ ...t
26
+ };
27
+ }
28
+ //#endregion
29
+ //#region src/errors.ts
30
+ var u = /* @__PURE__ */ function(e) {
31
+ return e.ExecutorRequired = "TRIEX_EXECUTOR_REQUIRED", e.AddressRequired = "TRIEX_ADDRESS_REQUIRED", e.ApiKeyRequired = "TRIEX_API_KEY_REQUIRED", e.Unauthorized = "TRIEX_UNAUTHORIZED", e.RateLimited = "TRIEX_RATE_LIMITED", e.IndexerError = "TRIEX_INDEXER_ERROR", e.UnexpectedResponse = "TRIEX_UNEXPECTED_RESPONSE", e.ValidationFailed = "TRIEX_VALIDATION_FAILED", e.InsufficientBalance = "TRIEX_INSUFFICIENT_BALANCE", e.CollectionMismatch = "TRIEX_COLLECTION_MISMATCH", e.BalanceManagerNotFound = "TRIEX_BALANCE_MANAGER_NOT_FOUND", e.PoolNotFound = "TRIEX_POOL_NOT_FOUND", e.HubNotFound = "TRIEX_HUB_NOT_FOUND", e.CharacterNotFound = "TRIEX_CHARACTER_NOT_FOUND", e.TransactionFailed = "TRIEX_TRANSACTION_FAILED", e.Timeout = "TRIEX_TIMEOUT", e.NotImplemented = "TRIEX_NOT_IMPLEMENTED", e;
32
+ }({}), d = class extends Error {
33
+ code;
34
+ cause;
35
+ status;
36
+ retryAfterMs;
37
+ constructor(e, t, n, r, i) {
38
+ super(t), this.code = e, this.cause = n, this.status = r, this.retryAfterMs = i, this.name = "TriexClientError";
39
+ }
40
+ }, f = {
41
+ "pool::12": "Slippage too high — the order price moved (EMinimumQuantityOutNotMet)",
42
+ "book::2": "No liquidity available (EEmptyOrderbook)",
43
+ "order_info::5": "POST-ONLY order would cross the book — use a plain limit order (EPOSTOrderCrossesOrderbook)",
44
+ "order_info::6": "Not enough liquidity to fully fill a FOK order (EFOKOrderCannotBeFullyFilled)",
45
+ "order_info::8": "Self-match would cancel your order (ESelfMatchingCancelTaker)",
46
+ "balance_manager::3": "Balance manager holds insufficient currency — deposit more (EBalanceManagerBalanceTooLow)",
47
+ "balance_manager::7": "Balance manager holds insufficient items (EMultiCoinBalanceTooLow)",
48
+ "state::2": "Max 100 open orders per balance manager per pool reached (EMaxOpenOrders)",
49
+ "book::7": "Modified quantity must be less than the original (ENewQuantityMustBeLessThanOriginal)",
50
+ "book::8": "Order not found — already filled or canceled? (EBookOrderNotFound)",
51
+ "order_info::4": "Invalid order restriction value (EInvalidOrderType)",
52
+ "order_info::0": "Price out of valid range (EOrderInvalidPrice)",
53
+ "order_info::3": "Expire timestamp is in the past (EInvalidExpireTimestamp)"
54
+ };
55
+ function p(e) {
56
+ let t = typeof e == "string" ? e : e instanceof Error ? e.message : JSON.stringify(e ?? ""), n, r, i = /Identifier\(\\*"([a-z_]+)\\*"\)[\s\S]*?},?\s*(\d+)\)/.exec(t);
57
+ return i && ([, n, r] = i), n || (i = /::([a-z_]+)::[a-z_]+[^,]*,\s*abort code:?\s*(\d+)/i.exec(t), i && ([, n, r] = i)), n || (i = /abort code:?\s*(\d+)[\s\S]*?::([a-z_]+)::[a-z_]+/i.exec(t), i && ([, r, n] = i)), n || (i = /module:?\s*'?"?([a-z_]+)'?"?[\s\S]*?abort_code:?\s*"?(\d+)"?/i.exec(t), i && ([, n, r] = i)), !n || !r ? null : f[`${n}::${r}`] ?? null;
58
+ }
59
+ //#endregion
60
+ //#region src/execute.ts
61
+ async function m(e, t) {
62
+ let n;
63
+ try {
64
+ n = await e(t);
65
+ } catch (e) {
66
+ if (e instanceof d) throw e;
67
+ let t = e instanceof Error ? e.message : String(e);
68
+ if (/MoveAbort|abort code/i.test(t)) {
69
+ let n = p(t);
70
+ throw new d(u.TransactionFailed, `Transaction failed${n ? `: ${n}` : ""} (${t}).`, e);
71
+ }
72
+ throw e;
73
+ }
74
+ return h(n);
75
+ }
76
+ function h(e) {
77
+ let t = e, n = t?.Transaction ?? t?.FailedTransaction;
78
+ if (n && typeof n.digest == "string") {
79
+ if (t?.$kind === "FailedTransaction" || t?.FailedTransaction !== void 0 || n.status?.success === !1) {
80
+ let e = JSON.stringify(n.status?.error ?? "unknown error"), t = p(e);
81
+ throw new d(u.TransactionFailed, `Transaction ${n.digest} failed on-chain${t ? `: ${t}` : ""} (${e}).`, n.status?.error);
82
+ }
83
+ let r = [], i = n.objectTypes ?? {}, a = n.effects?.changedObjects ?? [];
84
+ if (a.length > 0) for (let e of a) e?.idOperation === "Created" && typeof e.objectId == "string" && r.push({
85
+ objectId: e.objectId,
86
+ objectType: i[e.objectId] ?? ""
87
+ });
88
+ else for (let [e, t] of Object.entries(i)) r.push({
89
+ objectId: e,
90
+ objectType: t
91
+ });
92
+ return {
93
+ digest: n.digest,
94
+ createdObjects: r,
95
+ raw: e
96
+ };
97
+ }
98
+ if (typeof t?.digest == "string") {
99
+ let n = [];
100
+ for (let e of t.objectChanges ?? []) e?.type === "created" && typeof e.objectId == "string" && typeof e.objectType == "string" && n.push({
101
+ objectId: e.objectId,
102
+ objectType: e.objectType
103
+ });
104
+ let r = t.effects?.status;
105
+ if (r?.status === "failure") {
106
+ let e = String(r.error ?? "unknown error"), n = p(e);
107
+ throw new d(u.TransactionFailed, `Transaction ${t.digest} failed on-chain${n ? `: ${n}` : ""} (${e}).`, r.error);
108
+ }
109
+ return {
110
+ digest: t.digest,
111
+ createdObjects: n,
112
+ raw: e
113
+ };
114
+ }
115
+ throw new d(u.UnexpectedResponse, "Executor returned an unrecognized result — expected a v2 TransactionResult or an object with a `digest`.");
116
+ }
117
+ function g(e, t) {
118
+ return e.createdObjects.find((e) => e.objectType.includes(t));
119
+ }
120
+ //#endregion
121
+ //#region src/onchain.ts
122
+ var _ = t.struct("BalanceKey", { dummy_field: t.bool() });
123
+ function v() {
124
+ return _.serialize({ dummy_field: !1 }).toBytes();
125
+ }
126
+ var y = t.struct("MultiCoinBalanceKey", {
127
+ collection_id: t.Address,
128
+ asset_id: t.u64()
129
+ });
130
+ function b(e, t) {
131
+ return y.serialize({
132
+ collection_id: e,
133
+ asset_id: t
134
+ }).toBytes();
135
+ }
136
+ var x = t.struct("MultiCoinBalance", {
137
+ id: t.Address,
138
+ collection: t.Address,
139
+ asset_id: t.u64(),
140
+ amount: t.u64()
141
+ }), ee = t.u64();
142
+ function te(e) {
143
+ return e && typeof e == "object" && "fields" in e ? e.fields : e;
144
+ }
145
+ function S(e) {
146
+ if (typeof e == "string") return e;
147
+ if (e && typeof e == "object") {
148
+ let t = e;
149
+ if (typeof t.objectId == "string") return t.objectId;
150
+ if (typeof t.id == "string") return t.id;
151
+ if (typeof t.bytes == "string") return t.bytes;
152
+ if (t.id) return S(t.id);
153
+ }
154
+ return null;
155
+ }
156
+ var C = (e) => e.core;
157
+ function w(e) {
158
+ return "0x" + BigInt(e).toString(16).padStart(64, "0");
159
+ }
160
+ async function ne(e, t) {
161
+ let { object: n } = await C(e).getObject({ objectId: t });
162
+ return {
163
+ objectId: n.objectId,
164
+ version: n.version,
165
+ digest: n.digest
166
+ };
167
+ }
168
+ async function re(e, t, n) {
169
+ let r = 0n, i;
170
+ for (let a = 0; a < 40; a++) {
171
+ let a = await C(e).listCoins({
172
+ owner: t,
173
+ coinType: n,
174
+ limit: 50,
175
+ ...i ? { cursor: i } : {}
176
+ });
177
+ for (let e of a?.objects ?? []) r += BigInt(e.balance);
178
+ let o = a?.hasNextPage ?? a?.pageInfo?.hasNextPage;
179
+ if (i = a?.cursor ?? a?.pageInfo?.endCursor, !o || !i || (a?.objects?.length ?? 0) === 0) break;
180
+ }
181
+ return r;
182
+ }
183
+ async function T(e, t, n) {
184
+ let r = (await C(e).getObject({
185
+ objectId: n,
186
+ include: { json: !0 }
187
+ }).catch(() => null))?.object?.json, i = S(te(r?.balances)?.id);
188
+ if (!i) return 0n;
189
+ let a = `${t.triexbook}::balance_manager::BalanceKey<${t.credCoinType}>`, o = await C(e).getDynamicField({
190
+ parentId: i,
191
+ name: {
192
+ type: a,
193
+ bcs: v()
194
+ }
195
+ }).catch(() => null);
196
+ return o ? BigInt(ee.parse(o.dynamicField.value.bcs)) : 0n;
197
+ }
198
+ async function ie(e, t, n, r, i) {
199
+ let a = `${t.triexbook}::balance_manager::MultiCoinBalanceKey`, o = await C(e).getDynamicObjectField({
200
+ parentId: n,
201
+ name: {
202
+ type: a,
203
+ bcs: b(r, i)
204
+ },
205
+ include: { content: !0 }
206
+ }).catch(() => null);
207
+ if (!o) return {
208
+ hasKey: !1,
209
+ balance: 0n
210
+ };
211
+ let s = x.parse(o.object.content);
212
+ return {
213
+ hasKey: !0,
214
+ balance: BigInt(s.amount)
215
+ };
216
+ }
217
+ async function E(e, n) {
218
+ let r = `${n.triexbook}::registry::MultiCoinCollectionKey`, i = await C(e).getDynamicField({
219
+ parentId: n.triexRegistry,
220
+ name: {
221
+ type: r,
222
+ bcs: v()
223
+ }
224
+ }).catch(() => null);
225
+ if (!i) throw Error("Registry MultiCoin collection id not found (registry not initialized?).");
226
+ return t.Address.parse(i.dynamicField.value.bcs);
227
+ }
228
+ async function D(e, t, n, r) {
229
+ let i = `${t.multicoin}::multicoin::Balance`, a = [], o;
230
+ for (let t = 0; t < 40; t++) {
231
+ let t = await C(e).listOwnedObjects({
232
+ owner: n,
233
+ type: i,
234
+ limit: 50,
235
+ include: { content: !0 },
236
+ ...o ? { cursor: o } : {}
237
+ });
238
+ for (let e of t?.objects ?? []) try {
239
+ let t = x.parse(e.content);
240
+ if (r?.assetId && String(t.asset_id) !== r.assetId) continue;
241
+ a.push({
242
+ objectId: e.objectId,
243
+ collectionId: t.collection,
244
+ assetId: String(t.asset_id),
245
+ amount: BigInt(t.amount)
246
+ });
247
+ } catch {}
248
+ let s = t?.hasNextPage ?? t?.pageInfo?.hasNextPage;
249
+ if (o = t?.cursor ?? t?.pageInfo?.endCursor, !s || !o || (t?.objects?.length ?? 0) === 0) break;
250
+ }
251
+ return a;
252
+ }
253
+ async function O(e, t, n) {
254
+ let r = [t.worldOriginal];
255
+ t.world !== t.worldOriginal && r.push(t.world);
256
+ for (let t of r) {
257
+ let r = `${t}::character::PlayerProfile`, i = (await C(e).listOwnedObjects({
258
+ owner: n,
259
+ type: r,
260
+ include: { json: !0 },
261
+ limit: 1
262
+ }).catch(() => null))?.objects?.[0]?.json, a = typeof i?.character_id == "string" ? i.character_id : null;
263
+ if (!a) continue;
264
+ let o = (await C(e).getObject({
265
+ objectId: a,
266
+ include: { json: !0 }
267
+ }).catch(() => null))?.object?.json?.owner_cap_id;
268
+ if (typeof o == "string") return {
269
+ characterId: a,
270
+ ownerCapId: o
271
+ };
272
+ }
273
+ return null;
274
+ }
275
+ async function k(e, t, n) {
276
+ let r = (await C(e).getObject({
277
+ objectId: t,
278
+ include: { json: !0 }
279
+ }).catch(() => null))?.object?.json?.owner_cap_id;
280
+ if (typeof r != "string") return null;
281
+ let i = (await C(e).getObject({ objectId: r }).catch(() => null))?.object?.owner;
282
+ if (!i || typeof i != "object") return null;
283
+ let a = null;
284
+ if (i.AddressOwner) {
285
+ if (i.AddressOwner === n) return null;
286
+ a = i.AddressOwner;
287
+ } else i.ObjectOwner && (a = i.ObjectOwner);
288
+ if (!a) return null;
289
+ let o = (await C(e).getObject({
290
+ objectId: a,
291
+ include: { json: !0 }
292
+ }).catch(() => null))?.object?.json;
293
+ if (o?.character_address !== n) return null;
294
+ let s = o?.owner_cap_id;
295
+ return typeof s == "string" ? {
296
+ ssuOwnerCapId: r,
297
+ characterId: a,
298
+ charOwnerCapId: s
299
+ } : null;
300
+ }
301
+ async function A(e, n, r, i) {
302
+ let a = await C(e).getDynamicField({
303
+ parentId: n,
304
+ name: {
305
+ type: "0x2::object::ID",
306
+ bcs: t.Address.serialize(r).toBytes()
307
+ }
308
+ }).catch(() => null);
309
+ if (!a) return 0n;
310
+ let o = (await C(e).getObject({
311
+ objectId: a.dynamicField.fieldId,
312
+ include: { json: !0 }
313
+ }).catch(() => null))?.object?.json?.value?.items?.contents ?? [], s = 0n;
314
+ for (let e of o) String(e?.value?.type_id ?? "") === i && (s += BigInt(String(e?.value?.quantity ?? "0")));
315
+ return s;
316
+ }
317
+ //#endregion
318
+ //#region src/transactions.ts
319
+ var ae = /* @__PURE__ */ i({
320
+ cancelAllOrdersItem: () => R,
321
+ cancelOrderItem: () => L,
322
+ depositCoin: () => N,
323
+ depositMulticoinObject: () => oe,
324
+ generateProofAsOwner: () => M,
325
+ modifyOrderItem: () => z,
326
+ newBalanceManager: () => j,
327
+ placeLimitOrderItem: () => F,
328
+ placeMarketOrderItem: () => I,
329
+ redeemReceipt: () => ue,
330
+ sourceItemsFromHangar: () => P,
331
+ withdrawAllCoin: () => ce,
332
+ withdrawAllMulticoin: () => le,
333
+ withdrawCoin: () => se,
334
+ withdrawSettledAmounts: () => B
335
+ });
336
+ function j(e, t) {
337
+ return e.moveCall({
338
+ target: `${t.triexbook}::balance_manager::new`,
339
+ arguments: []
340
+ });
341
+ }
342
+ function M(e, t, n) {
343
+ return e.moveCall({
344
+ target: `${t.triexbook}::balance_manager::generate_proof_as_owner`,
345
+ arguments: [n]
346
+ });
347
+ }
348
+ function N(e, t, n, r, i = t.credCoinType) {
349
+ e.moveCall({
350
+ target: `${t.triexbook}::balance_manager::deposit`,
351
+ typeArguments: [i],
352
+ arguments: [n, r]
353
+ });
354
+ }
355
+ function oe(e, t, n, r) {
356
+ e.moveCall({
357
+ target: `${t.triexbook}::balance_manager::deposit_multicoin`,
358
+ arguments: [n, e.object(r)]
359
+ });
360
+ }
361
+ function se(e, t, n, r, i = t.credCoinType) {
362
+ return e.moveCall({
363
+ target: `${t.triexbook}::balance_manager::withdraw`,
364
+ typeArguments: [i],
365
+ arguments: [n, e.pure.u64(r)]
366
+ });
367
+ }
368
+ function ce(e, t, n, r = t.credCoinType) {
369
+ return e.moveCall({
370
+ target: `${t.triexbook}::balance_manager::withdraw_all`,
371
+ typeArguments: [r],
372
+ arguments: [n]
373
+ });
374
+ }
375
+ function le(e, t, n, r, i) {
376
+ return e.moveCall({
377
+ target: `${t.triexbook}::balance_manager::withdraw_all_multicoin`,
378
+ arguments: [
379
+ n,
380
+ e.pure.id(r),
381
+ e.pure.u64(i)
382
+ ]
383
+ });
384
+ }
385
+ function ue(e, t, n, r) {
386
+ e.moveCall({
387
+ target: `${t.warehouseReceipts}::receipt::redeem_receipt`,
388
+ arguments: [
389
+ n,
390
+ e.object(r.ssuObjectId),
391
+ e.object(r.characterId),
392
+ e.object(r.vaultConfigId),
393
+ e.object(r.collectionId),
394
+ e.pure.bool(r.isOwner)
395
+ ]
396
+ });
397
+ }
398
+ function P(e, t, n, r) {
399
+ let i = e.object(r.characterId), a = e.moveCall({
400
+ target: `${t.world}::character::borrow_owner_cap`,
401
+ typeArguments: [r.capTypeArg],
402
+ arguments: [i, e.receivingRef(r.capRef)]
403
+ }), o = a[0], s = a[1], [c] = e.moveCall({
404
+ target: `${t.warehouseReceipts}::receipt::deposit_for_receipt`,
405
+ typeArguments: [r.capTypeArg],
406
+ arguments: [
407
+ e.object(r.ssuObjectId),
408
+ i,
409
+ o,
410
+ e.object(r.vaultConfigId),
411
+ e.object(r.vaultCollectionId),
412
+ e.pure.u64(r.assetId),
413
+ e.pure.u32(r.amount)
414
+ ]
415
+ });
416
+ e.moveCall({
417
+ target: `${t.world}::character::return_owner_cap`,
418
+ typeArguments: [r.capTypeArg],
419
+ arguments: [
420
+ i,
421
+ o,
422
+ s
423
+ ]
424
+ }), e.moveCall({
425
+ target: `${t.triexbook}::balance_manager::deposit_multicoin`,
426
+ arguments: [n, c]
427
+ });
428
+ }
429
+ function F(e, t, n) {
430
+ e.moveCall({
431
+ target: `${t.triexbook}::multicoin_pool::place_limit_order`,
432
+ typeArguments: [t.credCoinType],
433
+ arguments: [
434
+ e.object(n.poolId),
435
+ n.bm,
436
+ n.proof,
437
+ e.pure.u8(n.orderType ?? 0),
438
+ e.pure.u8(n.selfMatchingOption ?? 0),
439
+ e.pure.u64(n.price),
440
+ e.pure.u64(n.quantity),
441
+ e.pure.bool(n.isBid),
442
+ e.pure.u64(n.expireTimestamp),
443
+ e.object(t.clock)
444
+ ]
445
+ });
446
+ }
447
+ function I(e, t, n) {
448
+ e.moveCall({
449
+ target: `${t.triexbook}::multicoin_pool::place_market_order`,
450
+ typeArguments: [t.credCoinType],
451
+ arguments: [
452
+ e.object(n.poolId),
453
+ n.bm,
454
+ n.proof,
455
+ e.pure.u8(n.selfMatchingOption ?? 0),
456
+ e.pure.u64(n.quantity),
457
+ e.pure.bool(n.isBid),
458
+ e.object(t.clock)
459
+ ]
460
+ });
461
+ }
462
+ function L(e, t, n) {
463
+ e.moveCall({
464
+ target: `${t.triexbook}::multicoin_pool::cancel_order`,
465
+ typeArguments: [t.credCoinType],
466
+ arguments: [
467
+ e.object(n.poolId),
468
+ n.bm,
469
+ n.proof,
470
+ e.pure.u64(n.orderId),
471
+ e.object(t.clock)
472
+ ]
473
+ });
474
+ }
475
+ function R(e, t, n) {
476
+ e.moveCall({
477
+ target: `${t.triexbook}::multicoin_pool::cancel_all_orders`,
478
+ typeArguments: [t.credCoinType],
479
+ arguments: [
480
+ e.object(n.poolId),
481
+ n.bm,
482
+ n.proof,
483
+ e.object(t.clock)
484
+ ]
485
+ });
486
+ }
487
+ function z(e, t, n) {
488
+ e.moveCall({
489
+ target: `${t.triexbook}::multicoin_pool::modify_order`,
490
+ typeArguments: [t.credCoinType],
491
+ arguments: [
492
+ e.object(n.poolId),
493
+ n.bm,
494
+ n.proof,
495
+ e.pure.u64(n.orderId),
496
+ e.pure.u64(n.newQuantity),
497
+ e.object(t.clock)
498
+ ]
499
+ });
500
+ }
501
+ function B(e, t, n) {
502
+ e.moveCall({
503
+ target: `${t.triexbook}::multicoin_pool::withdraw_settled_amounts`,
504
+ typeArguments: [n.quoteCoinType ?? t.credCoinType],
505
+ arguments: [
506
+ e.object(n.poolId),
507
+ n.bm,
508
+ n.proof
509
+ ]
510
+ });
511
+ }
512
+ //#endregion
513
+ //#region src/funding.ts
514
+ async function V(e, t, n, r, i, a = "Insufficient wallet balance to fund this transaction.") {
515
+ let o = e.core, s = [], c = 0n, l;
516
+ for (let e = 0; e < 40 && c < i; e++) {
517
+ let e = await o.listCoins({
518
+ owner: n,
519
+ coinType: r,
520
+ limit: 50,
521
+ ...l ? { cursor: l } : {}
522
+ });
523
+ for (let t of e?.objects ?? []) if (s.push({
524
+ objectId: t.objectId,
525
+ balance: BigInt(t.balance)
526
+ }), c += BigInt(t.balance), c >= i) break;
527
+ let t = e?.hasNextPage ?? e?.pageInfo?.hasNextPage;
528
+ if (l = e?.cursor ?? e?.pageInfo?.endCursor, !t || !l || (e?.objects?.length ?? 0) === 0) break;
529
+ }
530
+ if (c < i) throw new d(u.InsufficientBalance, `${a} (need ${i}, wallet holds ${c}).`);
531
+ let f = t.object(s[0].objectId);
532
+ s.length > 1 && t.mergeCoins(f, s.slice(1).map((e) => t.object(e.objectId)));
533
+ let [p] = t.splitCoins(f, [t.pure.u64(i)]);
534
+ return p;
535
+ }
536
+ async function H(e, t, n, r, i) {
537
+ let { assetId: a, amount: o } = i;
538
+ if (o <= 0n) throw new d(u.ValidationFailed, "Item amount must be positive.");
539
+ let s = i.deficitMode && i.balanceManagerId ? await ie(e, n, i.balanceManagerId, i.vaultCollectionId, a) : {
540
+ hasKey: !1,
541
+ balance: 0n
542
+ }, c = i.deficitMode ? o - s.balance : o;
543
+ if (c <= 0n) return;
544
+ let l = await D(e, n, i.owner, { assetId: a.toString() }), f = (i.vaultCollectionId || await E(e, n)).trim().toLowerCase(), p = l.filter((e) => e.amount > 0n && (!e.collectionId || e.collectionId.toLowerCase() === f)).sort((e, t) => e.amount > t.amount ? -1 : 1), m = 0n;
545
+ for (let e of p) {
546
+ if (m >= c) break;
547
+ oe(t, n, r, e.objectId), m += e.amount;
548
+ }
549
+ if (c -= m, c <= 0n) return;
550
+ let [h, g] = await Promise.all([k(e, i.ssuObjectId, i.owner), O(e, n, i.owner)]), _ = async (o, s, c, l) => {
551
+ let u = await ne(e, o);
552
+ P(t, n, r, {
553
+ ssuObjectId: i.ssuObjectId,
554
+ characterId: c,
555
+ capRef: u,
556
+ capTypeArg: s,
557
+ vaultConfigId: i.vaultConfigId,
558
+ vaultCollectionId: i.vaultCollectionId,
559
+ assetId: a,
560
+ amount: Number(l)
561
+ });
562
+ }, v = `${n.worldOriginal}::storage_unit::StorageUnit`, y = `${n.worldOriginal}::character::Character`;
563
+ if (h) {
564
+ let [t, n] = await Promise.all([A(e, i.ssuObjectId, h.ssuOwnerCapId, a.toString()), A(e, i.ssuObjectId, h.charOwnerCapId, a.toString())]), r = t >= c ? c : t, o = c - r, s = o <= n ? o : n;
565
+ if (r + s < c) throw new d(u.InsufficientBalance, `Insufficient items in the hub inventory (SSU slot: ${t}, character slot: ${n}, needed: ${c}).`);
566
+ r > 0n && await _(h.ssuOwnerCapId, v, h.characterId, r), s > 0n && await _(h.charOwnerCapId, y, h.characterId, s);
567
+ return;
568
+ }
569
+ if (g) {
570
+ let t = await A(e, i.ssuObjectId, g.ownerCapId, a.toString());
571
+ if (t < c) throw new d(u.InsufficientBalance, `Insufficient items (need ${o}, BM holds ${s.balance}, wallet receipts cover ${m}, hangar slot holds ${t}).`);
572
+ await _(g.ownerCapId, y, g.characterId, c);
573
+ return;
574
+ }
575
+ let b = l.filter((e) => e.collectionId && e.collectionId.toLowerCase() !== f);
576
+ if (m === 0n && b.length > 0) {
577
+ let e = b.slice(0, 5).map((e) => `${e.collectionId}=${e.amount}`).join(", ");
578
+ throw new d(u.CollectionMismatch, `You own item receipts for asset ${a}, but in a different MultiCoin collection than this market trades. Expected ${f}; found: ${e}.`);
579
+ }
580
+ throw new d(u.CharacterNotFound, `Insufficient wallet receipts (cover ${m} of ${o}) and no on-chain character resolved for ${i.owner} to draw hangar items from.`);
581
+ }
582
+ //#endregion
583
+ //#region src/money.ts
584
+ var de = 1000000000n, U = 1n, W = 1000000000n, fe = 18446744073709551615n;
585
+ function pe(e, t) {
586
+ let n = typeof e == "number" ? e.toString() : e.trim();
587
+ if (!/^\d+(\.\d+)?$/.test(n)) throw Error(`toBase: invalid amount "${e}"`);
588
+ let [r, i = ""] = n.split("."), a = (i + "0".repeat(t)).slice(0, t);
589
+ return BigInt(r) * 10n ** BigInt(t) + BigInt(a || "0");
590
+ }
591
+ function me(e, t) {
592
+ let n = e < 0n, r = n ? -e : e, i = 10n ** BigInt(t), a = r / i, o = (r % i).toString().padStart(t, "0").replace(/0+$/, ""), s = n ? "-" : "";
593
+ return o ? `${s}${a}.${o}` : `${s}${a}`;
594
+ }
595
+ function G(e, t) {
596
+ return e * t * U / 1n;
597
+ }
598
+ function K(e, t, n) {
599
+ return G(e, t) * (W + n) / W;
600
+ }
601
+ function he(e, t) {
602
+ return e * t / W + 2n;
603
+ }
604
+ function ge(e, t, n) {
605
+ let r = t, i = 0n;
606
+ for (let t of e) {
607
+ if (r <= 0n) break;
608
+ let e = t.remainingQuantity < r ? t.remainingQuantity : r;
609
+ i += e * t.price, r -= e;
610
+ }
611
+ let a = i * n / W;
612
+ return {
613
+ quote: i,
614
+ fee: a,
615
+ total: i + a,
616
+ fillable: t - r
617
+ };
618
+ }
619
+ //#endregion
620
+ //#region src/schemas.ts
621
+ var q = n.union([n.string(), n.number()]).transform((e, t) => {
622
+ try {
623
+ return BigInt(e);
624
+ } catch {
625
+ return t.addIssue({
626
+ code: n.ZodIssueCode.custom,
627
+ message: `not an integer: ${e}`
628
+ }), n.NEVER;
629
+ }
630
+ }), _e = n.object({
631
+ pool_id: n.string(),
632
+ order_id: n.string(),
633
+ price: q,
634
+ is_bid: n.boolean(),
635
+ balance_manager_id: n.string(),
636
+ remaining_quantity: q,
637
+ filled_quantity: q,
638
+ expires_at: n.number().nullable(),
639
+ last_activity_at: n.number(),
640
+ asset_id: n.string(),
641
+ collection_id: n.string(),
642
+ hub_id: n.string().nullable(),
643
+ hub_name: n.string().nullable(),
644
+ hub_state: n.string().nullable(),
645
+ quote_asset_id: n.string().nullable(),
646
+ quote_asset_symbol: n.string().nullable(),
647
+ quote_asset_decimals: n.number().nullable(),
648
+ trader_address: n.string().nullable(),
649
+ trader_name: n.string().nullable()
650
+ }).transform((e) => ({
651
+ poolId: e.pool_id,
652
+ orderId: e.order_id,
653
+ price: e.price,
654
+ isBid: e.is_bid,
655
+ balanceManagerId: e.balance_manager_id,
656
+ remainingQuantity: e.remaining_quantity,
657
+ filledQuantity: e.filled_quantity,
658
+ expiresAt: e.expires_at,
659
+ lastActivityAt: e.last_activity_at,
660
+ assetId: e.asset_id,
661
+ collectionId: e.collection_id,
662
+ hubId: e.hub_id,
663
+ hubName: e.hub_name,
664
+ hubState: e.hub_state,
665
+ quoteAssetId: e.quote_asset_id,
666
+ quoteAssetSymbol: e.quote_asset_symbol,
667
+ quoteAssetDecimals: e.quote_asset_decimals,
668
+ traderAddress: e.trader_address,
669
+ traderName: e.trader_name
670
+ })), ve = n.object({
671
+ data: n.array(_e),
672
+ next_cursor: n.string().nullable(),
673
+ prev_cursor: n.string().nullable()
674
+ }).transform((e) => ({
675
+ orders: e.data,
676
+ nextCursor: e.next_cursor,
677
+ prevCursor: e.prev_cursor
678
+ })), ye = n.object({ pool_id: n.string().nullable() }).transform((e) => ({ poolId: e.pool_id })), be = n.object({
679
+ encodedOrderId: n.string(),
680
+ quantity: q,
681
+ filledQuantity: q,
682
+ expireTimestamp: q,
683
+ lastUpdatedTimestamp: q,
684
+ status: n.number(),
685
+ price: q
686
+ }).transform((e) => ({
687
+ orderId: e.encodedOrderId,
688
+ quantity: e.quantity,
689
+ filledQuantity: e.filledQuantity,
690
+ remainingQuantity: e.quantity - e.filledQuantity,
691
+ expireTimestamp: e.expireTimestamp,
692
+ lastUpdatedTimestamp: e.lastUpdatedTimestamp,
693
+ status: e.status,
694
+ price: e.price
695
+ })), xe = n.object({
696
+ bids: n.array(be),
697
+ asks: n.array(be)
698
+ }), Se = n.object({
699
+ pool_id: n.string(),
700
+ pool_name: n.string(),
701
+ base_asset_symbol: n.string(),
702
+ base_asset_name: n.string().nullable(),
703
+ base_asset_decimals: n.number(),
704
+ quote_asset_symbol: n.string(),
705
+ quote_asset_name: n.string().nullable(),
706
+ quote_asset_decimals: n.number(),
707
+ storage_unit_id: n.string().nullable(),
708
+ asset_id: n.string().nullable(),
709
+ collection_id: n.string().nullable(),
710
+ fee: n.string().nullable(),
711
+ fee_rate: n.number().nullable()
712
+ }).transform((e) => ({
713
+ poolId: e.pool_id,
714
+ poolName: e.pool_name,
715
+ baseAssetSymbol: e.base_asset_symbol,
716
+ baseAssetName: e.base_asset_name,
717
+ baseAssetDecimals: e.base_asset_decimals,
718
+ quoteAssetSymbol: e.quote_asset_symbol,
719
+ quoteAssetName: e.quote_asset_name,
720
+ quoteAssetDecimals: e.quote_asset_decimals,
721
+ storageUnitId: e.storage_unit_id,
722
+ assetId: e.asset_id,
723
+ collectionId: e.collection_id,
724
+ feeRateScaled: e.fee === null ? 0n : BigInt(e.fee),
725
+ feeRate: e.fee_rate
726
+ })), Ce = n.object({
727
+ hub_id: n.string(),
728
+ collection_id: n.string(),
729
+ vault_config_id: n.string()
730
+ }).transform((e) => ({
731
+ hubId: e.hub_id,
732
+ collectionId: e.collection_id,
733
+ vaultConfigId: e.vault_config_id
734
+ })), we = n.object({
735
+ hub_id: n.string(),
736
+ assembly_item_id: n.string(),
737
+ assembly_tenant: n.string(),
738
+ type_id: n.string(),
739
+ owner_cap_id: n.string(),
740
+ owner: n.string().nullable(),
741
+ solar_system: n.string(),
742
+ x: n.string(),
743
+ y: n.string(),
744
+ z: n.string(),
745
+ updated_at: n.number(),
746
+ tx_digest: n.string(),
747
+ is_public: n.boolean(),
748
+ region_id: n.number().nullable(),
749
+ solar_system_name: n.string().nullable()
750
+ }).transform((e) => ({
751
+ hubId: e.hub_id,
752
+ assemblyItemId: e.assembly_item_id,
753
+ assemblyTenant: e.assembly_tenant,
754
+ typeId: e.type_id,
755
+ ownerCapId: e.owner_cap_id,
756
+ owner: e.owner,
757
+ solarSystemId: e.solar_system,
758
+ x: e.x,
759
+ y: e.y,
760
+ z: e.z,
761
+ updatedAt: e.updated_at,
762
+ txDigest: e.tx_digest,
763
+ isPublic: e.is_public,
764
+ regionId: e.region_id,
765
+ solarSystemName: e.solar_system_name
766
+ })), Te = n.object({
767
+ asset_id: n.string(),
768
+ has_bids: n.boolean(),
769
+ has_asks: n.boolean()
770
+ }).transform((e) => ({
771
+ assetId: e.asset_id,
772
+ hasBids: e.has_bids,
773
+ hasAsks: e.has_asks
774
+ })), Ee = n.object({
775
+ data: n.array(Te),
776
+ next_cursor: n.string().nullable()
777
+ }).transform((e) => ({
778
+ items: e.data,
779
+ nextCursor: e.next_cursor
780
+ })), De = n.object({
781
+ hub_id: n.string(),
782
+ collection_id: n.string()
783
+ }).transform((e) => ({
784
+ hubId: e.hub_id,
785
+ collectionId: e.collection_id
786
+ })), J = n.object({
787
+ asset_id: n.string(),
788
+ amount: q
789
+ }).transform((e) => ({
790
+ assetId: e.asset_id,
791
+ amount: e.amount
792
+ })), Oe = n.object({
793
+ storage_unit_id: n.string(),
794
+ collection_id: n.string(),
795
+ warehouse: n.array(J),
796
+ marketplace: n.array(J),
797
+ hangar: n.array(J),
798
+ org_vaults: n.record(n.string(), n.array(J))
799
+ }).transform((e) => ({
800
+ storageUnitId: e.storage_unit_id,
801
+ collectionId: e.collection_id,
802
+ warehouse: e.warehouse,
803
+ marketplace: e.marketplace,
804
+ hangar: e.hangar,
805
+ orgVaults: e.org_vaults
806
+ })), ke = n.object({
807
+ pool_id: n.string(),
808
+ order_id: n.string(),
809
+ encoded_order_id: n.string().optional(),
810
+ side: n.enum(["buy", "sell"]),
811
+ price: q,
812
+ remaining_quantity: q,
813
+ filled_quantity: q,
814
+ expires_at: n.number(),
815
+ updated_at: n.number(),
816
+ asset_id: n.string(),
817
+ storage_unit_id: n.string(),
818
+ quote_asset_symbol: n.string().nullable(),
819
+ quote_asset_decimals: n.number().nullable()
820
+ }).transform((e) => ({
821
+ poolId: e.pool_id,
822
+ orderId: e.order_id,
823
+ encodedOrderId: e.encoded_order_id,
824
+ side: e.side,
825
+ price: e.price,
826
+ remainingQuantity: e.remaining_quantity,
827
+ filledQuantity: e.filled_quantity,
828
+ expiresAt: e.expires_at,
829
+ updatedAt: e.updated_at,
830
+ assetId: e.asset_id,
831
+ storageUnitId: e.storage_unit_id,
832
+ quoteAssetSymbol: e.quote_asset_symbol,
833
+ quoteAssetDecimals: e.quote_asset_decimals
834
+ })), Ae = n.object({
835
+ data: n.array(ke),
836
+ next_cursor: n.string().nullable()
837
+ }).transform((e) => ({
838
+ orders: e.data,
839
+ nextCursor: e.next_cursor
840
+ })), je = n.object({
841
+ event_digest: n.string(),
842
+ pool_id: n.string(),
843
+ order_id: n.string(),
844
+ counterparty_balance_manager_id: n.string(),
845
+ price: q,
846
+ base_quantity: q,
847
+ quote_quantity: q,
848
+ fee: q,
849
+ role: n.enum(["maker", "taker"]),
850
+ taker_is_bid: n.boolean(),
851
+ filled_at: n.number()
852
+ }).transform((e) => ({
853
+ eventDigest: e.event_digest,
854
+ poolId: e.pool_id,
855
+ orderId: e.order_id,
856
+ counterpartyBalanceManagerId: e.counterparty_balance_manager_id,
857
+ price: e.price,
858
+ baseQuantity: e.base_quantity,
859
+ quoteQuantity: e.quote_quantity,
860
+ fee: e.fee,
861
+ role: e.role,
862
+ takerIsBid: e.taker_is_bid,
863
+ filledAt: e.filled_at
864
+ })), Me = n.object({
865
+ data: n.array(je),
866
+ next_cursor: n.string().nullable()
867
+ }).transform((e) => ({
868
+ fills: e.data,
869
+ nextCursor: e.next_cursor
870
+ })), Ne = n.object({
871
+ event_digest: n.string(),
872
+ pool_id: n.string(),
873
+ order_id: n.string(),
874
+ counterparty_balance_manager_id: n.string(),
875
+ price: q,
876
+ base_quantity: q,
877
+ quote_quantity: q,
878
+ fee: q,
879
+ role: n.enum(["maker", "taker"]),
880
+ side: n.enum(["buy", "sell"]),
881
+ traded_at: n.number(),
882
+ asset_id: n.string(),
883
+ storage_unit_id: n.string()
884
+ }).transform((e) => ({
885
+ eventDigest: e.event_digest,
886
+ poolId: e.pool_id,
887
+ orderId: e.order_id,
888
+ counterpartyBalanceManagerId: e.counterparty_balance_manager_id,
889
+ price: e.price,
890
+ baseQuantity: e.base_quantity,
891
+ quoteQuantity: e.quote_quantity,
892
+ fee: e.fee,
893
+ role: e.role,
894
+ side: e.side,
895
+ tradedAt: e.traded_at,
896
+ assetId: e.asset_id,
897
+ storageUnitId: e.storage_unit_id
898
+ })), Pe = n.object({
899
+ data: n.array(Ne),
900
+ next_cursor: n.string().nullable()
901
+ }).transform((e) => ({
902
+ trades: e.data,
903
+ nextCursor: e.next_cursor
904
+ })), Fe = n.object({
905
+ base: q,
906
+ quote: q,
907
+ cred: q
908
+ }).transform((e) => ({
909
+ base: e.base,
910
+ quote: e.quote,
911
+ cred: e.cred
912
+ })), Ie = n.object({
913
+ pool_id: n.string(),
914
+ collection_id: n.string(),
915
+ asset_id: n.string(),
916
+ quote_asset_id: n.string().nullable(),
917
+ storage_unit_id: n.string(),
918
+ vault_config_id: n.string(),
919
+ settled: Fe,
920
+ owed: Fe,
921
+ open_order_count: n.number()
922
+ }).transform((e) => ({
923
+ poolId: e.pool_id,
924
+ collectionId: e.collection_id,
925
+ assetId: e.asset_id,
926
+ quoteAssetId: e.quote_asset_id,
927
+ storageUnitId: e.storage_unit_id,
928
+ vaultConfigId: e.vault_config_id,
929
+ settled: e.settled,
930
+ owed: e.owed,
931
+ openOrderCount: e.open_order_count
932
+ })), Le = n.object({
933
+ collection_id: n.string(),
934
+ asset_id: n.string(),
935
+ amount: q,
936
+ storage_unit_id: n.string(),
937
+ vault_config_id: n.string()
938
+ }).transform((e) => ({
939
+ collectionId: e.collection_id,
940
+ assetId: e.asset_id,
941
+ amount: e.amount,
942
+ storageUnitId: e.storage_unit_id,
943
+ vaultConfigId: e.vault_config_id
944
+ })), Re = n.object({
945
+ balance_manager_id: n.string(),
946
+ as_of_checkpoint: n.string().nullable(),
947
+ pools: n.array(Ie),
948
+ items: n.array(Le)
949
+ }).transform((e) => ({
950
+ balanceManagerId: e.balance_manager_id,
951
+ asOfCheckpoint: e.as_of_checkpoint,
952
+ pools: e.pools,
953
+ items: e.items
954
+ }));
955
+ function Y(e, t, n) {
956
+ let r = e.safeParse(t);
957
+ if (!r.success) throw new d(u.UnexpectedResponse, `Unexpected indexer response for ${n}: ${r.error.message}`, r.error);
958
+ return r.data;
959
+ }
960
+ //#endregion
961
+ //#region src/queries.ts
962
+ var X = class {
963
+ baseUrl;
964
+ apiKey;
965
+ constructor(e, t) {
966
+ this.baseUrl = e, this.apiKey = t;
967
+ }
968
+ async get(e, t, n) {
969
+ if (!this.apiKey) throw new d(u.ApiKeyRequired, "An apiKey is required for indexer reads.");
970
+ let r = new URL(e, this.baseUrl);
971
+ if (t) for (let [e, n] of Object.entries(t)) n !== void 0 && r.searchParams.set(e, String(n));
972
+ let i = await fetch(r, { headers: {
973
+ "x-api-key": this.apiKey,
974
+ accept: "application/json"
975
+ } });
976
+ if (!i.ok) {
977
+ let e = "";
978
+ try {
979
+ let t = await i.json(), n = t?.message ?? t?.error ?? t?.reason;
980
+ n && (e = ` — ${typeof n == "string" ? n : JSON.stringify(n)}`);
981
+ } catch {}
982
+ let t = `Indexer ${i.status} ${i.statusText} for GET ${r.pathname}${e}`;
983
+ if (i.status === 401 || i.status === 403) throw new d(u.Unauthorized, `${t}. Check TRINARY_API_KEY and the key's access tier.`, void 0, i.status);
984
+ if (i.status === 429) {
985
+ let e = i.headers?.get?.("retry-after"), n;
986
+ if (e) {
987
+ let t = Number(e);
988
+ n = Number.isFinite(t) ? t * 1e3 : Math.max(0, Date.parse(e) - Date.now()) || void 0;
989
+ }
990
+ throw new d(u.RateLimited, `${t}. Compute-unit budget exhausted — back off${n ? ` ~${n}ms` : ""} and retry.`, void 0, i.status, n);
991
+ }
992
+ throw i.status === 404 && n ? new d(n, t, void 0, i.status) : new d(u.IndexerError, t, void 0, i.status);
993
+ }
994
+ return await i.json();
995
+ }
996
+ async discovery(e) {
997
+ return Y(ve, await this.get("/v1/discovery", {
998
+ storage_unit_ids: e?.storageUnitIds?.join(","),
999
+ asset_id: e?.assetId,
1000
+ balance_manager_id: e?.balanceManagerId,
1001
+ side: e?.side,
1002
+ public_only: e?.publicOnly,
1003
+ cursor: e?.cursor,
1004
+ limit: e?.limit
1005
+ }), "discovery");
1006
+ }
1007
+ async resolvePool(e) {
1008
+ return Y(ye, await this.get("/v1/pools/resolve", {
1009
+ collection_id: e.collectionId,
1010
+ asset_id: e.assetId,
1011
+ quote_type: e.quoteType
1012
+ }), "resolvePool").poolId;
1013
+ }
1014
+ async orderbook(e) {
1015
+ return {
1016
+ poolId: e,
1017
+ ...Y(xe, await this.get(`/v1/pools/${encodeURIComponent(e)}/orderbook`, void 0, u.PoolNotFound), "orderbook")
1018
+ };
1019
+ }
1020
+ async poolMetadata(e) {
1021
+ return Y(Se, await this.get(`/v1/pools/${encodeURIComponent(e)}/metadata`, void 0, u.PoolNotFound), "poolMetadata");
1022
+ }
1023
+ async hubVault(e) {
1024
+ return Y(Ce, await this.get(`/v1/hubs/${encodeURIComponent(e)}/vault`, void 0, u.HubNotFound), "hubVault");
1025
+ }
1026
+ async hubLocation(e) {
1027
+ try {
1028
+ return Y(we, await this.get(`/v1/hubs/${encodeURIComponent(e)}/location`, void 0, u.HubNotFound), "hubLocation");
1029
+ } catch (e) {
1030
+ if (e instanceof d && e.status === 404) return null;
1031
+ throw e;
1032
+ }
1033
+ }
1034
+ async hubItems(e) {
1035
+ return Y(Ee, await this.get(`/v1/hubs/${encodeURIComponent(e)}/items`, void 0, u.HubNotFound), "hubItems");
1036
+ }
1037
+ async collectionHub(e) {
1038
+ return Y(De, await this.get(`/v1/collections/${encodeURIComponent(e)}/hub`, void 0, u.HubNotFound), "collectionHub");
1039
+ }
1040
+ async inventoryBalances(e) {
1041
+ return Y(Oe, await this.get("/v1/inventory/balances", {
1042
+ storage_unit_id: e.storageUnitId,
1043
+ owner_address: e.address,
1044
+ balance_manager_id: e.balanceManagerId,
1045
+ inventory_key: e.inventoryKey,
1046
+ vault_ids: e.vaultIds?.join(",")
1047
+ }, u.HubNotFound), "inventoryBalances");
1048
+ }
1049
+ async openOrders(e, t) {
1050
+ return Y(Ae, await this.get(`/v1/balance-managers/${encodeURIComponent(e)}/open-orders`, {
1051
+ before: t?.before,
1052
+ after: t?.after,
1053
+ limit: t?.limit
1054
+ }, u.BalanceManagerNotFound), "openOrders");
1055
+ }
1056
+ async fills(e, t) {
1057
+ return Y(Me, await this.get(`/v1/balance-managers/${encodeURIComponent(e)}/fills`, {
1058
+ before: t?.before,
1059
+ after: t?.after,
1060
+ limit: t?.limit,
1061
+ pool_id: t?.poolId,
1062
+ side: t?.side
1063
+ }, u.BalanceManagerNotFound), "fills");
1064
+ }
1065
+ async sweepable(e) {
1066
+ return Y(Re, await this.get(`/v1/balance-managers/${encodeURIComponent(e)}/sweepable`, void 0, u.BalanceManagerNotFound), "sweepable");
1067
+ }
1068
+ async trades(e, t) {
1069
+ return Y(Pe, await this.get(`/v1/balance-managers/${encodeURIComponent(e)}/trades`, {
1070
+ before: t?.before,
1071
+ after: t?.after,
1072
+ limit: t?.limit,
1073
+ side: t?.side,
1074
+ asset_id: t?.assetId
1075
+ }, u.BalanceManagerNotFound), "trades");
1076
+ }
1077
+ }, ze = class {
1078
+ suiClient;
1079
+ ids;
1080
+ indexer;
1081
+ executor;
1082
+ address;
1083
+ cachedBalanceManagerId;
1084
+ account;
1085
+ balances;
1086
+ market;
1087
+ orders;
1088
+ constructor(e) {
1089
+ this.suiClient = e.suiClient, this.executor = e.executor, this.address = e.address, this.ids = l(e.network ?? "testnet", e.packageIds), this.indexer = new X(e.indexerUrl ?? "https://api.trinary.exchange", e.apiKey), this.account = new Ve(this), this.balances = new He(this), this.market = new Ue(this), this.orders = new We(this);
1090
+ }
1091
+ requireExecutor() {
1092
+ if (!this.executor) throw new d(u.ExecutorRequired, "This operation writes on-chain and requires an `executor`.");
1093
+ return this.executor;
1094
+ }
1095
+ requireAddress(e) {
1096
+ let t = e ?? this.address;
1097
+ if (!t) throw new d(u.AddressRequired, "This operation needs the player address — set `address` in config or pass it per-call.");
1098
+ return t;
1099
+ }
1100
+ async resolveBalanceManagerId(e) {
1101
+ if (this.cachedBalanceManagerId) return this.cachedBalanceManagerId;
1102
+ let t = `${this.ids.triexbook}::balance_manager::BalanceManager`, n = (await this.suiClient.core.listOwnedObjects({
1103
+ owner: e,
1104
+ type: t,
1105
+ limit: 1
1106
+ }))?.objects?.[0]?.objectId;
1107
+ return n && (this.cachedBalanceManagerId = n), n ?? null;
1108
+ }
1109
+ rememberBalanceManagerId(e) {
1110
+ this.cachedBalanceManagerId = e;
1111
+ }
1112
+ async beginBmTx(t) {
1113
+ let n = await this.resolveBalanceManagerId(t), r = new e();
1114
+ return {
1115
+ tx: r,
1116
+ bm: n ? r.object(n) : j(r, this.ids)[0],
1117
+ existingBmId: n
1118
+ };
1119
+ }
1120
+ async finishBmTx(e, t, n, r) {
1121
+ n || e.transferObjects([t], r);
1122
+ let i = await m(this.requireExecutor(), e);
1123
+ if (!n) {
1124
+ let e = Be(i);
1125
+ e && this.rememberBalanceManagerId(e);
1126
+ }
1127
+ return Z(i);
1128
+ }
1129
+ async requireBalanceManagerId(e) {
1130
+ let t = await this.resolveBalanceManagerId(e);
1131
+ if (!t) throw new d(u.BalanceManagerNotFound, "No balance manager exists for this address yet.");
1132
+ return t;
1133
+ }
1134
+ };
1135
+ function Be(e) {
1136
+ return g(e, "::balance_manager::BalanceManager")?.objectId ?? null;
1137
+ }
1138
+ function Z(e) {
1139
+ return {
1140
+ digest: e.digest,
1141
+ createdObjects: e.createdObjects,
1142
+ raw: e.raw
1143
+ };
1144
+ }
1145
+ var Ve = class {
1146
+ c;
1147
+ constructor(e) {
1148
+ this.c = e;
1149
+ }
1150
+ async get(e) {
1151
+ let t = this.c.requireAddress(e), n = await this.c.resolveBalanceManagerId(t);
1152
+ return n ? {
1153
+ balanceManagerId: n,
1154
+ owner: t
1155
+ } : null;
1156
+ }
1157
+ async ensure(t) {
1158
+ let n = this.c.requireAddress(t), r = await this.c.resolveBalanceManagerId(n);
1159
+ if (r) return {
1160
+ balanceManagerId: r,
1161
+ created: !1
1162
+ };
1163
+ let i = this.c.requireExecutor(), a = new e(), o = j(a, this.c.ids);
1164
+ a.transferObjects([o], n);
1165
+ let s = Be(await m(i, a));
1166
+ if (!s) throw new d(u.UnexpectedResponse, "Balance manager created but no created-object info found — have the executor include effects+objectTypes (v2) or objectChanges (legacy).");
1167
+ return this.c.rememberBalanceManagerId(s), {
1168
+ balanceManagerId: s,
1169
+ created: !0
1170
+ };
1171
+ }
1172
+ async depositCurrency(e) {
1173
+ if (e.amount <= 0n) throw new d(u.ValidationFailed, "Deposit amount must be positive.");
1174
+ let t = this.c.requireAddress();
1175
+ this.c.requireExecutor();
1176
+ let { tx: n, bm: r, existingBmId: i } = await this.c.beginBmTx(t), a = await V(this.c.suiClient, n, t, this.c.ids.credCoinType, e.amount, "Insufficient CRED in the wallet for this deposit.");
1177
+ return N(n, this.c.ids, r, a), this.c.finishBmTx(n, r, i, t);
1178
+ }
1179
+ async depositItems(e) {
1180
+ let t = this.c.requireAddress();
1181
+ this.c.requireExecutor();
1182
+ let n = await this.c.indexer.hubVault(e.storageUnitId), r = w(e.storageUnitId), { tx: i, bm: a, existingBmId: o } = await this.c.beginBmTx(t);
1183
+ for (let s of e.items) await H(this.c.suiClient, i, this.c.ids, a, {
1184
+ owner: t,
1185
+ ssuObjectId: r,
1186
+ vaultConfigId: n.vaultConfigId,
1187
+ vaultCollectionId: n.collectionId,
1188
+ assetId: BigInt(s.assetId),
1189
+ amount: s.amount,
1190
+ balanceManagerId: o,
1191
+ deficitMode: !1
1192
+ });
1193
+ return this.c.finishBmTx(i, a, o, t);
1194
+ }
1195
+ async withdrawCurrency(t) {
1196
+ let n = this.c.requireAddress(), r = await this.c.requireBalanceManagerId(n), i = this.c.requireExecutor(), a = new e(), o = a.object(r), s = t?.amount === void 0 ? ce(a, this.c.ids, o) : se(a, this.c.ids, o, t.amount);
1197
+ return a.transferObjects([s], n), Z(await m(i, a));
1198
+ }
1199
+ async withdrawItems(t) {
1200
+ let n = this.c.requireAddress(), r = await this.c.requireBalanceManagerId(n), i = this.c.requireExecutor(), a = await this.c.indexer.hubVault(t.storageUnitId), o = w(t.storageUnitId), s = t.characterId;
1201
+ if (!s) {
1202
+ let e = await O(this.c.suiClient, this.c.ids, n);
1203
+ if (!e) throw new d(u.CharacterNotFound, `No on-chain character resolved for ${n} — pass characterId explicitly.`);
1204
+ s = e.characterId;
1205
+ }
1206
+ let c = await k(this.c.suiClient, o, n), l = new e(), f = l.object(r);
1207
+ for (let e of t.items) {
1208
+ let t = le(l, this.c.ids, f, a.collectionId, BigInt(e.assetId));
1209
+ ue(l, this.c.ids, t, {
1210
+ ssuObjectId: o,
1211
+ characterId: s,
1212
+ vaultConfigId: a.vaultConfigId,
1213
+ collectionId: a.collectionId,
1214
+ isOwner: c !== null
1215
+ });
1216
+ }
1217
+ return Z(await m(i, l));
1218
+ }
1219
+ async sweepable() {
1220
+ let e = this.c.requireAddress(), t = await this.c.requireBalanceManagerId(e);
1221
+ return this.c.indexer.sweepable(t);
1222
+ }
1223
+ async claimSettled(t) {
1224
+ let n = this.c.requireAddress(), r = await this.c.requireBalanceManagerId(n), i = this.c.requireExecutor(), a;
1225
+ if (a = t?.poolIds?.length ? t.poolIds.map((e) => ({ poolId: e })) : (await this.c.indexer.sweepable(r)).pools.filter((e) => e.settled.base > 0n || e.settled.quote > 0n || e.settled.cred > 0n).map((e) => ({
1226
+ poolId: e.poolId,
1227
+ quoteCoinType: e.quoteAssetId ?? void 0
1228
+ })), a.length === 0) throw new d(u.ValidationFailed, "Nothing settled to claim — no pools with claimable balances.");
1229
+ let o = new e(), s = o.object(r), c = M(o, this.c.ids, s)[0];
1230
+ for (let e of a) B(o, this.c.ids, {
1231
+ poolId: e.poolId,
1232
+ bm: s,
1233
+ proof: c,
1234
+ quoteCoinType: e.quoteCoinType
1235
+ });
1236
+ return Z(await m(i, o));
1237
+ }
1238
+ }, He = class {
1239
+ c;
1240
+ constructor(e) {
1241
+ this.c = e;
1242
+ }
1243
+ async atHub(e) {
1244
+ let t = e.address ?? this.c.requireAddress(), n = await this.c.resolveBalanceManagerId(t) ?? void 0, r = e.inventoryKey;
1245
+ return !r && e.includeHangar && (r = (await O(this.c.suiClient, this.c.ids, t))?.ownerCapId), this.c.indexer.inventoryBalances({
1246
+ ...e,
1247
+ address: t,
1248
+ balanceManagerId: n,
1249
+ inventoryKey: r
1250
+ });
1251
+ }
1252
+ async currency(e) {
1253
+ let t = this.c.requireAddress(e), [n, r] = await Promise.all([re(this.c.suiClient, t, this.c.ids.credCoinType), this.c.resolveBalanceManagerId(t)]);
1254
+ return {
1255
+ wallet: n,
1256
+ balanceManager: r ? await T(this.c.suiClient, this.c.ids, r) : 0n,
1257
+ balanceManagerId: r
1258
+ };
1259
+ }
1260
+ }, Ue = class {
1261
+ c;
1262
+ constructor(e) {
1263
+ this.c = e;
1264
+ }
1265
+ discover(e) {
1266
+ return this.c.indexer.discovery(e);
1267
+ }
1268
+ async hub(e) {
1269
+ let [t, n] = await Promise.all([this.c.indexer.hubVault(e), this.c.indexer.hubLocation(e)]);
1270
+ return {
1271
+ hubId: t.hubId,
1272
+ collectionId: t.collectionId,
1273
+ vaultConfigId: t.vaultConfigId,
1274
+ location: n
1275
+ };
1276
+ }
1277
+ itemsAtHub(e) {
1278
+ return this.c.indexer.hubItems(e);
1279
+ }
1280
+ async resolvePool(e) {
1281
+ let t = await this.c.indexer.hubVault(e.storageUnitId), n = await this.c.indexer.resolvePool({
1282
+ collectionId: t.collectionId,
1283
+ assetId: e.assetId
1284
+ });
1285
+ if (!n) throw new d(u.PoolNotFound, `No pool for item ${e.assetId} at hub ${e.storageUnitId}.`);
1286
+ return n;
1287
+ }
1288
+ async orderbook(e) {
1289
+ let t = await this.resolvePool(e);
1290
+ return this.c.indexer.orderbook(t);
1291
+ }
1292
+ poolMetadata(e) {
1293
+ return this.c.indexer.poolMetadata(e);
1294
+ }
1295
+ }, We = class {
1296
+ c;
1297
+ constructor(e) {
1298
+ this.c = e;
1299
+ }
1300
+ async limit(e) {
1301
+ if (e.quantity <= 0n || e.price <= 0n) throw new d(u.ValidationFailed, "Limit orders need a positive price and quantity.");
1302
+ let t = this.c.requireAddress();
1303
+ this.c.requireExecutor();
1304
+ let n = e.side === "buy", r = await this.c.indexer.hubVault(e.storageUnitId), i = await this.requirePool(r.collectionId, e), { tx: a, bm: o, existingBmId: s } = await this.c.beginBmTx(t);
1305
+ if (!n) await H(this.c.suiClient, a, this.c.ids, o, {
1306
+ owner: t,
1307
+ ssuObjectId: w(e.storageUnitId),
1308
+ vaultConfigId: r.vaultConfigId,
1309
+ vaultCollectionId: r.collectionId,
1310
+ assetId: BigInt(e.assetId),
1311
+ amount: e.quantity,
1312
+ balanceManagerId: s,
1313
+ deficitMode: !0
1314
+ });
1315
+ else {
1316
+ let n = e.quoteDeposit;
1317
+ if (n === void 0) {
1318
+ let t = await this.c.indexer.poolMetadata(i);
1319
+ n = K(e.price, e.quantity, t.feeRateScaled);
1320
+ }
1321
+ if (n <= 0n) throw new d(u.ValidationFailed, "Invalid quote deposit amount.");
1322
+ await this.depositQuoteDeficit(a, o, s, t, n);
1323
+ }
1324
+ let c = M(a, this.c.ids, o)[0];
1325
+ return F(a, this.c.ids, {
1326
+ poolId: i,
1327
+ bm: o,
1328
+ proof: c,
1329
+ orderType: e.orderType ?? 0,
1330
+ selfMatchingOption: e.selfMatchingOption ?? 0,
1331
+ price: e.price,
1332
+ quantity: e.quantity,
1333
+ isBid: n,
1334
+ expireTimestamp: e.expireAt ?? 18446744073709551615n
1335
+ }), this.c.finishBmTx(a, o, s, t);
1336
+ }
1337
+ async market(e) {
1338
+ if (e.quantity <= 0n) throw new d(u.ValidationFailed, "Market orders need a positive quantity.");
1339
+ let t = this.c.requireAddress();
1340
+ this.c.requireExecutor();
1341
+ let n = e.side === "buy", r = await this.c.indexer.hubVault(e.storageUnitId), i = await this.requirePool(r.collectionId, e), { tx: a, bm: o, existingBmId: s } = await this.c.beginBmTx(t);
1342
+ if (!n) await H(this.c.suiClient, a, this.c.ids, o, {
1343
+ owner: t,
1344
+ ssuObjectId: w(e.storageUnitId),
1345
+ vaultConfigId: r.vaultConfigId,
1346
+ vaultCollectionId: r.collectionId,
1347
+ assetId: BigInt(e.assetId),
1348
+ amount: e.quantity,
1349
+ balanceManagerId: s,
1350
+ deficitMode: !0
1351
+ });
1352
+ else {
1353
+ if (!e.quoteBudget || e.quoteBudget <= 0n) throw new d(u.ValidationFailed, "Market buys require `quoteBudget` (see estimateMarketBuyCost).");
1354
+ let n = await this.c.indexer.poolMetadata(i), r = e.quoteBudget + he(e.quantity, n.feeRateScaled);
1355
+ await this.depositQuoteDeficit(a, o, s, t, r);
1356
+ }
1357
+ let c = M(a, this.c.ids, o)[0];
1358
+ return I(a, this.c.ids, {
1359
+ poolId: i,
1360
+ bm: o,
1361
+ proof: c,
1362
+ quantity: e.quantity,
1363
+ isBid: n,
1364
+ selfMatchingOption: e.selfMatchingOption ?? 0
1365
+ }), this.c.finishBmTx(a, o, s, t);
1366
+ }
1367
+ async cancel(e) {
1368
+ let { tx: t, bm: n, poolId: r, execute: i } = await this.beginCancelTx(e), a = M(t, this.c.ids, n)[0];
1369
+ return L(t, this.c.ids, {
1370
+ poolId: r,
1371
+ bm: n,
1372
+ proof: a,
1373
+ orderId: BigInt(e.orderId)
1374
+ }), i();
1375
+ }
1376
+ async cancelAll(e) {
1377
+ let { tx: t, bm: n, poolId: r, execute: i } = await this.beginCancelTx(e), a = M(t, this.c.ids, n)[0];
1378
+ return R(t, this.c.ids, {
1379
+ poolId: r,
1380
+ bm: n,
1381
+ proof: a
1382
+ }), i();
1383
+ }
1384
+ async modify(e) {
1385
+ if (e.newQuantity <= 0n) throw new d(u.ValidationFailed, "Modified quantity must be positive.");
1386
+ let { tx: t, bm: n, poolId: r, execute: i } = await this.beginCancelTx(e), a = M(t, this.c.ids, n)[0];
1387
+ return z(t, this.c.ids, {
1388
+ poolId: r,
1389
+ bm: n,
1390
+ proof: a,
1391
+ orderId: BigInt(e.orderId),
1392
+ newQuantity: e.newQuantity
1393
+ }), i();
1394
+ }
1395
+ async openOrders(e) {
1396
+ let t = await this.ownBm();
1397
+ return t ? this.c.indexer.openOrders(t, e) : {
1398
+ orders: [],
1399
+ nextCursor: null
1400
+ };
1401
+ }
1402
+ async fills(e) {
1403
+ let t = await this.ownBm();
1404
+ return t ? this.c.indexer.fills(t, e) : {
1405
+ fills: [],
1406
+ nextCursor: null
1407
+ };
1408
+ }
1409
+ async trades(e) {
1410
+ let t = await this.ownBm();
1411
+ return t ? this.c.indexer.trades(t, e) : {
1412
+ trades: [],
1413
+ nextCursor: null
1414
+ };
1415
+ }
1416
+ ownBm() {
1417
+ return this.c.resolveBalanceManagerId(this.c.requireAddress());
1418
+ }
1419
+ async requirePool(e, t) {
1420
+ let n = await this.c.indexer.resolvePool({
1421
+ collectionId: e,
1422
+ assetId: t.assetId
1423
+ });
1424
+ if (!n) throw new d(u.PoolNotFound, `No pool for item ${t.assetId} at hub ${t.storageUnitId}.`);
1425
+ return n;
1426
+ }
1427
+ async depositQuoteDeficit(e, t, n, r, i) {
1428
+ let a = n ? await T(this.c.suiClient, this.c.ids, n) : 0n, o = i > a ? i - a : 0n;
1429
+ if (o === 0n) return;
1430
+ let s = await V(this.c.suiClient, e, r, this.c.ids.credCoinType, o, "Insufficient CRED to fund the balance manager for this order.");
1431
+ N(e, this.c.ids, t, s);
1432
+ }
1433
+ async beginCancelTx(t) {
1434
+ let n = this.c.requireAddress(), r = await this.c.requireBalanceManagerId(n), i = this.c.requireExecutor(), a = await this.c.indexer.hubVault(t.storageUnitId), o = await this.requirePool(a.collectionId, t), s = new e();
1435
+ return {
1436
+ tx: s,
1437
+ bm: s.object(r),
1438
+ poolId: o,
1439
+ execute: async () => Z(await m(i, s))
1440
+ };
1441
+ }
1442
+ }, Ge = class {
1443
+ ids;
1444
+ indexer;
1445
+ constructor(e) {
1446
+ this.ids = l(e.network ?? "testnet", e.packageIds), this.indexer = new X(e.indexerUrl ?? "https://api.trinary.exchange", e.apiKey);
1447
+ }
1448
+ discover(e) {
1449
+ return this.indexer.discovery(e);
1450
+ }
1451
+ async hub(e) {
1452
+ let [t, n] = await Promise.all([this.indexer.hubVault(e), this.indexer.hubLocation(e)]);
1453
+ return {
1454
+ hubId: t.hubId,
1455
+ collectionId: t.collectionId,
1456
+ vaultConfigId: t.vaultConfigId,
1457
+ location: n
1458
+ };
1459
+ }
1460
+ itemsAtHub(e) {
1461
+ return this.indexer.hubItems(e);
1462
+ }
1463
+ async resolvePool(e) {
1464
+ let t = await this.indexer.hubVault(e.storageUnitId), n = await this.indexer.resolvePool({
1465
+ collectionId: t.collectionId,
1466
+ assetId: e.assetId
1467
+ });
1468
+ if (!n) throw new d(u.PoolNotFound, `No pool for item ${e.assetId} at hub ${e.storageUnitId}.`);
1469
+ return n;
1470
+ }
1471
+ async orderbook(e) {
1472
+ let t = await this.resolvePool(e);
1473
+ return this.indexer.orderbook(t);
1474
+ }
1475
+ poolMetadata(e) {
1476
+ return this.indexer.poolMetadata(e);
1477
+ }
1478
+ balancesAtHub(e) {
1479
+ return this.indexer.inventoryBalances(e);
1480
+ }
1481
+ openOrders(e, t) {
1482
+ return this.indexer.openOrders(e, t);
1483
+ }
1484
+ fills(e, t) {
1485
+ return this.indexer.fills(e, t);
1486
+ }
1487
+ trades(e, t) {
1488
+ return this.indexer.trades(e, t);
1489
+ }
1490
+ sweepable(e) {
1491
+ return this.indexer.sweepable(e);
1492
+ }
1493
+ };
1494
+ //#endregion
1495
+ //#region src/book.ts
1496
+ function Ke(e) {
1497
+ let t = [];
1498
+ for (let n of e) {
1499
+ let e = t[t.length - 1];
1500
+ e && e.price === n.price ? (e.quantity += n.remainingQuantity, e.orderCount++) : t.push({
1501
+ price: n.price,
1502
+ quantity: n.remainingQuantity,
1503
+ orderCount: 1
1504
+ });
1505
+ }
1506
+ return t;
1507
+ }
1508
+ function Q(e) {
1509
+ return e.bids[0] ?? null;
1510
+ }
1511
+ function $(e) {
1512
+ return e.asks[0] ?? null;
1513
+ }
1514
+ function qe(e) {
1515
+ let t = Q(e), n = $(e);
1516
+ return !t || !n ? null : (t.price + n.price) / 2n;
1517
+ }
1518
+ function Je(e) {
1519
+ let t = Q(e), n = $(e);
1520
+ if (!t || !n) return null;
1521
+ let r = n.price - t.price, i = (t.price + n.price) / 2n;
1522
+ return i === 0n ? {
1523
+ absolute: r,
1524
+ bps: 0
1525
+ } : {
1526
+ absolute: r,
1527
+ bps: Number(r * 10000n / i)
1528
+ };
1529
+ }
1530
+ function Ye(e) {
1531
+ let t = 0n;
1532
+ for (let n of e) t += n.remainingQuantity;
1533
+ return t;
1534
+ }
1535
+ function Xe(e) {
1536
+ let t = 0n, n = 0n;
1537
+ for (let r of e) t += r.baseQuantity, n += r.quoteQuantity;
1538
+ return t === 0n ? null : n / t;
1539
+ }
1540
+ function Ze(e, t) {
1541
+ if (t <= 0) throw Error("intervalMs must be positive");
1542
+ let n = [...e].sort((e, t) => e.tradedAt - t.tradedAt), r = [];
1543
+ for (let e of n) {
1544
+ let n = Math.floor(e.tradedAt / t) * t, i = r[r.length - 1];
1545
+ i && i.openTime === n ? (e.price > i.high && (i.high = e.price), e.price < i.low && (i.low = e.price), i.close = e.price, i.baseVolume += e.baseQuantity, i.quoteVolume += e.quoteQuantity, i.tradeCount++) : r.push({
1546
+ openTime: n,
1547
+ open: e.price,
1548
+ high: e.price,
1549
+ low: e.price,
1550
+ close: e.price,
1551
+ baseVolume: e.baseQuantity,
1552
+ quoteVolume: e.quoteQuantity,
1553
+ tradeCount: 1
1554
+ });
1555
+ }
1556
+ return r;
1557
+ }
1558
+ //#endregion
1559
+ //#region src/paging.ts
1560
+ async function* Qe(e, t, n) {
1561
+ let r = n?.maxItems ?? 1e4, i = t?.cursor, a = 0;
1562
+ for (;;) {
1563
+ let n = await e.discovery({
1564
+ ...t,
1565
+ cursor: i
1566
+ });
1567
+ for (let e of n.orders) if (yield e, ++a >= r) return;
1568
+ if (!n.nextCursor || n.orders.length === 0) return;
1569
+ i = n.nextCursor;
1570
+ }
1571
+ }
1572
+ async function* $e(e, t, n, r) {
1573
+ let i = r?.maxItems ?? 1e4, a = n?.before, o = 0;
1574
+ for (;;) {
1575
+ let r = await e.fills(t, {
1576
+ ...n,
1577
+ before: a
1578
+ });
1579
+ if (r.fills.length === 0) return;
1580
+ for (let e of r.fills) if (yield e, ++o >= i) return;
1581
+ a = r.fills[r.fills.length - 1].filledAt;
1582
+ }
1583
+ }
1584
+ async function* et(e, t, n, r) {
1585
+ let i = r?.maxItems ?? 1e4, a = n?.before, o = 0;
1586
+ for (;;) {
1587
+ let r = await e.trades(t, {
1588
+ ...n,
1589
+ before: a
1590
+ });
1591
+ if (r.trades.length === 0) return;
1592
+ for (let e of r.trades) if (yield e, ++o >= i) return;
1593
+ a = r.trades[r.trades.length - 1].tradedAt;
1594
+ }
1595
+ }
1596
+ //#endregion
1597
+ //#region src/wait.ts
1598
+ async function tt(e, t) {
1599
+ let n = t?.timeoutMs ?? 3e4, r = t?.intervalMs ?? 2e3, i = Date.now() + n;
1600
+ for (;;) {
1601
+ let a = await e();
1602
+ if (a) return a;
1603
+ if (Date.now() + r > i) throw new d(u.Timeout, `Timed out after ${n}ms waiting for ${t?.label ?? "the indexer to reflect the change"} — the indexer lags the chain by seconds; the on-chain write itself is unaffected.`);
1604
+ await new Promise((e) => setTimeout(e, r));
1605
+ }
1606
+ }
1607
+ //#endregion
1608
+ export { o as CLOCK_ID, a as DEFAULT_INDEXER_URL, W as FEE_RATE_SCALING, fe as GTC_EXPIRE, X as IndexerClient, U as MULTICOIN_PRICE_SCALING, c as NETWORK_PRESETS, Ge as ReadOnlyClient, s as STILLNESS_PACKAGE_IDS, de as TRIEXBOOK_PRICE_SCALING, ze as TriexClient, d as TriexClientError, u as TriexError, Ke as aggregateLevels, $ as bestAsk, Q as bestBid, Ze as bucketTrades, K as computeBidQuoteDeposit, G as computeItemQuote, Ye as depth, ge as estimateMarketBuyCost, m as executeAndNormalize, p as explainMoveAbort, O as fetchCharacterInfo, A as fetchInventorySlotQuantity, k as fetchSsuOwnerInfo, g as findCreatedObject, D as findOwnedItemReceipts, me as fromBase, T as getBalanceManagerCurrencyBalance, ie as getBalanceManagerItemBalance, ne as getObjectRef, E as getRegistryMulticoinCollectionId, re as getWalletCurrencyBalance, Qe as iterateDiscovery, $e as iterateFills, et as iterateTrades, he as marketBuyRoundingBuffer, qe as midPrice, h as normalizeExecuteResult, V as prepareWalletCoinInput, l as resolvePackageIds, H as sourceItemsIntoBalanceManager, Je as spread, pe as toBase, w as toSsuObjectId, ae as transactions, tt as untilIndexed, Xe as vwap };