@gala-chain/gswap-sdk 1.0.0 → 1.1.1

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.mjs CHANGED
@@ -757,14 +757,435 @@ function isBlockNumber(value) {
757
757
  return typeof value === "number" && Number.isInteger(value) && value >= 0;
758
758
  }
759
759
 
760
+ //#endregion
761
+ //#region src/types/env.ts
762
+ /** Built-in GalaSwap deployment environments. */
763
+ const GSWAP_ENVIRONMENTS = {
764
+ prod: {
765
+ dexBackendBaseUrl: "https://dex-backend-prod1.defi.gala.com",
766
+ dexBackendWsUrl: "wss://dex-backend-prod1.defi.gala.com/ws"
767
+ },
768
+ stage: {
769
+ dexBackendBaseUrl: "https://swap-backend.stage.defi.ovh.gala.com",
770
+ dexBackendWsUrl: "wss://swap-backend.stage.defi.ovh.gala.com/ws"
771
+ }
772
+ };
773
+
760
774
  //#endregion
761
775
  //#region src/utils/debug.ts
762
776
  const debugLog = debug("GSWAP_SDK");
763
777
 
778
+ //#endregion
779
+ //#region src/utils/reconnection.ts
780
+ /** Counts reconnect attempts and doubles the delay between them, up to a ceiling. */
781
+ var ReconnectionBackoff = class {
782
+ options;
783
+ attempts = 0;
784
+ delayMs;
785
+ maxDelayMs;
786
+ constructor(options) {
787
+ this.options = options;
788
+ this.delayMs = options.baseDelayMs;
789
+ this.maxDelayMs = options.maxDelayMs ?? 3e4;
790
+ }
791
+ /** Whether another attempt is allowed. */
792
+ shouldRetry() {
793
+ return this.attempts < this.options.maxAttempts;
794
+ }
795
+ /** The delay to wait before the next attempt. */
796
+ nextDelayMs() {
797
+ return this.delayMs;
798
+ }
799
+ /** Record that an attempt is being made, and double the next delay. */
800
+ recordAttempt() {
801
+ this.attempts += 1;
802
+ this.delayMs = Math.min(this.delayMs * 2, this.maxDelayMs);
803
+ }
804
+ /** Forget every attempt: the connection is healthy again. */
805
+ reset() {
806
+ this.attempts = 0;
807
+ this.delayMs = this.options.baseDelayMs;
808
+ }
809
+ get attemptCount() {
810
+ return this.attempts;
811
+ }
812
+ get maxAttempts() {
813
+ return this.options.maxAttempts;
814
+ }
815
+ };
816
+
817
+ //#endregion
818
+ //#region src/classes/gdex_stream.ts
819
+ const GDEX_SUBPROTOCOL = "gdex.jsonrpc.v1";
820
+ const RATE_LIMITED = -32003;
821
+ const MAX_RESUBSCRIBE_RATE_RETRIES = 5;
822
+ const WEBSOCKET_OPEN = 1;
823
+ const LIQUIDITY_ACTIONS = [
824
+ "add",
825
+ "remove",
826
+ "collect"
827
+ ];
828
+ /** Whether a stream payload carries every field of a {@link GdexLiquidityEvent}. */
829
+ function isGdexLiquidityEvent(value) {
830
+ const { pool } = value;
831
+ return (value["version"] === "v1" || value["version"] === "v2") && typeof pool === "object" && pool !== null && typeof value["poolHash"] === "string" && typeof value["transactionId"] === "string" && LIQUIDITY_ACTIONS.includes(value["action"]) && typeof value["owner"] === "string" && typeof value["amount0"] === "string" && typeof value["amount1"] === "string" && typeof value["blockNumber"] === "number" && typeof value["timestamp"] === "string";
832
+ }
833
+ /** A JSON-RPC error answered by the stream. */
834
+ var GdexStreamError = class extends Error {
835
+ code;
836
+ data;
837
+ constructor(code, message, data) {
838
+ super(message);
839
+ this.name = "GdexStreamError";
840
+ this.code = code;
841
+ if (data !== void 0) this.data = data;
842
+ }
843
+ };
844
+ /**
845
+ * Client for the gSwap realtime stream (gdex WebSocket Protocol v1): JSON-RPC 2.0 over one raw
846
+ * WebSocket, with automatic reconnect and resubscribe.
847
+ *
848
+ * @example
849
+ * ```typescript
850
+ * const stream = new GdexStreamService();
851
+ * await stream.connect();
852
+ * await stream.subscribeLiquidity(event => console.log(event.action, event.owner), {
853
+ * owner: 'client|618ae395c1c653111d3315be',
854
+ * });
855
+ * ```
856
+ */
857
+ var GdexStreamService = class {
858
+ url;
859
+ requestTimeoutMs;
860
+ webSocketConstructor;
861
+ backoff;
862
+ socket;
863
+ connectPromise;
864
+ nextRequestId = 0;
865
+ pending = /* @__PURE__ */ new Map();
866
+ subscriptionsByServerId = /* @__PURE__ */ new Map();
867
+ activeSubscriptions = /* @__PURE__ */ new Set();
868
+ intentionalClose = false;
869
+ reconnecting = false;
870
+ reconnectTimer;
871
+ reconnectDelayResolve;
872
+ constructor(config = {}) {
873
+ this.url = config.url ?? GSWAP_ENVIRONMENTS.prod.dexBackendWsUrl;
874
+ this.requestTimeoutMs = config.requestTimeoutMs ?? 15e3;
875
+ this.backoff = new ReconnectionBackoff({
876
+ maxAttempts: config.reconnectAttempts ?? 5,
877
+ baseDelayMs: config.reconnectDelayMs ?? 2e3
878
+ });
879
+ const implementation = config.webSocketImpl ?? globalThis.WebSocket;
880
+ if (typeof implementation !== "function") throw new Error("GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the \"ws\" package).");
881
+ this.webSocketConstructor = implementation;
882
+ }
883
+ /** Open the connection. Resolves at once when already connected. */
884
+ connect() {
885
+ if (this.isConnected()) return Promise.resolve();
886
+ if (this.connectPromise) return this.connectPromise;
887
+ this.intentionalClose = false;
888
+ this.clearReconnectTimer();
889
+ this.connectPromise = this.openSocket();
890
+ return this.connectPromise;
891
+ }
892
+ /** Close the connection and stop reconnecting. */
893
+ disconnect() {
894
+ this.intentionalClose = true;
895
+ this.reconnecting = false;
896
+ this.clearReconnectTimer();
897
+ this.rejectPending(/* @__PURE__ */ new Error("GDEX stream disconnected"));
898
+ const socket = this.socket;
899
+ this.socket = void 0;
900
+ this.connectPromise = void 0;
901
+ socket === null || socket === void 0 || socket.close(1e3, "client disconnect");
902
+ }
903
+ isConnected() {
904
+ var _this$socket;
905
+ return ((_this$socket = this.socket) === null || _this$socket === void 0 ? void 0 : _this$socket.readyState) === WEBSOCKET_OPEN;
906
+ }
907
+ /** Raw JSON-RPC escape hatch. */
908
+ request(method, params) {
909
+ if (!this.isConnected() || !this.socket) return Promise.reject(/* @__PURE__ */ new Error("GDEX stream is not connected. Call connect() first."));
910
+ const id = ++this.nextRequestId;
911
+ const frame = {
912
+ jsonrpc: "2.0",
913
+ id,
914
+ method
915
+ };
916
+ if (params !== void 0) frame["params"] = params;
917
+ return new Promise((resolve, reject) => {
918
+ const timeout = setTimeout(() => {
919
+ this.pending.delete(id);
920
+ reject(/* @__PURE__ */ new Error(`GDEX request "${method}" timed out after ${this.requestTimeoutMs}ms`));
921
+ }, this.requestTimeoutMs);
922
+ this.pending.set(id, {
923
+ resolve: (value) => resolve(value),
924
+ reject,
925
+ timeout
926
+ });
927
+ try {
928
+ var _this$socket2;
929
+ (_this$socket2 = this.socket) === null || _this$socket2 === void 0 || _this$socket2.send(JSON.stringify(frame));
930
+ } catch (error) {
931
+ clearTimeout(timeout);
932
+ this.pending.delete(id);
933
+ reject(error instanceof Error ? error : new Error(String(error)));
934
+ }
935
+ });
936
+ }
937
+ serverInfo() {
938
+ return this.request("gdex_serverInfo");
939
+ }
940
+ ping() {
941
+ return this.request("gdex_ping");
942
+ }
943
+ getPool(selector) {
944
+ return this.request("gdex_getPool", selector);
945
+ }
946
+ getBalance(owner, tokenClassKey) {
947
+ return this.request("gdex_getBalance", tokenClassKey === void 0 ? { owner } : {
948
+ owner,
949
+ tokenClassKey
950
+ });
951
+ }
952
+ getPositions(opts) {
953
+ return this.request("gdex_getPositions", opts);
954
+ }
955
+ getBlockHeight() {
956
+ return this.request("gdex_getBlockHeight");
957
+ }
958
+ quote(params) {
959
+ return this.request("gdex_quote", params);
960
+ }
961
+ getToken(tokenClassKey) {
962
+ return this.request("gdex_getToken", { tokenClassKey });
963
+ }
964
+ /** One event per committed swap. Omit the pool to receive every pool's swaps. */
965
+ subscribeSwaps(cb, opts = {}) {
966
+ return this.subscribe("swap", cb, opts);
967
+ }
968
+ /**
969
+ * State changes of one pool (price, tick, reserves, liquidity). These events carry no acting wallet:
970
+ * on v2 `creator` is whoever created the pool, not whoever just traded or added liquidity. For
971
+ * "who did it", use {@link subscribeLiquidity} (`owner`) or {@link subscribeSwaps} (`sender`).
972
+ */
973
+ subscribePool(selector, cb, opts = {}) {
974
+ return this.subscribe("pool", cb, {
975
+ ...selector,
976
+ ...opts
977
+ });
978
+ }
979
+ /** Balance changes of one wallet. */
980
+ subscribeBalances(owner, cb, opts = {}) {
981
+ return this.subscribe("balance", cb, {
982
+ owner,
983
+ ...opts
984
+ });
985
+ }
986
+ /** Each newly created pool. */
987
+ subscribePoolCreated(cb, opts = {}) {
988
+ return this.subscribe("poolCreated", cb, opts);
989
+ }
990
+ /**
991
+ * One event per committed AddLiquidity, RemoveLiquidity and CollectPositionFees, on both contract
992
+ * versions. Every filter is optional; with none, every liquidity event arrives. These events never
993
+ * appear on {@link subscribeSwaps}. There is no snapshot: read positions with {@link getPositions}.
994
+ * Deduplicate by `transactionId` plus `positionId`: a v1 BatchSubmit can hold several operations
995
+ * under one transaction id.
996
+ */
997
+ subscribeLiquidity(cb, opts = {}) {
998
+ return this.subscribe("liquidity", (event) => {
999
+ if (isGdexLiquidityEvent(event)) cb(event);
1000
+ else debugLog("Ignoring a malformed liquidity event from the GDEX stream");
1001
+ }, opts);
1002
+ }
1003
+ /** Each block-height advance. */
1004
+ subscribeBlocks(cb, opts = {}) {
1005
+ return this.subscribe("blocks", cb, opts);
1006
+ }
1007
+ openSocket() {
1008
+ return new Promise((resolve, reject) => {
1009
+ let opened = false;
1010
+ const socket = new this.webSocketConstructor(this.url, GDEX_SUBPROTOCOL);
1011
+ this.socket = socket;
1012
+ socket.onopen = () => {
1013
+ if (this.socket !== socket) return;
1014
+ opened = true;
1015
+ this.connectPromise = void 0;
1016
+ if (!this.reconnecting) this.backoff.reset();
1017
+ debugLog("Connected to GDEX stream");
1018
+ resolve();
1019
+ };
1020
+ socket.onmessage = (event) => this.handleMessage(event.data);
1021
+ socket.onerror = () => {
1022
+ if (!opened) reject(/* @__PURE__ */ new Error(`Failed to connect to GDEX stream at ${this.url}`));
1023
+ };
1024
+ socket.onclose = (event) => {
1025
+ if (this.socket !== socket) return;
1026
+ this.socket = void 0;
1027
+ this.connectPromise = void 0;
1028
+ if (!opened) reject(/* @__PURE__ */ new Error(`GDEX stream closed before connecting (code ${event.code ?? 0})`));
1029
+ this.rejectPending(/* @__PURE__ */ new Error(`GDEX stream connection closed (code ${event.code ?? 0})`));
1030
+ if (!this.intentionalClose && !this.reconnecting) this.startReconnectLoop();
1031
+ };
1032
+ });
1033
+ }
1034
+ handleMessage(data) {
1035
+ if (typeof data !== "string") {
1036
+ debugLog("Ignoring non-text GDEX WebSocket frame");
1037
+ return;
1038
+ }
1039
+ let message;
1040
+ try {
1041
+ message = JSON.parse(data);
1042
+ } catch {
1043
+ debugLog("Ignoring invalid JSON from GDEX stream");
1044
+ return;
1045
+ }
1046
+ if (typeof message.id === "number") {
1047
+ const pending = this.pending.get(message.id);
1048
+ if (!pending) return;
1049
+ clearTimeout(pending.timeout);
1050
+ this.pending.delete(message.id);
1051
+ if (message.error) {
1052
+ const code = typeof message.error.code === "number" ? message.error.code : -32603;
1053
+ const errorMessage = typeof message.error.message === "string" ? message.error.message : "GDEX request failed";
1054
+ pending.reject(new GdexStreamError(code, errorMessage, message.error.data));
1055
+ } else pending.resolve(message.result);
1056
+ return;
1057
+ }
1058
+ if (message.method !== "gdex_subscription" || !this.isRecord(message.params)) return;
1059
+ const subscriptionId = message.params["subscription"];
1060
+ const result = message.params["result"];
1061
+ if (typeof subscriptionId !== "string" || !this.isRecord(result)) return;
1062
+ const subscription = this.subscriptionsByServerId.get(subscriptionId);
1063
+ if (!(subscription === null || subscription === void 0 ? void 0 : subscription.active)) return;
1064
+ try {
1065
+ subscription.callback(result);
1066
+ } catch (error) {
1067
+ debugLog("GDEX subscription callback failed", error);
1068
+ }
1069
+ }
1070
+ async subscribe(channel, callback, options) {
1071
+ const params = {
1072
+ channel,
1073
+ ...options
1074
+ };
1075
+ const result = await this.request("gdex_subscribe", params);
1076
+ let active;
1077
+ const handle = {
1078
+ subscriptionId: result.subscriptionId,
1079
+ unsubscribe: async () => this.unsubscribe(active)
1080
+ };
1081
+ active = {
1082
+ serverId: result.subscriptionId,
1083
+ params,
1084
+ callback,
1085
+ handle,
1086
+ active: true
1087
+ };
1088
+ this.activeSubscriptions.add(active);
1089
+ this.subscriptionsByServerId.set(active.serverId, active);
1090
+ return handle;
1091
+ }
1092
+ async unsubscribe(subscription) {
1093
+ if (!subscription.active) return;
1094
+ subscription.active = false;
1095
+ this.activeSubscriptions.delete(subscription);
1096
+ this.subscriptionsByServerId.delete(subscription.serverId);
1097
+ if (this.isConnected()) await this.request("gdex_unsubscribe", { subscriptionId: subscription.serverId });
1098
+ }
1099
+ startReconnectLoop() {
1100
+ if (this.reconnecting || this.intentionalClose) return;
1101
+ this.reconnecting = true;
1102
+ this.reconnectLoop();
1103
+ }
1104
+ async reconnectLoop() {
1105
+ while (!this.intentionalClose && this.backoff.shouldRetry()) {
1106
+ const delay = this.backoff.nextDelayMs();
1107
+ this.backoff.recordAttempt();
1108
+ debugLog(`GDEX reconnect attempt ${this.backoff.attemptCount}/${this.backoff.maxAttempts} in ${delay}ms`);
1109
+ await this.waitForReconnectDelay(delay);
1110
+ if (this.intentionalClose) break;
1111
+ try {
1112
+ await this.openSocket();
1113
+ await this.resubscribeAll();
1114
+ this.backoff.reset();
1115
+ this.reconnecting = false;
1116
+ return;
1117
+ } catch (error) {
1118
+ debugLog(`GDEX reconnect failed: ${error instanceof Error ? error.message : String(error)}`);
1119
+ }
1120
+ }
1121
+ this.reconnecting = false;
1122
+ if (!this.intentionalClose) debugLog("GDEX reconnection attempts exhausted");
1123
+ }
1124
+ async resubscribeAll() {
1125
+ this.subscriptionsByServerId.clear();
1126
+ for (const subscription of this.activeSubscriptions) {
1127
+ if (!subscription.active) continue;
1128
+ const params = {
1129
+ ...subscription.params,
1130
+ snapshot: true
1131
+ };
1132
+ const result = await this.resubscribeWithRateLimitRetry(params);
1133
+ if (!subscription.active) {
1134
+ await this.request("gdex_unsubscribe", { subscriptionId: result.subscriptionId });
1135
+ continue;
1136
+ }
1137
+ subscription.serverId = result.subscriptionId;
1138
+ subscription.handle.subscriptionId = result.subscriptionId;
1139
+ this.subscriptionsByServerId.set(result.subscriptionId, subscription);
1140
+ }
1141
+ }
1142
+ async resubscribeWithRateLimitRetry(params) {
1143
+ for (let attempt = 0;; attempt++) try {
1144
+ return await this.request("gdex_subscribe", params);
1145
+ } catch (error) {
1146
+ if (!(error instanceof GdexStreamError) || error.code !== RATE_LIMITED || attempt >= MAX_RESUBSCRIBE_RATE_RETRIES) throw error;
1147
+ const retryAfterMs = this.readRetryAfterMs(error.data);
1148
+ debugLog(`GDEX resubscribe rate limited; retrying in ${retryAfterMs}ms`);
1149
+ await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
1150
+ }
1151
+ }
1152
+ waitForReconnectDelay(delay) {
1153
+ return new Promise((resolve) => {
1154
+ this.reconnectTimer = setTimeout(() => {
1155
+ this.reconnectTimer = void 0;
1156
+ this.reconnectDelayResolve = void 0;
1157
+ resolve();
1158
+ }, delay);
1159
+ this.reconnectDelayResolve = resolve;
1160
+ });
1161
+ }
1162
+ clearReconnectTimer() {
1163
+ if (this.reconnectTimer !== void 0) clearTimeout(this.reconnectTimer);
1164
+ this.reconnectTimer = void 0;
1165
+ const resolve = this.reconnectDelayResolve;
1166
+ this.reconnectDelayResolve = void 0;
1167
+ resolve === null || resolve === void 0 || resolve();
1168
+ }
1169
+ rejectPending(error) {
1170
+ for (const pending of this.pending.values()) {
1171
+ clearTimeout(pending.timeout);
1172
+ pending.reject(error);
1173
+ }
1174
+ this.pending.clear();
1175
+ }
1176
+ readRetryAfterMs(data) {
1177
+ if (!this.isRecord(data) || typeof data["retryAfterMs"] !== "number" || data["retryAfterMs"] < 0) return 1e3;
1178
+ return data["retryAfterMs"];
1179
+ }
1180
+ isRecord(value) {
1181
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1182
+ }
1183
+ };
1184
+
764
1185
  //#endregion
