@gala-chain/gswap-sdk 1.0.0 → 1.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.
package/dist/index.mjs CHANGED
@@ -757,14 +757,431 @@ 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
+ /** State changes of one pool. */
969
+ subscribePool(selector, cb, opts = {}) {
970
+ return this.subscribe("pool", cb, {
971
+ ...selector,
972
+ ...opts
973
+ });
974
+ }
975
+ /** Balance changes of one wallet. */
976
+ subscribeBalances(owner, cb, opts = {}) {
977
+ return this.subscribe("balance", cb, {
978
+ owner,
979
+ ...opts
980
+ });
981
+ }
982
+ /** Each newly created pool. */
983
+ subscribePoolCreated(cb, opts = {}) {
984
+ return this.subscribe("poolCreated", cb, opts);
985
+ }
986
+ /**
987
+ * One event per committed AddLiquidity, RemoveLiquidity and CollectPositionFees, on both contract
988
+ * versions. Every filter is optional; with none, every liquidity event arrives. These events never
989
+ * appear on {@link subscribeSwaps}. There is no snapshot: read positions with {@link getPositions}.
990
+ * Deduplicate by `transactionId` plus `positionId`: a v1 BatchSubmit can hold several operations
991
+ * under one transaction id.
992
+ */
993
+ subscribeLiquidity(cb, opts = {}) {
994
+ return this.subscribe("liquidity", (event) => {
995
+ if (isGdexLiquidityEvent(event)) cb(event);
996
+ else debugLog("Ignoring a malformed liquidity event from the GDEX stream");
997
+ }, opts);
998
+ }
999
+ /** Each block-height advance. */
1000
+ subscribeBlocks(cb, opts = {}) {
1001
+ return this.subscribe("blocks", cb, opts);
1002
+ }
1003
+ openSocket() {
1004
+ return new Promise((resolve, reject) => {
1005
+ let opened = false;
1006
+ const socket = new this.webSocketConstructor(this.url, GDEX_SUBPROTOCOL);
1007
+ this.socket = socket;
1008
+ socket.onopen = () => {
1009
+ if (this.socket !== socket) return;
1010
+ opened = true;
1011
+ this.connectPromise = void 0;
1012
+ if (!this.reconnecting) this.backoff.reset();
1013
+ debugLog("Connected to GDEX stream");
1014
+ resolve();
1015
+ };
1016
+ socket.onmessage = (event) => this.handleMessage(event.data);
1017
+ socket.onerror = () => {
1018
+ if (!opened) reject(/* @__PURE__ */ new Error(`Failed to connect to GDEX stream at ${this.url}`));
1019
+ };
1020
+ socket.onclose = (event) => {
1021
+ if (this.socket !== socket) return;
1022
+ this.socket = void 0;
1023
+ this.connectPromise = void 0;
1024
+ if (!opened) reject(/* @__PURE__ */ new Error(`GDEX stream closed before connecting (code ${event.code ?? 0})`));
1025
+ this.rejectPending(/* @__PURE__ */ new Error(`GDEX stream connection closed (code ${event.code ?? 0})`));
1026
+ if (!this.intentionalClose && !this.reconnecting) this.startReconnectLoop();
1027
+ };
1028
+ });
1029
+ }
1030
+ handleMessage(data) {
1031
+ if (typeof data !== "string") {
1032
+ debugLog("Ignoring non-text GDEX WebSocket frame");
1033
+ return;
1034
+ }
1035
+ let message;
1036
+ try {
1037
+ message = JSON.parse(data);
1038
+ } catch {
1039
+ debugLog("Ignoring invalid JSON from GDEX stream");
1040
+ return;
1041
+ }
1042
+ if (typeof message.id === "number") {
1043
+ const pending = this.pending.get(message.id);
1044
+ if (!pending) return;
1045
+ clearTimeout(pending.timeout);
1046
+ this.pending.delete(message.id);
1047
+ if (message.error) {
1048
+ const code = typeof message.error.code === "number" ? message.error.code : -32603;
1049
+ const errorMessage = typeof message.error.message === "string" ? message.error.message : "GDEX request failed";
1050
+ pending.reject(new GdexStreamError(code, errorMessage, message.error.data));
1051
+ } else pending.resolve(message.result);
1052
+ return;
1053
+ }
1054
+ if (message.method !== "gdex_subscription" || !this.isRecord(message.params)) return;
1055
+ const subscriptionId = message.params["subscription"];
1056
+ const result = message.params["result"];
1057
+ if (typeof subscriptionId !== "string" || !this.isRecord(result)) return;
1058
+ const subscription = this.subscriptionsByServerId.get(subscriptionId);
1059
+ if (!(subscription === null || subscription === void 0 ? void 0 : subscription.active)) return;
1060
+ try {
1061
+ subscription.callback(result);
1062
+ } catch (error) {
1063
+ debugLog("GDEX subscription callback failed", error);
1064
+ }
1065
+ }
1066
+ async subscribe(channel, callback, options) {
1067
+ const params = {
1068
+ channel,
1069
+ ...options
1070
+ };
1071
+ const result = await this.request("gdex_subscribe", params);
1072
+ let active;
1073
+ const handle = {
1074
+ subscriptionId: result.subscriptionId,
1075
+ unsubscribe: async () => this.unsubscribe(active)
1076
+ };
1077
+ active = {
1078
+ serverId: result.subscriptionId,
1079
+ params,
1080
+ callback,
1081
+ handle,
1082
+ active: true
1083
+ };
1084
+ this.activeSubscriptions.add(active);
1085
+ this.subscriptionsByServerId.set(active.serverId, active);
1086
+ return handle;
1087
+ }
1088
+ async unsubscribe(subscription) {
1089
+ if (!subscription.active) return;
1090
+ subscription.active = false;
1091
+ this.activeSubscriptions.delete(subscription);
1092
+ this.subscriptionsByServerId.delete(subscription.serverId);
1093
+ if (this.isConnected()) await this.request("gdex_unsubscribe", { subscriptionId: subscription.serverId });
1094
+ }
1095
+ startReconnectLoop() {
1096
+ if (this.reconnecting || this.intentionalClose) return;
1097
+ this.reconnecting = true;
1098
+ this.reconnectLoop();
1099
+ }
1100
+ async reconnectLoop() {
1101
+ while (!this.intentionalClose && this.backoff.shouldRetry()) {
1102
+ const delay = this.backoff.nextDelayMs();
1103
+ this.backoff.recordAttempt();
1104
+ debugLog(`GDEX reconnect attempt ${this.backoff.attemptCount}/${this.backoff.maxAttempts} in ${delay}ms`);
1105
+ await this.waitForReconnectDelay(delay);
1106
+ if (this.intentionalClose) break;
1107
+ try {
1108
+ await this.openSocket();
1109
+ await this.resubscribeAll();
1110
+ this.backoff.reset();
1111
+ this.reconnecting = false;
1112
+ return;
1113
+ } catch (error) {
1114
+ debugLog(`GDEX reconnect failed: ${error instanceof Error ? error.message : String(error)}`);
1115
+ }
1116
+ }
1117
+ this.reconnecting = false;
1118
+ if (!this.intentionalClose) debugLog("GDEX reconnection attempts exhausted");
1119
+ }
1120
+ async resubscribeAll() {
1121
+ this.subscriptionsByServerId.clear();
1122
+ for (const subscription of this.activeSubscriptions) {
1123
+ if (!subscription.active) continue;
1124
+ const params = {
1125
+ ...subscription.params,
1126
+ snapshot: true
1127
+ };
1128
+ const result = await this.resubscribeWithRateLimitRetry(params);
1129
+ if (!subscription.active) {
1130
+ await this.request("gdex_unsubscribe", { subscriptionId: result.subscriptionId });
1131
+ continue;
1132
+ }
1133
+ subscription.serverId = result.subscriptionId;
1134
+ subscription.handle.subscriptionId = result.subscriptionId;
1135
+ this.subscriptionsByServerId.set(result.subscriptionId, subscription);
1136
+ }
1137
+ }
1138
+ async resubscribeWithRateLimitRetry(params) {
1139
+ for (let attempt = 0;; attempt++) try {
1140
+ return await this.request("gdex_subscribe", params);
1141
+ } catch (error) {
1142
+ if (!(error instanceof GdexStreamError) || error.code !== RATE_LIMITED || attempt >= MAX_RESUBSCRIBE_RATE_RETRIES) throw error;
1143
+ const retryAfterMs = this.readRetryAfterMs(error.data);
1144
+ debugLog(`GDEX resubscribe rate limited; retrying in ${retryAfterMs}ms`);
1145
+ await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
1146
+ }
1147
+ }
1148
+ waitForReconnectDelay(delay) {
1149
+ return new Promise((resolve) => {
1150
+ this.reconnectTimer = setTimeout(() => {
1151
+ this.reconnectTimer = void 0;
1152
+ this.reconnectDelayResolve = void 0;
1153
+ resolve();
1154
+ }, delay);
1155
+ this.reconnectDelayResolve = resolve;
1156
+ });
1157
+ }
1158
+ clearReconnectTimer() {
1159
+ if (this.reconnectTimer !== void 0) clearTimeout(this.reconnectTimer);
1160
+ this.reconnectTimer = void 0;
1161
+ const resolve = this.reconnectDelayResolve;
1162
+ this.reconnectDelayResolve = void 0;
1163
+ resolve === null || resolve === void 0 || resolve();
1164
+ }
1165
+ rejectPending(error) {
1166
+ for (const pending of this.pending.values()) {
1167
+ clearTimeout(pending.timeout);
1168
+ pending.reject(error);
1169
+ }
1170
+ this.pending.clear();
1171
+ }
1172
+ readRetryAfterMs(data) {
1173
+ if (!this.isRecord(data) || typeof data["retryAfterMs"] !== "number" || data["retryAfterMs"] < 0) return 1e3;
1174
+ return data["retryAfterMs"];
1175
+ }
1176
+ isRecord(value) {
1177
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1178
+ }
1179
+ };
1180
+
764
1181
  //#endregion
