ault-sdk-ts 0.0.2-alpha.8 → 0.3.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 (90) hide show
  1. package/README.md +378 -50
  2. package/dist/agent/attach.d.ts +26 -0
  3. package/dist/agent/sign-and-broadcast.d.ts +9 -2
  4. package/dist/agent/tx/clob.d.ts +8 -1
  5. package/dist/agent/tx-executor.d.ts +24 -2
  6. package/dist/client.d.ts +6 -7
  7. package/dist/core/clob-gas.d.ts +28 -0
  8. package/dist/core/clob-msgs.d.ts +31 -5
  9. package/dist/core/clob-responses.d.ts +20 -0
  10. package/dist/core/cloid.d.ts +4 -0
  11. package/dist/core/errors.d.ts +79 -0
  12. package/dist/core/manifest-fetcher.d.ts +12 -0
  13. package/dist/core/manifest-resolver.d.ts +131 -0
  14. package/dist/core/manifest-types.d.ts +104 -0
  15. package/dist/core/network.d.ts +42 -13
  16. package/dist/eip712/msg.generated.d.ts +26 -10
  17. package/dist/eip712/registry.d.ts +2 -0
  18. package/dist/eip712/sign-and-broadcast.d.ts +27 -3
  19. package/dist/high-level/cloid-lookup.d.ts +9 -0
  20. package/dist/high-level/create-client.d.ts +15 -11
  21. package/dist/high-level/tx/accountx.d.ts +3 -0
  22. package/dist/high-level/tx/agent.d.ts +1 -1
  23. package/dist/high-level/tx/clob.d.ts +1 -1
  24. package/dist/high-level/tx/context.d.ts +8 -0
  25. package/dist/high-level/tx/license.d.ts +1 -1
  26. package/dist/high-level/tx/miner.d.ts +1 -1
  27. package/dist/high-level/tx/reward.d.ts +1 -1
  28. package/dist/high-level/tx/staking.d.ts +1 -1
  29. package/dist/high-level/tx-executor.d.ts +23 -3
  30. package/dist/high-level/types.d.ts +356 -100
  31. package/dist/high-level-client.d.ts +1 -1
  32. package/dist/index.cjs +15590 -7271
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.ts +10 -1
  35. package/dist/index.js +15699 -7405
  36. package/dist/index.js.map +1 -1
  37. package/dist/proto/gen/ault/accountx/v1/genesis.d.ts +38 -0
  38. package/dist/proto/gen/ault/accountx/v1/params.d.ts +32 -0
  39. package/dist/proto/gen/ault/accountx/v1/query.d.ts +88 -0
  40. package/dist/proto/gen/ault/accountx/v1/tx.d.ts +52 -0
  41. package/dist/proto/gen/ault/agent/v1/tx.d.ts +4 -5
  42. package/dist/proto/gen/ault/authority/v1/authority.d.ts +2 -0
  43. package/dist/proto/gen/ault/clob/v1/genesis.d.ts +6 -5
  44. package/dist/proto/gen/ault/clob/v1/query.d.ts +14 -0
  45. package/dist/proto/gen/ault/clob/v1/tx.d.ts +30 -3
  46. package/dist/proto/gen/ault/common/v1/system.d.ts +31 -0
  47. package/dist/proto/gen/ault/license/v1/genesis.d.ts +1 -26
  48. package/dist/proto/gen/ault/license/v1/license.d.ts +0 -26
  49. package/dist/proto/gen/ault/license/v1/query.d.ts +44 -18
  50. package/dist/proto/gen/ault/market/v1/market.d.ts +1 -0
  51. package/dist/proto/gen/ault/market/v1/tx.d.ts +9 -0
  52. package/dist/proto/gen/ault/miner/v1/genesis.d.ts +52 -84
  53. package/dist/proto/gen/ault/miner/v1/miner.d.ts +10 -45
  54. package/dist/proto/gen/ault/miner/v1/query.d.ts +0 -13
  55. package/dist/proto/gen/ault/spot/v1/genesis.d.ts +2 -2
  56. package/dist/proto/gen/ault/spot/v1/order.d.ts +12 -4
  57. package/dist/proto/gen/ault/systemtx/v1/genesis.d.ts +37 -0
  58. package/dist/proto/gen/ault/tokenregistry/v1/genesis.d.ts +3 -3
  59. package/dist/proto/gen/ault/tokenregistry/v1/query.d.ts +2 -2
  60. package/dist/proto/gen/ault/tokenregistry/v1/tokenregistry.d.ts +24 -15
  61. package/dist/proto/gen/ault/tokenregistry/v1/tx.d.ts +1 -16
  62. package/dist/proto/gen/cosmos/bank/v1beta1/bank.d.ts +119 -0
  63. package/dist/proto/gen/cosmos/bank/v1beta1/query.d.ts +264 -0
  64. package/dist/proto/gen/cosmos/distribution/v1beta1/query.d.ts +203 -0
  65. package/dist/proto/gen/cosmos/query/v1/query.d.ts +1 -0
  66. package/dist/proto/gen/cosmos/staking/v1beta1/query.d.ts +275 -0
  67. package/dist/proto/gen/google/api/http.d.ts +20 -28
  68. package/dist/proto/gen/tendermint/abci/types.d.ts +23 -0
  69. package/dist/proto/tx-decode.d.ts +18 -0
  70. package/dist/rest/accountx.d.ts +8 -0
  71. package/dist/rest/bank.d.ts +15 -0
  72. package/dist/rest/clob.d.ts +9 -1
  73. package/dist/rest/context.d.ts +4 -4
  74. package/dist/rest/dex-types.generated.d.ts +434 -120
  75. package/dist/rest/dex.d.ts +7 -0
  76. package/dist/rest/dex.generated.d.ts +657 -83
  77. package/dist/rest/feemarket.d.ts +114 -0
  78. package/dist/rest/license.d.ts +21 -59
  79. package/dist/rest/miner.d.ts +16 -46
  80. package/dist/rest/portfolio.d.ts +103 -0
  81. package/dist/rest/staking.d.ts +14 -28
  82. package/dist/rest/tokenregistry.d.ts +3 -1
  83. package/dist/rest/types.d.ts +82 -858
  84. package/dist/utils/address.d.ts +2 -0
  85. package/dist/utils/opaque-id.d.ts +25 -0
  86. package/dist/utils/tx-hash.d.ts +1 -0
  87. package/dist/ws/client.d.ts +45 -5
  88. package/dist/ws/types.d.ts +379 -34
  89. package/package.json +2 -1
  90. package/dist/agent/create-agent-client.d.ts +0 -3
