@proof-labs/trading-sdk 6.4.0 → 7.1.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 (56) hide show
  1. package/README.md +93 -15
  2. package/dist/binary.d.ts +46 -0
  3. package/dist/binary.d.ts.map +1 -0
  4. package/dist/binary.js +84 -0
  5. package/dist/binary.js.map +1 -0
  6. package/dist/client.d.ts +36 -3
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +110 -79
  9. package/dist/client.js.map +1 -1
  10. package/dist/codec-adapter.d.ts.map +1 -1
  11. package/dist/codec-adapter.js +4 -0
  12. package/dist/codec-adapter.js.map +1 -1
  13. package/dist/codec.d.ts +19 -0
  14. package/dist/codec.d.ts.map +1 -1
  15. package/dist/codec.js +31 -0
  16. package/dist/codec.js.map +1 -1
  17. package/dist/errors.d.ts +10 -0
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/errors.js +23 -1
  20. package/dist/errors.js.map +1 -1
  21. package/dist/gateway-reads.d.ts +17 -0
  22. package/dist/gateway-reads.d.ts.map +1 -1
  23. package/dist/gateway-reads.js +19 -0
  24. package/dist/gateway-reads.js.map +1 -1
  25. package/dist/governance-query.d.ts +12 -3
  26. package/dist/governance-query.d.ts.map +1 -1
  27. package/dist/governance-query.js +109 -18
  28. package/dist/governance-query.js.map +1 -1
  29. package/dist/index.d.ts +7 -5
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +4 -2
  32. package/dist/index.js.map +1 -1
  33. package/dist/market-snapshot.d.ts.map +1 -1
  34. package/dist/market-snapshot.js +7 -2
  35. package/dist/market-snapshot.js.map +1 -1
  36. package/dist/oracle-permissions.d.ts +46 -2
  37. package/dist/oracle-permissions.d.ts.map +1 -1
  38. package/dist/oracle-permissions.js +76 -6
  39. package/dist/oracle-permissions.js.map +1 -1
  40. package/dist/sub-accounts.d.ts.map +1 -1
  41. package/dist/sub-accounts.js +8 -1
  42. package/dist/sub-accounts.js.map +1 -1
  43. package/dist/types.d.ts +112 -7
  44. package/dist/types.d.ts.map +1 -1
  45. package/dist/upgrade-plan.d.ts +5 -0
  46. package/dist/upgrade-plan.d.ts.map +1 -0
  47. package/dist/upgrade-plan.js +28 -0
  48. package/dist/upgrade-plan.js.map +1 -0
  49. package/dist/wasm/proof_trading_sdk_wasm.d.ts +12 -0
  50. package/dist/wasm/proof_trading_sdk_wasm.js +19 -0
  51. package/dist/wasm/proof_trading_sdk_wasm_bg.wasm +0 -0
  52. package/dist/wasm/proof_trading_sdk_wasm_bg.wasm.d.ts +1 -0
  53. package/dist/wasm-loader.d.ts +4 -0
  54. package/dist/wasm-loader.d.ts.map +1 -1
  55. package/dist/wasm-loader.js.map +1 -1
  56. package/package.json +1 -1
package/dist/client.js CHANGED
@@ -5,15 +5,17 @@ import { GatewayReads } from "./gateway-reads.js";
5
5
  import { GatewayHttpError } from "./errors.js";
6
6
  import { decodeCashFlowEvents, decodeHistoryPositionsPage, historyOwner, historySearchParams, } from "./history.js";
7
7
  import { toWasmFields } from "./codec-adapter.js";
8
- import { signAndEncode, encodePayloadBytes, encodeSignedTx } from "./codec.js";
8
+ import { signAndEncode, encodePayloadBytes, encodeSignedTx, rejectFloats, } from "./codec.js";
9
9
  import { decodeAccountState } from "./account-state.js";
10
10
  import { fetchFinancialState, } from "./financial-state.js";
11
11
  import { ready as initWasm } from "./wasm-loader.js";
12
12
  import { txEngineError, txFromEngineCode, txFromQueryResponse, txOk, txTimeout, txTransportError, } from "./tx-result.js";