765
1182
  //#region src/version.ts
766
1183
  /** Package version embedded by the bundler, with a source-test fallback. */
767
- const SDK_VERSION = "1.0.0";
1184
+ const SDK_VERSION = "1.1.0";
768
1185
 
769
1186
  //#endregion
770
1187
  //#region src/classes/http_client.ts
@@ -1896,14 +2313,6 @@ async function resolveSymbol(symbols, token) {
1896
2313
  throw new GSwapSDKError("Token could not be resolved to a trading symbol.", "SYMBOL_NOT_FOUND", { token });
1897
2314
  }
1898
2315
 
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
2316
  //#endregion
1908
2317
  //#region src/classes/gswap.ts
1909
2318
  /** Main entry point for the current GalaChainDex SDK. */
@@ -1919,6 +2328,9 @@ var GSwap = class {
1919
2328
  positions;
1920
2329
  swaps;
1921
2330
  assets;
2331
+ dexBackendWsUrl;
2332
+ webSocketImpl;
2333
+ streamClient;
1922
2334
  /**
1923
2335
  * Create an SDK client for prod or stage.
1924
2336
  *
@@ -1947,6 +2359,26 @@ var GSwap = class {
1947
2359
  this.positions = new Positions(this.gateway, this.symbols, this.signer, this.walletAddress);
1948
2360
  this.swaps = new Swaps(this.gateway, this.symbols, this.signer, this.walletAddress);
1949
2361
  this.assets = new Assets(this.dexBackendBaseUrl, httpClient);
2362
+ 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`);
2363
+ this.webSocketImpl = options === null || options === void 0 ? void 0 : options.webSocketImpl;
2364
+ }
2365
+ /**
2366
+ * The realtime stream client for this environment (created on first use, not connected until you
2367
+ * call `connect()`).
2368
+ *
2369
+ * @example
2370
+ * ```typescript
2371
+ * const gSwap = new GSwap({ env: 'stage' });
2372
+ * await gSwap.stream.connect();
2373
+ * await gSwap.stream.subscribeLiquidity((event) => console.log(event.action, event.amount0));
2374
+ * ```
2375
+ */
2376
+ get stream() {
2377
+ this.streamClient ??= new GdexStreamService({
2378
+ url: this.dexBackendWsUrl,
2379
+ ...this.webSocketImpl === void 0 ? {} : { webSocketImpl: this.webSocketImpl }
2380
+ });
2381
+ return this.streamClient;
1950
2382
  }
1951
2383
  };
1952
2384
  function trimTrailingSlash(value) {
@@ -2393,5 +2825,5 @@ var BrowserWalletSigner = class {
2393
2825
  };
2394
2826
 
2395
2827
  //#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 };
2828
+ 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
2829
  //# sourceMappingURL=index.mjs.map