package/README.md CHANGED
@@ -164,9 +164,148 @@ interface ClientOptions {
164
164
  fetchOptions?: FetchWithRetryOptions;
165
165
  defaultGasLimit?: string; // Optional: default gas limit
166
166
  defaultMemo?: string; // Optional: default memo
167
+ defaultConfirmationTimeoutMs?: number;
168
+ manifestOverride?: Manifest; // Optional: caller-supplied manifest layer (see "SDK Manifest")
167
169
  }
168
170
  ```
169
171
 
172
+ ## SDK Manifest
173
+
174
+ `createClient` resolves network endpoints and gas/EIP-712 defaults from three
175
+ layers, in increasing precedence:
176
+
177
+ 1. The embedded baseline shipped with the SDK (`NetworkConfig` plus
178
+ `GAS_CONSTANTS`).
179
+ 2. The manifest fetched from `<dexApiUrl>/api/v1/sdk-manifest` at bootstrap
180
+ and refreshed every five minutes in the background. The operator
181
+ rotates URLs, EIP-712 fee defaults, and per-module gas constants by
182
+ editing the dex-api `SDK_MANIFEST_JSON` env var; older SDK versions
183
+ pick up the new values within one refresh window without a package
184
+ bump.
185
+ 3. An optional `manifestOverride` you pass to `createClient`. The
186
+ override sits on top of both other layers, is frozen for the
187
+ lifetime of the client, and is not touched by background refreshes.
188
+
189
+ The override layer covers cases the fetched manifest cannot: pointing the
190
+ client at a private RPC during local development, pinning a deterministic
191
+ manifest in tests, surviving a URL rotation cutover by keeping the old
192
+ endpoint until you redeploy, or tuning gas constants without waiting on a
193
+ manifest deploy.
194
+
195
+ ```typescript
196
+ import { createClient, getNetworkConfig, type Manifest } from "ault-sdk-ts";
197
+
198
+ const manifestOverride: Manifest = {
199
+ schemaVersion: 1,
200
+ urls: {
201
+ rpc: "https://rpc.internal.example.com",
202
+ },
203
+ gas: {
204
+ LIMIT_ORDER: 250000,
205
+ },
206
+ };
207
+
208
+ const client = await createClient({
209
+ network: getNetworkConfig("ault_10904-1"),
210
+ signer: account,
211
+ manifestOverride,
212
+ });
213
+ ```
214
+
215
+ The override is sparse — every field is optional and only the keys you set
216
+ take effect. Disjoint keys still flow through from the fetched manifest, so
217
+ `{gas: {LIMIT_ORDER: 250000}}` does not erase a `MARKET_ORDER` value the
218
+ dex-api emits. Unknown top-level keys pass through untouched for forward
219
+ compatibility with future manifest fields.
220
+
221
+ ### Supported fields
222
+
223
+ The `Manifest` type has four top-level keys. `schemaVersion` is required; the
224
+ three sub-objects are optional and each one is itself sparse.
225
+
226
+ ```typescript
227
+ interface Manifest {
228
+ schemaVersion: number; // required, integer >= 1
229
+ urls?: Partial<ManifestUrls>;
230
+ eip712?: Partial<ManifestEip712>;
231
+ gas?: Partial<ManifestGas>;
232
+ // unknown top-level keys are preserved for forward compatibility
233
+ }
234
+ ```
235
+
236
+ **`urls`** — endpoint overrides. Each value is a string and applies only if
237
+ non-empty. The `dexApiUrl` itself is not overridable here (it is the trust
238
+ root for the fetched manifest).
239
+
240
+ | Key | Maps to `NetworkConfig` field |
241
+ | ---------- | ----------------------------- |
242
+ | `rpc` | `rpcUrl` |
243
+ | `rest` | `restUrl` |
244
+ | `evm` | `evmRpcUrl` |
245
+ | `explorer` | `explorerUrl` |
246
+ | `dexWs` | `dexWsUrl` |
247
+
248
+ URL rotations propagate to the tx executor on the next call but not to the
249
+ REST/WS contexts captured at `createClient` time. Re-create the client to
250
+ pick up new endpoints across the board.
251
+
252
+ **`eip712`** — fee defaults applied to every transaction unless per-call
253
+ options override them.
254
+
255
+ | Key | Type | Notes |
256
+ | ----------- | -------------------------------- | ------------------------------ |
257
+ | `feeDenom` | non-empty string | replaces `GAS_CONSTANTS.DENOM` |
258
+ | `feeAmount` | non-negative integer string | raw `aault`, `"0"` allowed |
259
+ | `gasLimit` | strictly positive integer string | gas units, `"0"` rejected |
260
+
261
+ **`gas`** — per-message-type gas constants and the fee-free multiplier.
262
+ Every value is a positive integer. Keys outside the supported list are
263
+ dropped silently and the embedded baseline keeps applying.
264
+
265
+ The keys most consumers will touch are the CLOB ones plus the fee-free
266
+ multiplier:
267
+
268
+ | Key | Used by |
269
+ | ------------------------- | ---------------------------------------- |
270
+ | `FEE_FREE_GAS_MULTIPLIER` | fee-free gas computation across all msgs |
271
+ | `LIMIT_ORDER` | `placeLimitOrder` |
272
+ | `MARKET_ORDER` | `placeMarketOrder` |
273
+ | `SCALE_ORDER_BASE` | `placeScaleOrder` (base cost) |
274
+ | `SCALE_ORDER_PER_SUB` | `placeScaleOrder` (per sub-order) |
275
+ | `CANCEL_ORDER_BASE` | `cancelOrders` (base cost) |
276
+ | `CANCEL_ORDER_PER_ID` | `cancelOrders` (per order id) |
277
+
278
+ The schema also accepts per-message gas constants for the license,
279
+ miner, agent, reward, and accountx modules (`PER_LICENSE`,
280
+ `PER_DELEGATE_MINING`, `APPROVE_AGENT`, `SET_REFERRAL_CODE`,
281
+ `OPEN_ACCOUNT`, and the rest). These exist for operator-side
282
+ deploy-cycle bypass and are rarely needed in consumer code. The full
283
+ list lives in `ManifestGasSchema` in `src/core/manifest-types.ts`.
284
+
285
+ The `gas` blob never accepts `EIP712_FEE_AMOUNT`, `EIP712_GAS_LIMIT`, or
286
+ `DENOM` — those live on `eip712` as `feeAmount`, `gasLimit`, and
287
+ `feeDenom`. Smuggling them through `gas` is dropped defensively because
288
+ the broadcast layer never reads them off the gas object.
289
+
290
+ The value validates against `ManifestSchema` synchronously at `createClient`
291
+ time. A malformed override throws straight away with the schema error
292
+ instead of falling back to the baseline the way a broken fetched manifest
293
+ does, since override data comes from your code and a typo is a bug worth
294
+ surfacing loudly. The caller's object is deep-cloned at construction, so
295
+ mutating it after `createClient` returns does not affect resolver state.
296
+
297
+ When a non-empty override is present, the resolver emits one
298
+ `console.info` line at boot listing the override key paths (never values,
299
+ since `urls` may carry private endpoints).
300
+
301
+ If you also use `client.attachAgent(...)`, the agent surface reuses the
302
+ same manifest resolver, so the override flows through to agent-signed
303
+ transactions without separate plumbing.
304
+
305
+ The package also re-exports the low-level helpers if you need them:
306
+ `mergeManifests`, `fetchManifest`, `applyNetworkOverrides`,
307
+ `applyGasOverrides`, `createManifestResolver`, `createStaticResolver`.
308
+
170
309
  ## Query Methods
171
310
 
172
311
  The client provides pass-through access to all REST API methods:
@@ -238,8 +377,18 @@ const candles = await dex.getOHLCV("AULT/USDT", {
238
377
  timeframe: "1h",
239
378
  limit: 100,
240
379
  });
380
+
381
+ // Protocol stats (24h window)
382
+ const stats = await dex.getStats(); // defaults to { window: "24h" }
383
+ console.log(stats.totals.quoteVolume); // "1234567.89" or null when markets span multiple quotes
384
+ console.log(stats.totals.tradeCount, stats.totals.traderCount);
385
+ for (const m of stats.markets) {
386
+ console.log(m.symbol, m.quoteVolume, m.tradeCount);
387
+ }
241
388
  ```