13
13
  import { getPublicKey, pubkeyToOwner, ownerToHex, bytesToHex, sign, verify, signingMessage, UNBOUND_CHAIN_ID, chainIdFromString, } from "./crypto.js";
14
- import { decodeAdminSignerRegistryInfo, decodeAuthoritiesSnapshot, decodeEventInfo, decodeProposalPage, } from "./governance-query.js";
14
+ import { decodeAdminSignerRegistryInfo, decodeAuthoritiesSnapshot, decodeNodeVersion, decodeUpgradesInfo, decodeEventInfo, decodeProposalPage, } from "./governance-query.js";
15
15
  import { Decoder } from "@msgpack/msgpack";
16
16
  import { readMarketsSnapshot } from "./market-snapshot.js";
17
+ import { yesOrder } from "./binary.js";
18
+ import { Side } from "./types.js";
17
19
  import { sha256 } from "@noble/hashes/sha2.js";
18
20
  import { decodePositionTriggerInfos, decodeTriggerMarketConfigInfos, decodeTriggerStatusJson, validateCancelPositionTriggers, validateOrderTriggers, validateSetPositionTriggers, } from "./triggers.js";
19
21
  import { decodePositionTriggerHistoryPage, decodeTriggerMarketHistoryPage, positionTriggerHistorySearchParams, triggerMarketHistorySearchParams, validateTriggerHistoryMarket, } from "./trigger-history.js";
@@ -500,6 +502,43 @@ export class ExchangeClient {
500
502
  // A dropped response does not prove the signed transaction was rejected.
501
503
  return txTimeout(txHash, "gateway transport interrupted; reconcile by hash");
502
504
  }
505
+ // The gateway's `status` states where the submission ended (api-gateway
506
+ // 7.0.0); nothing is inferred from which fields are present. Any other
507
+ // body falls through to the HTTP-status handling below.
508
+ const stated = gatewayBody.json;
509
+ // An answer naming another tx's hash says nothing about this one.
510
+ const foreignHash = stated?.txHash !== undefined &&
511
+ String(stated.txHash).toUpperCase() !== txHash;
512
+ switch (stated?.status) {
513
+ case "ok":
514
+ case "error":
515
+ // An engine verdict always carries its code and arrives as a 200.
516
+ if (res.status !== 200 || typeof stated.code !== "number")
517
+ break;
518
+ // `ok` with a non-zero code, or `error` with code 0, contradicts itself.
519
+ if ((stated.status === "ok") !== (stated.code === 0) || foreignHash)
520
+ return txTimeout(txHash, "gateway verdict contradicts itself; reconcile by hash");
521
+ return txFromEngineCode(stated.code, {
522
+ hash: txHash,
523
+ height: stated.height,
524
+ log: stated.log ?? stated.error,
525
+ info: stated.info,
526
+ events: stated.events,
527
+ });
528
+ case "refused":
529
+ // A refusal naming a hash, code or height contradicts itself, so it
530
+ // proves nothing about whether the tx was broadcast.
531
+ if (stated.txHash !== undefined ||
532
+ stated.code !== undefined ||
533
+ stated.height !== undefined)
534
+ return txTimeout(txHash, "gateway refusal contradicts itself; reconcile by hash");
535
+ // Nothing was broadcast, so there is nothing to reconcile.
536
+ return txTransportError(res.status === 200 ? 1 : res.status, stated.error ?? stated.errorCode ?? "refused by gateway");
537
+ case "pending":
538
+ // Reconcile the hash of the bytes sent, never one the answer names.
539
+ return txTimeout(txHash, stated.error ??
540
+ "gateway returned no on-chain result; reconcile by hash");
541
+ }
503
542
  // Auth/rate-limit transport failures don't have a JSON body the
504
543
  // engine produced — synthesize an HTTP-status code and tag the result
505
544
  // `outcome: "transport"` so callers don't read it as an ExecError.
@@ -514,12 +553,6 @@ export class ExchangeClient {
514
553
  gatewayBody.raw ??
515
554
  "request body exceeds max size (default 8192 bytes)");
516
555
  }