765
1186
  //#region src/version.ts
766
1187
  /** Package version embedded by the bundler, with a source-test fallback. */
767
- const SDK_VERSION = "1.0.0";
1188
+ const SDK_VERSION = "1.1.1";
768
1189
 
769
1190
  //#endregion
770
1191
  //#region src/classes/http_client.ts
@@ -1896,14 +2317,6 @@ async function resolveSymbol(symbols, token) {
1896
2317
  throw new GSwapSDKError("Token could not be resolved to a trading symbol.", "SYMBOL_NOT_FOUND", { token });
1897
2318
  }
1898
2319
 
1899
- //#endregion
1900
- //#region src/types/env.ts
1901
- /** Built-in GalaSwap deployment environments. */
1902
- const GSWAP_ENVIRONMENTS = {
1903
- prod: { dexBackendBaseUrl: "https://dex-backend-prod1.defi.gala.com" },
1904
- stage: { dexBackendBaseUrl: "https://swap-backend.stage.defi.ovh.gala.com" }
1905
- };
1906
-
1907
2320
  //#endregion
1908
2321
  //#region src/classes/gswap.ts
1909
2322
  /** Main entry point for the current GalaChainDex SDK. */
@@ -1919,6 +2332,9 @@ var GSwap = class {
1919
2332
  positions;
1920
2333
  swaps;
1921
2334
  assets;
2335
+ dexBackendWsUrl;
2336
+ webSocketImpl;
2337
+ streamClient;
1922
2338
  /**
1923
2339
  * Create an SDK client for prod or stage.
1924
2340
  *
@@ -1947,6 +2363,26 @@ var GSwap = class {
1947
2363
  this.positions = new Positions(this.gateway, this.symbols, this.signer, this.walletAddress);
1948
2364
  this.swaps = new Swaps(this.gateway, this.symbols, this.signer, this.walletAddress);
1949
2365
  this.assets = new Assets(this.dexBackendBaseUrl, httpClient);
2366
+ this.dexBackendWsUrl = (options === null || options === void 0 ? void 0 : options.dexBackendWsUrl) ?? ((options === null || options === void 0 ? void 0 : options.dexBackendBaseUrl) === void 0 ? environment.dexBackendWsUrl : `${this.dexBackendBaseUrl.replace(/^http/u, "ws")}/ws`);
2367
+ this.webSocketImpl = options === null || options === void 0 ? void 0 : options.webSocketImpl;
2368
+ }
2369
+ /**
2370
+ * The realtime stream client for this environment (created on first use, not connected until you
2371
+ * call `connect()`).
2372
+ *
2373
+ * @example
2374
+ * ```typescript
2375
+ * const gSwap = new GSwap({ env: 'stage' });
2376
+ * await gSwap.stream.connect();
2377
+ * await gSwap.stream.subscribeLiquidity((event) => console.log(event.action, event.amount0));
2378
+ * ```
2379
+ */
2380
+ get stream() {
2381
+ this.streamClient ??= new GdexStreamService({
2382
+ url: this.dexBackendWsUrl,
2383
+ ...this.webSocketImpl === void 0 ? {} : { webSocketImpl: this.webSocketImpl }
2384
+ });
2385
+ return this.streamClient;
1950
2386
  }
1951
2387
  };