242
389
 
390
+ Monetary fields like `quoteVolume`, `estimatedFee`, and `averageSlippageBps` come back as canonical decimal strings, so parse them with a decimal library rather than `parseFloat`. `totals.quoteVolume` and its related fee fields are `null` when the markets that traded in the window span more than one quote asset, since summing notionals across quotes is meaningless. `markets[]` can briefly lag `totals` while the symbol map updates, so the per-market trade counts need not add up to `totals.tradeCount`.
391
+
243
392
  ### User Queries
244
393
 
245
394
  ```typescript
@@ -254,6 +403,9 @@ const orders = await dex.listOrders({
254
403
  // Single order by ID
255
404
  const order = await dex.getOrder("010000000000000000000002");
256
405
 
406
+ // Single trade by its synthesized ID (block_height-hex(order_id)-open_quantity)
407
+ const trade = await dex.getTrade("12345-00010000000000003039000000000002-999");
408
+
257
409
  // User's trade history
258
410
  const myTrades = await dex.listMyTrades({
259
411
  address: "ault1...",
@@ -295,7 +447,7 @@ const tsMarks = await dex.getUDFTimescaleMarks({
295
447
 
296
448
  ## DEX WebSocket
297
449
 
298
- The SDK includes a WebSocket client for real-time streaming from the DEX API. All payload types are shared with the REST client — no extra types needed.
450
+ The SDK ships a WebSocket client for streaming live data from the DEX API. It speaks the v2 subscription protocol: open one connection, subscribe to channels, and receive `{ channel, data }` frames. The payload types are WebSocket-native (they differ from the REST shapes) and are exported from the SDK.
299
451
 
300
452
  ### Connecting
301
453
 
@@ -319,34 +471,39 @@ const ws = createDexWs("wss://my-dex-api.example.com/ws");
319
471
  await ws.connect();
320
472
  ```
