@proof-labs/trading-sdk 4.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.
Files changed (59) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +391 -0
  3. package/dist/client.d.ts +640 -0
  4. package/dist/client.d.ts.map +1 -0
  5. package/dist/client.js +1730 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/codec-adapter.d.ts +33 -0
  8. package/dist/codec-adapter.d.ts.map +1 -0
  9. package/dist/codec-adapter.js +419 -0
  10. package/dist/codec-adapter.js.map +1 -0
  11. package/dist/codec.d.ts +137 -0
  12. package/dist/codec.d.ts.map +1 -0
  13. package/dist/codec.js +229 -0
  14. package/dist/codec.js.map +1 -0
  15. package/dist/crypto.d.ts +78 -0
  16. package/dist/crypto.d.ts.map +1 -0
  17. package/dist/crypto.js +145 -0
  18. package/dist/crypto.js.map +1 -0
  19. package/dist/errors.d.ts +122 -0
  20. package/dist/errors.d.ts.map +1 -0
  21. package/dist/errors.js +397 -0
  22. package/dist/errors.js.map +1 -0
  23. package/dist/governance-query.d.ts +47 -0
  24. package/dist/governance-query.d.ts.map +1 -0
  25. package/dist/governance-query.js +525 -0
  26. package/dist/governance-query.js.map +1 -0
  27. package/dist/index.d.ts +11 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +22 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/testing.d.ts +25 -0
  32. package/dist/testing.d.ts.map +1 -0
  33. package/dist/testing.js +22 -0
  34. package/dist/testing.js.map +1 -0
  35. package/dist/trigger-history.d.ts +9 -0
  36. package/dist/trigger-history.d.ts.map +1 -0
  37. package/dist/trigger-history.js +442 -0
  38. package/dist/trigger-history.js.map +1 -0
  39. package/dist/triggers.d.ts +15 -0
  40. package/dist/triggers.d.ts.map +1 -0
  41. package/dist/triggers.js +399 -0
  42. package/dist/triggers.js.map +1 -0
  43. package/dist/tx-result.d.ts +53 -0
  44. package/dist/tx-result.d.ts.map +1 -0
  45. package/dist/tx-result.js +58 -0
  46. package/dist/tx-result.js.map +1 -0
  47. package/dist/types.d.ts +2085 -0
  48. package/dist/types.d.ts.map +1 -0
  49. package/dist/types.js +121 -0
  50. package/dist/types.js.map +1 -0
  51. package/dist/wasm/proof_trading_sdk_wasm.d.ts +98 -0
  52. package/dist/wasm/proof_trading_sdk_wasm.js +698 -0
  53. package/dist/wasm/proof_trading_sdk_wasm_bg.wasm +0 -0
  54. package/dist/wasm/proof_trading_sdk_wasm_bg.wasm.d.ts +19 -0
  55. package/dist/wasm-loader.d.ts +42 -0
  56. package/dist/wasm-loader.d.ts.map +1 -0
  57. package/dist/wasm-loader.js +95 -0
  58. package/dist/wasm-loader.js.map +1 -0
  59. package/package.json +72 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Proof Labs
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,391 @@
1
+ # Proof Trading SDK
2
+
3
+ TypeScript SDK for the [Proof Exchange](https://proof.trade): Ed25519 signing,
4
+ MessagePack codec, timestamp-nonce allocation, and gateway/CometBFT submission
5
+ for every exchange action.
6
+
7
+ **Quickest way to try it:**
8
+
9
+ ```bash
10
+ npx tsx examples/connect-and-trade.ts
11
+ ```
12
+
13
+ The example connects to the public devnet, queries markets, and optionally funds
14
+ an account via the dev faucet. Set `PROOF_FAUCET_TOKEN` to run the full
15
+ generate-key → fund → place-order → cancel flow.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ npm install @proof-labs/trading-sdk
21
+ ```
22
+
23
+ ## Connect to the devnet
24
+
25
+ The SDK ships configured for the Proof devnet out of the box:
26
+
27
+ | Parameter | Default |
28
+ | ----------- | -------------------------------- |
29
+ | Gateway URL | `https://api.dev.proof.trade` |
30
+ | Chain ID | `exchange-devnet-1` |
31
+ | Faucet URL | `https://faucet.dev.proof.trade` |
32
+
33
+ **Key generation (no server needed):**
34
+
35
+ ```typescript
36
+ import {
37
+ generateKeypair,
38
+ pubkeyToOwner,
39
+ ownerToHex,
40
+ } from "@proof-labs/trading-sdk";
41
+
42
+ const { publicKey, privateKey } = generateKeypair();
43
+ const address = pubkeyToOwner(publicKey);
44
+ console.log(`0x${ownerToHex(address)}`); // your new address
45
+ ```
46
+
47
+ **Fund your address** via the devnet faucet:
48
+
49
+ ```bash
50
+ curl -X POST https://faucet.dev.proof.trade/drip \
51
+ -H "Authorization: Bearer <token>" \
52
+ -H "Content-Type: application/json" \
53
+ -d '{"address": "0x<your-hex-address>"}'
54
+ ```
55
+
56
+ Each address receives ~10,000 USDC (10,000,000,000 µUSDC) with a 24 h cooldown.
57
+
58
+ > **Paper-trading competition participant?** Do not use the flow above — it
59
+ > needs a privileged faucet token you will not have. You receive a
60
+ > pre-funded private key by redeeming an access code. See
61
+ > [PAPER-TRADING.md](PAPER-TRADING.md).
62
+
63
+ ## Quick Start
64
+
65
+ ```typescript
66
+ import {
67
+ ExchangeClient,
68
+ Side,
69
+ generateKeypair,
70
+ pubkeyToOwner,
71
+ ownerToHex,
72
+ } from "@proof-labs/trading-sdk";
73
+
74
+ const { publicKey, privateKey } = generateKeypair();
75
+ const address = pubkeyToOwner(publicKey);
76
+ const addressHex = ownerToHex(address);
77
+
78
+ const client = new ExchangeClient({
79
+ chainId: "exchange-devnet-1",
80
+ });
81
+ client.setPrivateKey(privateKey);
82
+
83
+ // Query
84
+ const book = await client.queryOrderbook(1);
85
+ const account = await client.queryAccount(addressHex);
86
+
87
+ // Trade
88
+ const result = await client.submitTx({
89
+ type: "PlaceOrder",
90
+ data: {
91
+ market: 1,
92
+ owner: address,
93
+ side: Side.Buy,
94
+ price: 500_000_000_000n, // $500,000.00 in micro-USDC (6 dp)
95
+ quantity: 1n,
96
+ },
97
+ });
98
+
99
+ console.log(result); // { code: 0, hash: "…" } on success
100
+ ```
101
+
102
+ ## Unit Conventions
103
+
104
+ | Field | Unit | Example |
105
+ | ------------------- | -------------------- | ----------------------------- |
106
+ | Prices | micro-USDC (6 dp) | `66_752_340_000` = $66,752.34 |
107
+ | Balances / amounts | MicroUSDC (6 dp) | `100_000_000_000` = $100,000 |
108
+ | Fees / margin rates | Basis points | `500` = 5% |
109
+ | Addresses | 20-byte `Uint8Array` | `pubkeyToOwner(publicKey)` |
110
+
111
+ All prices and quantities are `u64` (BigInt) — never floats.
112
+
113
+ ## API
114
+
115
+ ### Client
116
+
117
+ ```typescript
118
+ class ExchangeClient {
119
+ constructor(opts: ExchangeClientOptions);
120
+
121
+ // Keys
122
+ setPrivateKey(key: Uint8Array): void;
123
+ getAddress(): Uint8Array | null;
124
+ getAddressHex(): string | null;
125
+
126
+ // Chain
127
+ ready(): Promise<void>;
128
+ status(): Promise<{ latestHeight: number; latestAppHash: string }>;
129
+
130
+ // Trading
131
+ submitTx(action: Action): Promise<TxResult>;
132
+ submitTxCommit(action: Action): Promise<TxResult>;
133
+ awaitPendingVerifies(): Promise<TxResult[]>;
134
+ // ^ Against a gateway that answers synchronously (api-gateway#90), both
135
+ // submit paths return the chain's own result — `code`, `height`, `events` —
136
+ // in ONE round-trip. `submitTxCommit` no longer polls `/tx?hash=` for it,
137
+ // and `submitTx` spawns no background verifier. See "Transaction results".
138
+
139
+ // External signers — no key loaded in the client. Build the envelope with
140
+ // signingMessage() → sign anywhere (hardware key, CLI signer) →
141
+ // encodeSignedTx(), then submit the bytes byte-exact (never re-encoded).
142
+ // Semantics mirror the pair above: submitSignedTx is fire-and-forget with
143
+ // background reconciliation; submitSignedTxCommit waits for the final
144
+ // chain verdict (scoped to the call — use it when the caller must know
145
+ // definitively whether the tx landed, e.g. operator/multisig actions).
146
+ submitSignedTx(txBytes: Uint8Array): Promise<TxResult>;
147
+ submitSignedTxCommit(txBytes: Uint8Array): Promise<TxResult>;
148
+
149
+ // Reads
150
+ queryOrderbook(market: number): Promise<Orderbook>;
151
+ queryOpenOrders(addressHex?: string): Promise<OpenOrder[]>;
152
+ queryMarkets(): Promise<MarketConfig[]>;
153
+ queryAccount(addressHex?: string): Promise<AccountInfo | null>;
154
+ queryHealth(): Promise<{ status: string; height: number }>;
155
+ queryWithdrawal(id: bigint): Promise<WithdrawalRecord | null>;
156
+ queryPositionTriggers(addressHex?: string): Promise<PositionTriggerInfo[]>;
157
+ queryTriggerMarketConfigs(): Promise<TriggerMarketConfigInfo[]>;
158
+ queryTriggerStatus(): Promise<TriggerStatus>;
159
+ queryPositionTriggerHistory(addressHex?: string, filters?: PositionTriggerHistoryFilters): Promise<PositionTriggerHistoryPage>;
160
+ queryTriggerMarketHistory(market: number, filters?: TriggerMarketHistoryFilters): Promise<TriggerMarketHistoryPage>;
161
+
162
+ // Owner defaults to signer; version-active agents pass delegated owner.
163
+ setPositionTriggers(params: Omit<SetPositionTriggers, "owner"> & { owner?: Uint8Array }): Promise<TxResult>;
164
+ cancelPositionTriggers(market: number, expectedPositionEpoch: bigint, owner?: Uint8Array): Promise<TxResult>;
165
+
166
+ // History
167
+ queryHistoryDeposits(...): Promise<HistoryCashFlow[]>;
168
+ queryHistoryWithdrawals(...): Promise<HistoryCashFlow[]>;
169
+ queryHistoryResolutions(...): Promise<HistoryResolution[]>;
170
+ queryHistoryPositions(...): Promise<HistoryPositionSnapshot[]>;
171
+
172
+ // Blocks
173
+ getBlock(height?: number): Promise<Record<string, unknown>>;
174
+ getBlockResults(height: number): Promise<Record<string, unknown>>;
175
+
176
+ // Streams (gateway-native; mirror the Python SDK)
177
+ subscribeAccountEvents(owner: Uint8Array | string, onEvent: (e: Record<string, unknown>) => void, opts?: WsStreamOptions): () => void;
178
+ subscribeOrderbookDeltas(market: number, onMessage: (m: Record<string, unknown>) => void, opts?: WsStreamOptions): () => void;
179
+ orderbookSnapshot(market: number): Promise<Record<string, unknown>>;
180
+ disconnect(): void;
181
+ }
182
+ ```
183
+
184
+ Position triggers are exact-position-generation brackets. For an existing
185
+ bracket, `queryPositionTriggers()` returns its epoch; first attach must use the
186
+ epoch on the canonical account position read and must never guess `1`. Submit
187
+ action `0x25` (`SetPositionTriggers`) or `0x26`
188
+ (`CancelPositionTriggers`). A set replaces the whole bracket atomically,
189
+ requires at least one limb, and each limb carries an explicit `1..=9999` bps
190
+ IOC collar. Owner defaults to the loaded signer; a version-active trading agent
191
+ passes the delegated owner explicitly and the engine verifies the grant.
192
+
193
+ Before setting a bracket, read `queryTriggerMarketConfigs()`. The current
194
+ policy is the only valid source for `enabled` and the maximum IOC slippage;
195
+ absence means disabled. The optional pending policy is shown with its accepted
196
+ and next-block effective heights. The SDK rejects malformed, empty, unsorted,
197
+ or version-skipping policy state rather than inventing a default.
198
+
199
+ `queryTriggerStatus()` reports the fail-closed next-height activation
200
+ predicate. `queryPositionTriggerHistory()` returns immutable owner-bearing
201
+ lifecycle events; `queryTriggerMarketHistory()` returns the shared market
202
+ deferred/resumed stream. Both history methods always use the gateway, return an
203
+ opaque filter-bound cursor, and preserve every coordinate/id as a decimal
204
+ string—pass those strings and the cursor through unchanged.
205
+
206
+ ### Actions
207
+
208
+ The `Action` type is a discriminated union. Every action is:
209
+
210
+ ```typescript
211
+ type Action = TraderAction | OperatorAction;
212
+
213
+ type TraderAction =
214
+ | { type: "PlaceOrder"; data: PlaceOrder }
215
+ | { type: "CancelOrder"; data: CancelOrder }
216
+ | { type: "CancelAllOrders"; data: CancelAllOrders }
217
+ | { type: "CancelReplaceOrder"; data: CancelReplaceOrder }
218
+ | { type: "MarketOrder"; data: MarketOrder }
219
+ | { type: "ClosePosition"; data: ClosePosition };
220
+ // … more trader actions — see src/types.ts
221
+ ```
222
+
223
+ Trading integrations use `TraderAction` and can type their calls against it to
224
+ keep operator actions out of autocomplete. `submitTx` still accepts the full
225
+ `Action` union.
226
+
227
+ #### Operator actions (privileged)
228
+
229
+ `OperatorAction` covers oracle-relay / composite-CEX-feeder / relayer-admin
230
+ actions — e.g. `OracleUpdate`, `OracleUpdateComposite`, `UpdateMarketFees`,
231
+ `CreateMarket`. **A trading integration never needs these.** Each is gated by a
232
+ dedicated engine allowlist, so codec availability grants nothing without an
233
+ operator-provisioned key. See [AGENTS.md](AGENTS.md) → "Operator actions" for
234
+ usage (e.g. driving the BE-31 multi-source mark via `OracleUpdateComposite` +
235
+ `UpdateMarketFees` `markSourceMode`).
236
+
237
+ ### Options
238
+
239
+ ```typescript
240
+ interface ExchangeClientOptions {
241
+ gatewayUrl?: string; // default: https://api.dev.proof.trade — the single endpoint
242
+ chainId?: string; // default: "exchange-devnet-1"
243
+ useGateway?: boolean; // default: true — route ALL traffic through the gateway
244
+ apiKey?: string; // gateway API key (optional)
245
+
246
+ // Internal direct-node overrides — only consulted when useGateway: false
247
+ // (in-cluster tools, scenario harness). Derived from gatewayUrl when
248
+ // omitted (local gateway 9080 → 26657 / 8080).
249
+ rpcUrl?: string;
250
+ apiUrl?: string;
251
+ wsUrl?: string;
252
+ }
253
+ ```
254
+
255
+ `gatewayUrl` is the single source of truth: under the default
256
+ `useGateway: true` everything — submission, reads, transaction-status polling,
257
+ chain status/blocks (`/v1/status`, `/v1/block`, `/v1/block_results`), chain-id
258
+ resolution, and the WebSocket feed — goes through it. External clients should
259
+ set only this.
260
+
261
+ When `chainId` is omitted, the SDK auto-resolves it on first submit from the
262
+ gateway's `/v1/status` (or `${rpcUrl}/status` on the direct-node path). Pinning
263
+ `chainId` explicitly is still recommended for production — it keeps signatures
264
+ deterministic across SDK rebuilds.
265
+
266
+ For a local development stack, point the client at your local gateway; the
267
+ node URLs are derived from it (override `rpcUrl` / `apiUrl` if your ports
268
+ differ from the 26657 / 8080 convention):
269
+
270
+ ```typescript
271
+ const client = new ExchangeClient({
272
+ gatewayUrl: "http://localhost:9080",
273
+ chainId: "proof-dev",
274
+ });
275
+ ```
276
+
277
+ ## Transaction results
278
+
279
+ `POST /exchange` on the gateway is **synchronous on the on-chain result**
280
+ ([api-gateway#90](https://github.com/Proof-labs/api-gateway/pull/90)): it parks the
281
+ response on the CometBFT tx hash and answers with the chain's own `code`, `log`,
282
+ `height` and per-tx `events`. So a submit costs **one round-trip**, not a submit plus
283
+ a poll loop — the original complaint (`exchange-issues-2026-06-08` H14) measured that
284
+ loop at 9 s+ under load.
285
+
286
+ The SDK reads that shape and stops working for it:
287
+
288
+ | Gateway answers | `TxResult` | Does the SDK poll? |
289
+ | -------------------- | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
290
+ | `code` + `height` | `ok` / `engine`, with `height` + `events` | **No** — the tx executed; there is nothing to wait for |
291
+ | `code`, no `height` | `engine` | **No** — a CheckTx reject never enters a block, so no DeliverTx will run |
292
+ | `txHash`, no `code` | `timeout` | **Yes** — the gateway broadcast it but couldn't report the outcome in time (park deadline, duplicate in flight, unreadable result). The tx may still commit, so it is reconciled by hash — **not** reported as a rejection |
293
+ | `{status:"ok"}` only | `ok`, no `height` | **Yes** — a pre-#90 gateway acks CheckTx only, so inclusion is still unknown |
294
+
295
+ That last row is why upgrading the SDK is safe against a gateway that has not been
296
+ upgraded yet: absence of `code`/`height` still means "execution unknown", and the old
297
+ polling paths run exactly as before.
298
+
299
+ **Read `code` from the field, not from the message.** The gateway still sends the
300
+ long-standing `"<code>: <message>"` format in `error` (so older clients that parse the
301
+ code back out of it keep working), and `log` carries the chain's message verbatim. New
302
+ code should read the structured `code` field: it is authoritative and needs no parsing.
303
+
304
+ ## WebSocket streams
305
+
306
+ The SDK exposes the gateway's native multiplexed feed — the same two streams
307
+ as the Python SDK. Each subscription opens its own connection, auto-reconnects
308
+ with exponential backoff (500ms → 30s, ±25% jitter), and returns an
309
+ unsubscribe function. `disconnect()` tears down every open stream.
310
+
311
+ The WS base URL defaults to `gatewayUrl` with its scheme swapped to `ws`/`wss`.
312
+ If your local stack serves WebSockets on a separate port, set `wsUrl`
313
+ explicitly (e.g. `ws://localhost:9091`).
314
+
315
+ ```typescript
316
+ // Account events: snapshot frame, then incremental events. The SDK tracks
317
+ // the highest event_id and replays via after_id on reconnect (no gaps).
318
+ const unsub = client.subscribeAccountEvents(address, (event) => {
319
+ console.log(event.event_type, event);
320
+ });
321
+
322
+ // L2 orderbook: first frame is a full `l2Book` snapshot, then deltas.
323
+ const unsubBook = client.subscribeOrderbookDeltas(1, (msg) => {
324
+ console.log(msg);
325
+ });
326
+
327
+ // One-shot snapshot (opens, reads the first l2Book frame, closes):
328
+ const book = await client.orderbookSnapshot(1);
329
+
330
+ // later:
331
+ unsub();
332
+ unsubBook();
333
+ client.disconnect(); // closes everything
334
+ ```
335
+
336
+ `WsStreamOptions` (third arg) takes `onError?: (err) => void` and
337
+ `reconnectBackoffMaxMs?: number`.
338
+
339
+ **Auth.** Account streams require auth only when the gateway runs with
340
+ `--api-key`. Because a browser `WebSocket` cannot send the `X-Api-Key` header,
341
+ the SDK uses the gateway's signed-query auth: with a private key loaded
342
+ (`setPrivateKey`) it signs the stream-auth message and appends `public_key` /
343
+ `signature` / `timestamp_ms` to the URL automatically. Against an
344
+ unauthenticated gateway (e.g. devnet) the owner alone suffices.
345
+
346
+ ## Wire Format
347
+
348
+ Transactions are MessagePack positional arrays:
349
+
350
+ ```
351
+ [2, action_type, seq, payload, pubkey(32B), signature(64B)]
352
+ ```
353
+
354
+ The signature covers
355
+ `DOMAIN_PREFIX(16B) || chain_id(32B) || action_type(1B) || seq(8B BE) || payload`.
356
+ The 32-byte `chain_id` binding closes the cross-chain replay vector.
357
+
358
+ `seq` is a timestamp nonce — a millisecond Unix timestamp chosen by the client.
359
+ The SDK allocates via `max(now_ms, last_nonce + 1)`. The engine validates
360
+ against a sliding window and rejects replays with code 21.
361
+
362
+ The full action set and payload layouts are defined in `src/types.ts` and
363
+ `src/codec.ts` — these are the wire contract.
364
+
365
+ ## Layout
366
+
367
+ | Path | Contents |
368
+ | ------------------------------- | ---------------------------------------------------- |
369
+ | `src/client.ts` | `ExchangeClient` — submit, queries, nonce allocation |
370
+ | `src/codec.ts` | MessagePack encode/decode, signed-envelope assembly |
371
+ | `src/crypto.ts` | Ed25519 sign/verify, keypair + owner derivation |
372
+ | `src/types.ts` | Action types and payload shapes (wire contract) |
373
+ | `src/errors.ts` | Typed engine/gateway error surface |
374
+ | `examples/connect-and-trade.ts` | End-to-end example |
375
+ | `src/scenarios/` | Matching/liquidation scenario tests |
376
+
377
+ ## Test
378
+
379
+ ```bash
380
+ npm test # vitest: codec round-trips, signing, client, scenarios
381
+ npm run build # tsc -> dist/
382
+ ```
383
+
384
+ ## Agent / Claude integration
385
+
386
+ See [AGENTS.md](AGENTS.md) for guidance on using this SDK with AI agents
387
+ (Claude, Cursor, Copilot, etc.).
388
+
389
+ ## License
390
+
391
+ Apache-2.0.