517
- const refusal = preAdmissionRefusal(res.status, gatewayBody.json);
518
- // Gateway ExchangeResponse::err is hashless: a structured 503 proves
519
- // the transaction never entered the broadcaster queue.
520
- if (res.status === 503 && refusal !== undefined) {
521
- return txTransportError(503, refusal);
522
- }
523
556
  if (res.status >= 500) {
524
557
  return txTimeout(txHash, `gateway HTTP ${res.status}; reconcile by hash${gatewayBody.error || gatewayBody.raw ? `: ${gatewayBody.error ?? gatewayBody.raw}` : ""}`);
525
558
  }
@@ -575,14 +608,10 @@ export class ExchangeClient {
575
608
  // Fallback: the code embedded in the string as "<engine_code>: <message>".
576
609
  // The gateway still emits this format for compatibility, so this path also
577
610
  // covers a pre-#90 gateway that sends ONLY the string. Parse the leading code;
578
- // Hashless gateway refusals are terminal; unrecognized bodies remain unknown.
579
611
  const errMsg = json?.error ?? gatewayBody.raw ?? "unknown gateway error";
580
612
  const code = parseLeadingErrorCode(errMsg);
581
613
  if (code !== null)
582
614
  return txEngineError(code, { log: errMsg });
583
- if (res.status === 200 && refusal !== undefined) {
584
- return txTransportError(1, refusal);
585
- }
586
615
  return txTimeout(txHash, "gateway returned no verdict; reconcile by hash");
587
616
  }
588
617
  /**
@@ -807,6 +836,25 @@ export class ExchangeClient {
807
836
  data: { ...params, owner: this.requireOwner() },
808
837
  });
809
838
  }
839
+ /**
840
+ * Buy No on an event's binary book: places the Yes sell at `$1 − price`.
841
+ * `market` is the event's book (`EventInfo.ebyMarket`); `price` and any
842
+ * `stopLoss`/`takeProfit` trigger prices are No prices. Reduce-only,
843
+ * post-only, client order id and time in force carry over unchanged.
844
+ * Throws {@link BinaryPriceError} for a No price with no Yes mirror (0 or
845
+ * `$1`).
846
+ */
847
+ async buyNo(params) {
848
+ return this.placeOrder(yesOrder({ ...params, side: Side.Buy }));
849
+ }
850
+ /**
851
+ * Sell No on an event's binary book: places the Yes buy at `$1 − price`.
852
+ * Selling No that an account holds is a reduce-only Yes buy: pass
853
+ * `reduceOnly: true` to close without flipping. See {@link ExchangeClient.buyNo}.
854
+ */
855
+ async sellNo(params) {
856
+ return this.placeOrder(yesOrder({ ...params, side: Side.Sell }));
857
+ }
810
858
  /** Cancel a resting order by its engine-assigned order ID. */