321
473
 
322
- ### Subscribing to Topics
474
+ ### Subscribing to Channels
323
475
 
324
- Subscriptions are type-safe — the `onData` callback is automatically typed based on the topic string.
476
+ Pass a subscription descriptor and the `onData` callback is typed from its `type`. Market channels need a `coin`; the `candle` channel also needs an `interval`. Frames flow through `onData` as they arrive. For snapshot-gated channels the first frame is the snapshot and the rest are deltas, so don't assume the first frame is a delta.
325
477
 
326
478
  ```typescript
327
- // Orderbook snapshots (data typed as OrderbookResponse)
328
- const sub = client.ws.subscribe("orderbook:AULT/USDT", {
329
- onData: (orderbook) => {
330
- console.log(orderbook.bids[0], orderbook.asks[0]);
479
+ // L2 order book — snapshot first, then per-block deltas (data typed as WsBook)
480
+ const sub = client.ws.subscribe(
481
+ { type: "l2Book", coin: "AULT/USDC" },
482
+ {
483
+ onData: (book) => {
484
+ const [bids, asks] = book.levels;
485
+ console.log(bids[0], asks[0]); // { px, sz, n }
486
+ },
331
487
  },
332
- });
488
+ );
333
489
 
334
- // Trades (data typed as TradeResponse[])
335
- client.ws.subscribe("trades:AULT/USDT", {
336
- onData: (trades) => {
337
- for (const t of trades) console.log(t.side, t.price, t.amount);
338
- },
339
- });
490
+ // Trades in each block (data typed as WsTrade[])
491
+ client.ws.subscribe(
492
+ { type: "trades", coin: "AULT/USDC" },
493
+ { onData: (trades) => trades.forEach((t) => console.log(t.side, t.px, t.sz)) },
494
+ );
340
495
 
341
- // 24h ticker (data typed as TickerResponse)
342
- client.ws.subscribe("ticker:AULT/USDT", {
343
- onData: (ticker) => console.log(ticker.last, ticker.percentage),
344
- });
496
+ // Best bid / offer (data typed as WsBbo)
497
+ client.ws.subscribe(
498
+ { type: "bbo", coin: "AULT/USDC" },
499
+ { onData: (b) => console.log(b.bbo[0], b.bbo[1]) },
500
+ );
345
501
 
346
- // OHLCV candles (data typed as OHLCVEntry)
347
- client.ws.subscribe("chart:AULT/USDT:60", {
348
- onData: (bar) => console.log(bar), // [timestamp, o, h, l, c, v]
349
- });
502
+ // Candles (data typed as WsCandle[])
503
+ client.ws.subscribe(
504
+ { type: "candle", coin: "AULT/USDC", interval: "1m" },
505
+ { onData: (bars) => console.log(bars[bars.length - 1]) },
506
+ );
350
507
 
351
508
  // Unsubscribe
352
509
  sub.unsubscribe();
@@ -354,15 +511,16 @@ sub.unsubscribe();
354
511
 
355
512
  ### Subscription Options
356
513
 
514
+ `ttl` sets a subscription lifetime in seconds (the server caps it at 3,600). The ack carries the effective, clamped value.
515
+
357
516
  ```typescript