1952
2388
  function trimTrailingSlash(value) {
@@ -2393,5 +2829,5 @@ var BrowserWalletSigner = class {
2393
2829
  };
2394
2830
 
2395
2831
  //#endregion
2396
- export { ALL_FEE_TIERS, Assets, BrowserWalletSigner, ChainGateway, FEE_TIER, GC_MAX_TICK, GC_MIN_TICK, GSWAP_ENVIRONMENTS, GSwap, GSwapSDKError, GalaWalletSigner, Pools, Positions, PrivateKeySigner, Quoting, SubmittedTransaction, Swaps, Symbols, TICK_SPACING_BY_FEE, alignTickDown, alignTickUp, assertTickRange, compositeKeyOf, getObjectProperty, getStringProperty, orderSymbols, parseJson, parseTokenClassKey, readOrderedSymbols, sqrtPriceToTick, tickFromPrice, tickToSqrtPrice, validateFee, validateNumericAmount, validatePriceValues, validateTickRange, validateTickSpacing, validateTokenDecimals, validateWalletAddress };
2832
+ export { ALL_FEE_TIERS, Assets, BrowserWalletSigner, ChainGateway, FEE_TIER, GC_MAX_TICK, GC_MIN_TICK, GSWAP_ENVIRONMENTS, GSwap, GSwapSDKError, GalaWalletSigner, GdexStreamError, GdexStreamService, Pools, Positions, PrivateKeySigner, Quoting, SubmittedTransaction, Swaps, Symbols, TICK_SPACING_BY_FEE, alignTickDown, alignTickUp, assertTickRange, compositeKeyOf, getObjectProperty, getStringProperty, isGdexLiquidityEvent, orderSymbols, parseJson, parseTokenClassKey, readOrderedSymbols, sqrtPriceToTick, tickFromPrice, tickToSqrtPrice, validateFee, validateNumericAmount, validatePriceValues, validateTickRange, validateTickSpacing, validateTokenDecimals, validateWalletAddress };
2397
2833
  //# sourceMappingURL=index.mjs.map