811
859
  async cancelOrder(orderId) {
812
860
  return this.submitTx({
@@ -909,10 +957,23 @@ export class ExchangeClient {
909
957
  ? postInfoJson(this.gatewayUrl, info)
910
958
  : fetchApiJson(`${this.apiUrl}${nodePath}`);
911
959
  }
960
+ /** Decode gateway MessagePack bytes after the authoritative strict preflight
961
+ * (`rejectFloats`). Reads now route through the WASM core, so this
962
+ * initialises it on first use. Unlike `ready()` it does not resolve the
963
+ * chain-id binding, which a read never needs. */
964
+ async strictDecode(bytes) {
965
+ await initWasm();
966
+ // Decode first, then preflight: a payload the decoder already refuses
967
+ // keeps its own message; the preflight only adds rejections for bytes that
968
+ // decode cleanly.
969
+ const value = msgpackDecoder.decode(bytes);
970
+ rejectFloats(bytes);
971
+ return value;
972
+ }
912
973
  async queryOrderbook(market) {
913
974
  const json = await fetchApiJson(`${this.readBaseUrl}/v1/orderbook/${market}`);
914
975
  const bytes = fromBase64(json.data);
915
- const raw = msgpackDecoder.decode(bytes);
976
+ const raw = (await this.strictDecode(bytes));
916
977
  const parseLevel = (arr) => ({
917
978
  price: BigInt(arr[0]),
918
979
  totalQty: BigInt(arr[1]),
@@ -935,11 +996,12 @@ export class ExchangeClient {
935
996
  async queryMarkets() {
936
997
  const json = await fetchApiJson(`${this.readBaseUrl}/v1/markets`);
937
998
  const bytes = fromBase64(json.data);
938
- const raw = msgpackDecoder.decode(bytes);
999
+ const raw = (await this.strictDecode(bytes));
939
1000
  return raw.map((m) => decodeMarketConfig(m));
940
1001
  }
941
- /** All events: each is two prediction-binary books (EBY/EBN) under one
942
- * `EventInfo`, plus every conditional attached to it. Fail-closed like the
1002
+ /** All events: each is its binary book (plus a No book on an engine that
1003
+ * still has one) under one `EventInfo`, plus every conditional attached
1004
+ * to it. Fail-closed like the
943
1005
  * governance reads: a missing envelope or malformed row is a refusal.
944
1006
  * Decoder pinned to the engine golden vector in governance-query.test.ts. */
945
1007
  async queryEvents() {
@@ -947,7 +1009,7 @@ export class ExchangeClient {
947
1009
  if (typeof json.data !== "string") {
948
1010
  throw new Error("governance decode: events response has no encoded-data envelope");
949
1011
  }
950
- const raw = msgpackDecoder.decode(fromBase64(json.data));
1012
+ const raw = await this.strictDecode(fromBase64(json.data));
951
1013
  if (!Array.isArray(raw)) {
952
1014
  throw new Error("governance decode: events is not an array");
953
1015
  }
@@ -969,7 +1031,7 @@ export class ExchangeClient {
969
1031
  if (typeof json.data !== "string") {
970
1032
  throw new Error("governance decode: event response has no encoded-data envelope");
971
1033
  }
972
- const raw = msgpackDecoder.decode(fromBase64(json.data));
1034
+ const raw = await this.strictDecode(fromBase64(json.data));
973
1035
  if (raw == null)
974
1036
  return null;
975
1037
  return decodeEventInfo(raw);
@@ -986,7 +1048,7 @@ export class ExchangeClient {
986
1048
  const path = `/v1/triggers/${hex.toLowerCase()}`;
987
1049
  const json = await fetchApiJson(`${this.readBaseUrl}${path}`);
988
1050
  const bytes = fromBase64(requireEncodedData(json, path));
989
- return decodePositionTriggerInfos(msgpackDecoder.decode(bytes));
1051
+ return decodePositionTriggerInfos(await this.strictDecode(bytes));
990
1052
  }
991
1053
  /** Read the complete governed trigger-market policy registry. Missing
992
1054
  * markets are disabled; callers must never synthesize a default policy. */
@@ -994,7 +1056,7 @@ export class ExchangeClient {
994
1056
  const path = "/v1/triggers/markets";
995
1057
  const json = await fetchApiJson(`${this.readBaseUrl}${path}`);
996
1058
  const bytes = fromBase64(requireEncodedData(json, path));
997
- return decodeTriggerMarketConfigInfos(msgpackDecoder.decode(bytes));
1059
+ return decodeTriggerMarketConfigInfos(await this.strictDecode(bytes));
998
1060
  }
999
1061
  /** Read the fail-closed next-height trigger admission predicate. Heights
1000
1062
  * are parsed from raw JSON into bigint without a lossy Number round-trip.
@@ -1029,7 +1091,7 @@ export class ExchangeClient {
1029
1091
  const path = `/v1/oracle/permissions/${market}`;
1030
1092
  const json = await fetchApiJson(`${this.readBaseUrl}${path}`);
1031
1093
  const bytes = fromBase64(requireEncodedData(json, path));
1032
- return decodeOraclePermissions(msgpackDecoder.decode(bytes), market);
1094
+ return decodeOraclePermissions(await this.strictDecode(bytes), market);
1033
1095
  }
1034
1096
  /** Immutable owner-bearing trigger lifecycle history. This always uses the
1035
1097
  * public gateway, including when the client is configured for direct-node
@@ -1068,7 +1130,7 @@ export class ExchangeClient {
1068
1130
  async queryAdminSignerRegistry() {
1069
1131
  const json = await fetchApiJson(`${this.readBaseUrl}/v1/admin/signer-registry`);
1070
1132
  const bytes = fromBase64(requireEncodedData(json, "/v1/admin/signer-registry"));
1071
- return decodeAdminSignerRegistryInfo(msgpackDecoder.decode(bytes));
1133
+ return decodeAdminSignerRegistryInfo(await this.strictDecode(bytes));
1072
1134
  }
1073
1135
  /**
1074
1136
  * Read the engine's privileged authorization sets via the gateway proxy
@@ -1080,7 +1142,25 @@ export class ExchangeClient {
1080
1142
  async queryAuthorities() {
1081
1143
  const json = await fetchApiJson(`${this.readBaseUrl}/v1/admin/authorities`);
1082
1144
  const bytes = fromBase64(requireEncodedData(json, "/v1/admin/authorities"));
1083
- return decodeAuthoritiesSnapshot(msgpackDecoder.decode(bytes));
1145
+ return decodeAuthoritiesSnapshot(await this.strictDecode(bytes));
1146
+ }
1147
+ /**
1148
+ * Read the pending protocol-upgrade plan and the executed activation
1149
+ * ledger via the gateway proxy (`GET /v1/upgrades`).
1150
+ */
1151
+ async queryUpgrades() {
1152
+ const json = await fetchApiJson(`${this.readBaseUrl}/v1/upgrades`);
1153
+ const bytes = fromBase64(requireEncodedData(json, "/v1/upgrades"));
1154
+ return decodeUpgradesInfo(await this.strictDecode(bytes));
1155
+ }
1156
+ /**
1157
+ * The answering node's binary and loaded engine release
1158
+ * (`GET /v1/version`). Node-local: behind a load balancer it describes
1159
+ * whichever node served the request.
1160
+ */
1161
+ async queryNodeVersion() {
1162
+ const json = await fetchApiJson(`${this.readBaseUrl}/v1/version`);
1163
+ return decodeNodeVersion(json);
1084
1164
  }
1085
1165
  /**
1086
1166
  * List admin governance proposals via the gateway proxy
@@ -1105,7 +1185,7 @@ export class ExchangeClient {
1105
1185
  const qs = params.toString();
1106
1186
  const json = await fetchApiJson(`${this.readBaseUrl}/v1/proposals${qs ? `?${qs}` : ""}`);
1107
1187
  const bytes = fromBase64(requireEncodedData(json, "/v1/proposals"));
1108
- return decodeProposalPage(msgpackDecoder.decode(bytes));
1188
+ return decodeProposalPage(await this.strictDecode(bytes));
1109
1189
  }
1110
1190
  /** Fetch open orders for an address. Returns an empty array if the
1111
1191
  * account has no open orders.
@@ -1119,6 +1199,7 @@ export class ExchangeClient {
1119
1199
  if (!json.data)
1120
1200
  return [];
1121
1201
  const bytes = fromBase64(json.data);
1202
+ await initWasm();
1122
1203
  let decoded;
1123
1204
  try {
1124
1205
  decoded = msgpackDecoder.decode(bytes);
@@ -1126,6 +1207,7 @@ export class ExchangeClient {
1126
1207
  catch {
1127
1208
  return [];
1128
1209
  }
1210
+ rejectFloats(bytes);
1129
1211
  if (!Array.isArray(decoded))
1130
1212
  return [];
1131
1213
  return decoded.map((order) => ({
@@ -1142,7 +1224,7 @@ export class ExchangeClient {
1142
1224
  async queryWithdrawal(id) {
1143
1225
  const json = await this.queryOwnerScoped({ type: "withdrawalStatus", withdrawalId: Number(id) }, `/v1/withdrawal/${id}`);
1144
1226
  const bytes = fromBase64(json.data);
1145
- const raw = msgpackDecoder.decode(bytes);
1227
+ const raw = (await this.strictDecode(bytes));
1146
1228
  if (raw === null)
1147
1229
  return null;
1148
1230
  return {
@@ -1167,7 +1249,7 @@ export class ExchangeClient {
1167
1249
  const owner = hex.toLowerCase();
1168
1250
  const path = `/v1/account/${owner}/state`;
1169
1251
  const json = await fetchApiJson(`${this.readBaseUrl}${path}`);
1170
- return decodeAccountState(msgpackDecoder.decode(fromBase64(requireEncodedData(json, path))), owner);
1252
+ return decodeAccountState(await this.strictDecode(fromBase64(requireEncodedData(json, path))), owner);
1171
1253
  }
1172
1254
  async queryAccount(addressHex) {
1173
1255
  const hex = addressHex ?? this.addressHex;
@@ -1175,7 +1257,7 @@ export class ExchangeClient {
1175
1257
  return null;
1176
1258
  const json = await this.queryOwnerScoped({ type: "clearinghouseState", user: hex }, `/v1/account/${hex}`);
1177
1259
  const bytes = fromBase64(json.data);
1178
- const raw = msgpackDecoder.decode(bytes);
1260
+ const raw = (await this.strictDecode(bytes));
1179
1261
  const balance = BigInt(raw[0]);
1180
1262
  const positions = (raw[1] ?? []).map((p) => {
1181
1263
  // Optional enrichments (indices 6-13) shipped incrementally:
@@ -1272,7 +1354,7 @@ export class ExchangeClient {
1272
1354
  if (json.error)
1273
1355
  return [];
1274
1356
  const bytes = fromBase64(json.data);
1275
- const raw = msgpackDecoder.decode(bytes);
1357
+ const raw = await this.strictDecode(bytes);
1276
1358
  if (!Array.isArray(raw))
1277
1359
  return [];
1278
1360
  return raw.map((row) => ({
@@ -1875,57 +1957,6 @@ function deriveNodeUrl(gatewayUrl, fallbackPort) {
1875
1957
  function computeCometTxHash(txBytes) {
1876
1958
  return bytesToHex(sha256(txBytes)).toUpperCase();
1877
1959
  }
1878
- /** Only a fixed, known set of (HTTP status, message) pairs is hashless proof
1879
- * of a pre-admission refusal — mirrors
1880
- * `crates/proof-trading-sdk/src/gateway/mod.rs::pre_admission_refusal`
1881
- * exactly for the statuses reached here (200, 503). ExchangeResponse::err
1882
- * omits admission/verdict and rate-limit fields, but the shape alone is not
1883
- * enough: an unrecognized message in that same shape can come from a generic
1884
- * failure (an intermediary, a proxy) rather than the gateway's own refusal
1885
- * path, and contradictory or unknown evidence must not become a terminal
1886
- * refusal for a transaction that may have executed. */
1887
- const PRE_ADMISSION_REFUSAL_FIELDS = new Set([
1888
- "status",
1889
- "error",
1890
- "mode",
1891
- "retryAfterMs",
1892
- ]);
1893
- function preAdmissionRefusal(status, value) {
1894
- if (!value || typeof value !== "object" || Array.isArray(value))
1895
- return;
1896
- const body = value;
1897
- // Mirrors `RefusalRead`'s `#[serde(deny_unknown_fields)]`: any field
1898
- // outside this exact set — including ones this SDK doesn't know about
1899
- // yet — makes the body unrecognized, not refusal evidence.
1900
- if (body.status !== "error" ||
1901
- typeof body.error !== "string" ||
1902
- Object.keys(body).some((key) => !PRE_ADMISSION_REFUSAL_FIELDS.has(key)))
1903
- return undefined;
1904
- if (status === 503 &&
1905
- body.error === "maintenance: signed writes are not open") {
1906
- if (body.retryAfterMs !== undefined)
1907
- return undefined;
1908
- return body.mode === "paused" || body.mode === "cancel-only"
1909
- ? body.error
1910
- : undefined;
1911
- }
1912
- if (body.mode !== undefined || body.retryAfterMs !== undefined)
1913
- return undefined;
1914
- if (status === 503 &&
1915
- (body.error === "service overloaded" ||
1916
- body.error === "service unavailable"))
1917
- return body.error;
1918
- if (status === 200 &&
1919
- (body.error === "invalid request body" ||
1920
- body.error === "invalid action parameters" ||
1921
- body.error === "invalid base64 in action field" ||
1922
- body.error === "invalid signature" ||
1923
- body.error === "internal encoding error" ||
1924
- body.error ===
1925
- "action type 0x1d is proposer-only and cannot enter through the gateway"))
1926
- return body.error;
1927
- return undefined;
1928
- }
1929
1960
  async function readGatewayBody(res) {
1930
1961
  const raw = await res.text();
1931
1962
  if (!raw)