358
- // TTL: auto-expire after 300 seconds
359
517
  client.ws.subscribe(
360
- "orderbook:AULT/USDT",
518
+ { type: "l2Book", coin: "AULT/USDC" },
361
519
  {
362
520
  onData: (data) => {
363
521
  /* ... */
364
522
  },
365
- onSubscribed: () => console.log("subscribed!"),
523
+ onSubscribed: (ack) => console.log("subscribed; effective ttl", ack.ttl),
366
524
  onExpired: () => console.log("subscription expired"),
367
525
  onError: (err) => console.error(err),
368
526
  },
@@ -370,28 +528,33 @@ client.ws.subscribe(
370
528
  );
371
529
  ```
372
530
 
373
- ### Address Topics
531
+ ### User channels
374
532
 
375
- Address topics (`orders`, `balances`, `mytrades`) expose read-only projections
376
- of public on-chain state — no authentication is required:
533
+ User channels key on an address (`ault1...` or `0x...`, either case) and expose read-only projections of public on-chain state, so no authentication is required. The address round-trips in the ack in the format you sent.
377
534
 
378
535
  ```typescript
379
- // Orders (data typed as OrderResponse[])
380
- client.ws.subscribe("orders:ault1...", {
381
- onData: (orders) => {
382
- for (const o of orders) console.log(o.id, o.status, o.filled);
536
+ // Order updates (data typed as WsOrderUpdate[])
537
+ client.ws.subscribe(
538
+ { type: "orderUpdates", user: "ault1..." },
539
+ {
540
+ onData: (orders) => orders.forEach((o) => console.log(o.order.oid, o.status, o.chainStatus)),
383
541
  },
384
- });
542
+ );
385
543
 
386
- // Balances (data typed as BalancesResponse)
387
- client.ws.subscribe("balances:ault1...", {
388
- onData: (balances) => console.log(balances.free),
389
- });
544
+ // Spot balances — first frame is the full set, later frames are per-coin deltas
545
+ client.ws.subscribe(
546
+ { type: "spotState", user: "ault1..." },
547
+ { onData: (state) => console.log(state.spotState.balances) },
548
+ );
390
549
 
391
- // User trades (data typed as TradeResponse[])
392
- client.ws.subscribe("mytrades:ault1...", {
393
- onData: (trades) => console.log(trades[0].order, trades[0].price),
394
- });
550
+ // Fills — the snapshot frame carries isSnapshot: true, live frames false
551
+ client.ws.subscribe(
552
+ { type: "userFills", user: "ault1..." },
553
+ { onData: (f) => console.log(f.isSnapshot, f.fills) },
554
+ );
555
+
556
+ // userEvents data arrives on the wire "user" channel; the SDK routes it back here
557
+ client.ws.subscribe({ type: "userEvents", user: "ault1..." }, { onData: (ev) => console.log(ev) });
395
558
  ```
396
559
 
397
560
  ### Connection Events
@@ -404,12 +567,12 @@ client.ws.on("reconnecting", (attempt) => console.log("reconnecting...", attempt
404
567
  client.ws.on("reconnected", () => console.log("reconnected"));
405
568
 
406
569
  // Raw message listener
407
- client.ws.on("message", (msg) => console.log(msg.topic, msg.event));
570
+ client.ws.on("message", (msg) => console.log(msg.channel, msg.data));
408
571
  ```
409
572
 
410
573
  ### Reconnection
411
574
 
412
- Auto-reconnect is enabled by default with exponential backoff. On reconnect, all active subscriptions are automatically restored (including re-authentication if needed).
575
+ Auto-reconnect is enabled by default with exponential backoff. On reconnect, every active subscription is re-sent with its original TTL.
413
576
 
414
577
  ```typescript
415
578
  const ws = createDexWs("wss://my-dex-api.example.com/ws", {
@@ -477,11 +640,18 @@ interface TxResult {
477
640
  txHash: string; // Transaction hash
478
641
  code: number; // Result code (0 = success)
479
642
  rawLog?: string; // Raw log from transaction
480
- confirmed?: boolean; // true = definitive result, false = timed out, undefined = confirmation lookup unavailable
643
+ confirmed?: boolean; // true = DeliverTx observed; false = broadcast-only or poll timeout; undefined = confirmation lookup unavailable
481
644
  success: boolean; // True only when DeliverTx success was confirmed
482
645
  }
483
646
  ```
484
647
 
648
+ The CLOB order methods (`placeLimitOrder`, `placeMarketOrder`,
649
+ `placeScaleOrder`, `cancelOrders`) default to broadcast-only: they return once
650
+ CheckTx accepts the transaction, so the result has `confirmed: false` and
651
+ `success: false`. Pass `wait: true` to poll for DeliverTx and get back the
652
+ decoded order IDs. See [Market And CLOB
653
+ Transactions](#market-and-clob-transactions).
654
+
485
655
  ### License Transactions
486
656
 
487
657
  ```typescript
@@ -582,25 +752,62 @@ await client.updateOperatorInfo({
582
752
  ```typescript
583
753
  import { base64ToBytes } from "ault-sdk-ts";
584
754
 
585
- // Place a limit order
755
+ const marketId = base64ToBytes("base64MarketId...");
756
+
757
+ // Place a limit order (broadcast-only: returns once CheckTx accepts it).
586
758
  await client.placeLimitOrder({
587
- marketId: 1,
759
+ marketId,
588
760
  isBuy: true,
589
761
  price: "1.5",
590
762
  quantity: "100",
591
763
  lifespan: { seconds: 3600n, nanos: 0 }, // 1 hour
592
764
  });
593
765
 
766
+ // Pass `wait: true` to poll for DeliverTx and read back the order ID.
767
+ const placed = await client.placeLimitOrder({
768
+ marketId,
769
+ isBuy: true,
770
+ price: "1.5",
771
+ quantity: "100",
772
+ lifespan: { seconds: 3600n, nanos: 0 },
773
+ wait: true,
774
+ });
775
+ console.log(placed.orderId);
776
+
594
777
  // Place a market order
595
778
  await client.placeMarketOrder({
596
- marketId: 1,
779
+ marketId,
597
780
  isBuy: true,
598
781
  deposit: "100",
599
782
  });
600
783
 
601
- // Cancel specific orders
784
+ // Cancel specific orders. With `wait: true` the result lists which IDs
785
+ // succeeded and which failed.
602
786
  await client.cancelOrders({ orderIds: [base64ToBytes("base64OrderId...")] });
603
787
 
788
+ // Client order id (cloid): attach an 8-byte id to an order so you can address
789
+ // it without the chain-assigned order id. It is echoed back (as hex) on the
790
+ // wait-mode result, and cancelOrders accepts a cloid or an order id
791
+ // interchangeably.
792
+ const cloid = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
793
+ const withCloid = await client.placeLimitOrder({
794
+ marketId,
795
+ isBuy: true,
796
+ price: "1.5",
797
+ quantity: "100",
798
+ deadline: new Date(Date.now() + 3600_000),
799
+ cloid,
800
+ wait: true,
801
+ });
802
+ console.log(withCloid.cloid); // "0102030405060708"
803
+
804
+ await client.cancelOrders({ orderIds: [cloid] });
805
+
806
+ // Look up an order by (orderer, cloid), chain-first with a dex-api fallback.
807
+ // Live orders resolve from the chain; filled/cancelled ones from the indexer.
808
+ const found = await client.findOrderByCloid(client.address, cloid);
809
+ if (found.source !== "none") console.log(found.source, found.order);
810
+
604
811
  // Create a market
605
812
  await client.createMarket({
606
813
  marketType: MarketType.MARKET_TYPE_SPOT,
@@ -648,6 +855,119 @@ await client.delegateMining({
648
855
  });
649
856
  ```
650
857
 
858
+ ## Agent-Signed Transactions
859
+
860
+ The chain's `agent` module lets a master account approve a separate keypair to
861
+ submit a restricted set of CLOB transactions on its behalf, without prompting
862
+ the master signer for each one. Typical use cases: market-making bots that
863
+ sign hot orders with a short-lived key, or trading UIs that sign orders
864
+ without a wallet popup per click.
865
+
866
+ The SDK exposes this through `client.attachAgent(...)` rather than a separate
867
+ client. The agent surface reuses the master client's manifest resolver, REST
868
+ contexts, and account-info cache — one network state, one of every cached
869
+ resource, no chance of drift between wallet-signed and agent-signed paths.
870
+
871
+ ### Approve and attach an agent
872
+
873
+ ```typescript
874
+ import { createClient, encodeEthSecp256k1PubKey, deriveAgentAddress } from "ault-sdk-ts";
875
+ import { secp256k1 } from "@noble/curves/secp256k1";
876
+ import { hexToBytes } from "viem";
877
+
878
+ const client = await createClient({ network, signer: masterSigner });
879
+
880
+ // 1. Generate (or load) the agent keypair.
881
+ const agentPrivateKey = `0x${"a".repeat(64)}`; // load from secret store in real usage
882
+ const compressed = secp256k1.getPublicKey(hexToBytes(agentPrivateKey), true);
883
+ const agentPubkey = {
884
+ typeUrl: "/cosmos.evm.crypto.v1.ethsecp256k1.PubKey",
885
+ value: encodeEthSecp256k1PubKey(compressed),
886
+ };
887
+
888
+ // 2. Master approves the agent on-chain (wallet-signed).
889
+ await client.approveAgent({
890
+ agentPubkey,
891
+ name: "market-maker-bot",
892
+ expiry: { seconds: 86_400n * 30n, nanos: 0 }, // 30 days
893
+ });
894
+
895
+ // 3. Attach the agent surface to this client.
896
+ const agent = client.attachAgent({ agentPrivateKey });
897
+ console.log(agent.address); // bech32 agent address
898
+ console.log(agent.masterAddress); // = client.address
899
+ console.log(client.asAgent === agent); // true
900
+ ```
901
+
902
+ ### Place agent-signed orders
903
+
904
+ ```typescript
905
+ // Same shape as the wallet-signed equivalents on `client.*`, including the
906
+ // broadcast-only default and the `wait: true` opt-in for a result with the
907
+ // decoded order ID.
908
+ const placed = await client.asAgent!.placeLimitOrder({
909
+ marketId,
910
+ isBuy: true,
911
+ price: "1.0",
912
+ quantity: "1000000000000000000",
913
+ lifespan: { seconds: 3600n, nanos: 0 },
914
+ wait: true,
915
+ });
916
+ console.log(placed.orderId);
917
+
918
+ await client.asAgent!.placeMarketOrder({
919
+ marketId,
920
+ isBuy: true,
921
+ deposit: "5000000000000000000",
922
+ });
923
+
924
+ await client.asAgent!.cancelOrders({ orderIds: [...] });
925
+
926
+ await client.asAgent!.placeScaleOrder({
927
+ marketId,
928
+ isBuy: true,
929
+ lowPrice: "0.9",
930
+ highPrice: "1.1",
931
+ totalQuantity: "10000000000000000000",
932
+ weights: [3333, 3334, 3333],
933
+ lifespan: { seconds: 3600n, nanos: 0 },
934
+ });
935
+ ```
936
+
937
+ ### Rotate or detach the agent
938
+
939
+ ```typescript
940
+ // Rotate: attachAgent replaces the prior agent in place. The previous
941
+ // surface is overwritten — read from `client.asAgent` after attaching.
942
+ client.attachAgent({ agentPrivateKey: newKey });
943
+
944
+ // Detach: clears `client.asAgent`. Idempotent.
945
+ client.detachAgent();
946
+
947
+ // Revoke on-chain (wallet-signed) when the agent should no longer sign.
948
+ await client.revokeAgent({ agentAddress: agent.address });
949
+ ```
950
+
951
+ ### What `attachAgent` shares with the master client
952
+
953
+ | Resource | Behavior |
954
+ | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
955
+ | `ManifestResolver` | One per `Client`. The agent path reads `getNetwork()` / `getGas()` from the same resolver, so URL and EIP-712 manifest overrides reach both signing paths atomically. |
956
+ | `AccountCache` | The master's `accountNumber` is fetched once. The agent path reads it from the shared cache; it never increments `nextSequence` (agent txs always sign with `sequence=0`). |
957
+ | REST/WS contexts | The master client's `client.<module>` query APIs are the only query surface — the agent surface is tx-only. |
958
+ | Lifecycle | `client.dispose()` clears `asAgent` and stops the manifest refresh timer. Calling `attachAgent` after `dispose()` throws. |
959
+
960
+ ### Notes
961
+
962
+ - `client.asAgent` is `null` until `attachAgent` is called. After detach or
963
+ dispose it is `null` again. Always read it fresh; do not cache references
964
+ across rotations.
965
+ - `attachAgent` is synchronous (no network I/O). The first agent tx may
966
+ trigger one `queryAccount` RPC if the cache is cold; subsequent agent
967
+ txs reuse the cached `accountNumber`.
968
+ - Two concurrent agents from the same master require two `Client`
969
+ instances — `attachAgent` replaces, it does not coexist.
970
+
651
971
  ## Development
652
972
 
653
973
  ### Generating Protos
@@ -874,12 +1194,20 @@ Pre-release tags publish to a separate npm dist-tag so they never become the def
874
1194
 
875
1195
  ```bash
876
1196
  # Set the pre-release version
1197
+ git checkout master
1198
+ git pull
1199
+ git checkout -b "release/v0.1.0-alpha.1"
877
1200
  npm version 0.1.0-alpha.1 --no-git-tag-version
878
-
879
1201
  git add package.json
880
1202
  git commit -m "chore: release v0.1.0-alpha.1"
1203
+ git push origin release/v0.1.0-alpha.1
1204
+
1205
+ # Create PR and merge to master
1206
+
1207
+ git checkout master
1208
+ git pull
881
1209
  git tag v0.1.0-alpha.1
882
- git push origin master v0.1.0-alpha.1
1210
+ git push origin v0.1.0-alpha.1
883
1211
  ```
884
1212
 
885
1213
  Consumers install with the corresponding tag:
@@ -0,0 +1,26 @@
1
+ import type { AccountCache } from "../eip712/sign-and-broadcast";
2
+ import type { FetchFn, FetchWithRetryOptions } from "../core/http";
3
+ import type { GAS_CONSTANTS, NetworkConfig } from "../core/network";
4
+ import type { AgentSurface, AttachAgentOptions } from "../high-level/types";
5
+ export { AGENT_DEFAULTS } from "./sign-and-broadcast";
6
+ /**
7
+ * Derives the agent's bech32 address from its private key. Mirrors the
8
+ * EVM-style derivation used by the chain's agent module: keccak256 of the
9
+ * uncompressed pubkey, take the lower 20 bytes, encode as bech32.
10
+ */
11
+ export declare function deriveAgentAddress(privateKeyHex: string): string;
12
+ export interface BuildAgentSurfaceContext {
13
+ masterAddress: string;
14
+ getNetwork: () => NetworkConfig;
15
+ getGas: () => typeof GAS_CONSTANTS;
16
+ cache: AccountCache;
17
+ fetchFn?: FetchFn;
18
+ fetchOptions?: FetchWithRetryOptions;
19
+ }
20
+ /**
21
+ * Builds the agent-signed CLOB tx surface attached to a `Client`. Reuses
22
+ * the client's manifest resolver (via `getNetwork` / `getGas`) and master
23
+ * account-info cache (via `cache`) so attaching does not trigger a manifest
24
+ * fetch or a duplicate account RPC.
25
+ */
26
+ export declare function buildAgentSurface(options: AttachAgentOptions, ctx: BuildAgentSurfaceContext): AgentSurface;
@@ -21,6 +21,12 @@ export interface AgentSignAndBroadcastParams {
21
21
  memo?: string;
22
22
  gasLimit?: string;
23
23
  confirmationTimeoutMs?: number;
24
+ /**
25
+ * When `true` (default), poll for DeliverTx after a successful CheckTx. When
26
+ * `false`, return immediately after CheckTx acceptance with `confirmed: false`.
27
+ * A CheckTx rejection throws in both modes.
28
+ */
29
+ wait?: boolean;
24
30
  timeoutSeconds?: number;
25
31
  timeoutTimestamp?: {
26
32
  seconds: bigint;
@@ -30,9 +36,10 @@ export interface AgentSignAndBroadcastParams {
30
36
  fetchOptions?: FetchWithRetryOptions;
31
37
  cache?: AccountCache;
32
38
  }
33
- export declare function signAndBroadcastAgentTx({ network, keyMaterial, masterAddress, msgs, memo, gasLimit, confirmationTimeoutMs, timeoutSeconds, timeoutTimestamp, fetchFn, fetchOptions, cache, }: AgentSignAndBroadcastParams): Promise<{
39
+ export declare function signAndBroadcastAgentTx({ network, keyMaterial, masterAddress, msgs, memo, gasLimit, confirmationTimeoutMs, wait, timeoutSeconds, timeoutTimestamp, fetchFn, fetchOptions, cache, }: AgentSignAndBroadcastParams): Promise<{
34
40
  txHash: string;
35
41
  code: number;
36
42
  rawLog?: string;
37
- confirmed?: boolean;
43
+ data?: string;
44
+ confirmed: boolean;
38
45
  }>;
@@ -1,7 +1,14 @@
1
+ import type { GAS_CONSTANTS } from "../../core/network";
1
2
  import type { AgentClobTxApi } from "../../high-level/types";
2
3
  import type { AgentTxExecutor } from "../tx-executor";
3
4
  export interface AgentClobTxContext {
4
5
  masterAddress: string;
5
6
  exec: AgentTxExecutor;
7
+ /**
8
+ * Returns the current gas constants — base GAS_CONSTANTS overlaid with any
9
+ * manifest overrides for the active client. Read on each tx so a hot-swap
10
+ * (manifest refresh) takes effect on the next call.
11
+ */
12
+ getGas: () => typeof GAS_CONSTANTS;
6
13
  }
7
- export declare function createAgentClobTxApi({ masterAddress, exec }: AgentClobTxContext): AgentClobTxApi;
14
+ export declare function createAgentClobTxApi({ masterAddress, exec, getGas, }: AgentClobTxContext): AgentClobTxApi;
@@ -2,8 +2,21 @@ import type { FetchFn, FetchWithRetryOptions } from "../core/http";
2
2
  import { type NetworkConfig } from "../core/network";
3
3
  import type { AnyEip712Msg } from "../eip712/builder";
4
4
  import type { AgentTxOptions, TxResult } from "../high-level/types";
5
+ import { type AccountCache } from "../eip712/sign-and-broadcast";
6
+ /**
7
+ * Internal exec options: the public {@link AgentTxOptions} plus the per-call
8
+ * `wait` flag threaded through by the CLOB order methods.
9
+ */
10
+ type AgentExecOptions = AgentTxOptions & {
11
+ wait?: boolean;
12
+ };
5
13
  export interface AgentTxExecutorOptions {
6
- network: NetworkConfig;
14
+ /**
15
+ * Returns the network with the latest manifest URL/eip712 overrides applied.
16
+ * Called fresh on every tx so a hot-swap takes effect on the next call
17
+ * without re-creating the executor.
18
+ */
19
+ getNetwork: () => NetworkConfig;
7
20
  agentPrivateKey: string;
8
21
  masterAddress: string;
9
22
  fetchFn?: FetchFn;
@@ -12,6 +25,15 @@ export interface AgentTxExecutorOptions {
12
25
  defaultMemo?: string;
13
26
  defaultConfirmationTimeoutMs?: number;
14
27
  defaultTimeoutSeconds?: number;
28
+ /**
29
+ * Optional shared account cache. When the agent shares a `Client` with the
30
+ * wallet path, pass the wallet's cache here so both executors read the
31
+ * master's accountNumber from the same memo. The agent path only reads
32
+ * `accountNumber`, never writes `nextSequence`, so it's safe to share.
33
+ * Without sharing, the agent executor maintains its own cache.
34
+ */
35
+ cache?: AccountCache;
15
36
  }
16
- export type AgentTxExecutor = (msgs: AnyEip712Msg[], txOptions?: AgentTxOptions) => Promise<TxResult>;
37
+ export type AgentTxExecutor = (msgs: AnyEip712Msg[], txOptions?: AgentExecOptions) => Promise<TxResult>;
17
38
  export declare function createAgentTxExecutor(options: AgentTxExecutorOptions): AgentTxExecutor;
39
+ export {};