@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.cjs CHANGED
@@ -787,14 +787,435 @@ function isBlockNumber(value) {
787
787
  return typeof value === "number" && Number.isInteger(value) && value >= 0;
788
788
  }
789
789
 
790
+ //#endregion
791
+ //#region src/types/env.ts
792
+ /** Built-in GalaSwap deployment environments. */
793
+ const GSWAP_ENVIRONMENTS = {
794
+ prod: {
795
+ dexBackendBaseUrl: "https://dex-backend-prod1.defi.gala.com",
796
+ dexBackendWsUrl: "wss://dex-backend-prod1.defi.gala.com/ws"
797
+ },
798
+ stage: {
799
+ dexBackendBaseUrl: "https://swap-backend.stage.defi.ovh.gala.com",
800
+ dexBackendWsUrl: "wss://swap-backend.stage.defi.ovh.gala.com/ws"
801
+ }
802
+ };
803
+
790
804
  //#endregion
791
805
  //#region src/utils/debug.ts
792
806
  const debugLog = (0, debug.default)("GSWAP_SDK");
793
807
 
808
+ //#endregion
809
+ //#region src/utils/reconnection.ts
810
+ /** Counts reconnect attempts and doubles the delay between them, up to a ceiling. */
811
+ var ReconnectionBackoff = class {
812
+ options;
813
+ attempts = 0;
814
+ delayMs;
815
+ maxDelayMs;
816
+ constructor(options) {
817
+ this.options = options;
818
+ this.delayMs = options.baseDelayMs;
819
+ this.maxDelayMs = options.maxDelayMs ?? 3e4;
820
+ }
821
+ /** Whether another attempt is allowed. */
822
+ shouldRetry() {
823
+ return this.attempts < this.options.maxAttempts;
824
+ }
825
+ /** The delay to wait before the next attempt. */
826
+ nextDelayMs() {
827
+ return this.delayMs;
828
+ }
829
+ /** Record that an attempt is being made, and double the next delay. */
830
+ recordAttempt() {
831
+ this.attempts += 1;
832
+ this.delayMs = Math.min(this.delayMs * 2, this.maxDelayMs);
833
+ }
834
+ /** Forget every attempt: the connection is healthy again. */
835
+ reset() {
836
+ this.attempts = 0;
837
+ this.delayMs = this.options.baseDelayMs;
838
+ }
839
+ get attemptCount() {
840
+ return this.attempts;
841
+ }
842
+ get maxAttempts() {
843
+ return this.options.maxAttempts;
844
+ }
845
+ };
846
+
847
+ //#endregion
848
+ //#region src/classes/gdex_stream.ts
849
+ const GDEX_SUBPROTOCOL = "gdex.jsonrpc.v1";
850
+ const RATE_LIMITED = -32003;
851
+ const MAX_RESUBSCRIBE_RATE_RETRIES = 5;
852
+ const WEBSOCKET_OPEN = 1;
853
+ const LIQUIDITY_ACTIONS = [
854
+ "add",
855
+ "remove",
856
+ "collect"
857
+ ];
858
+ /** Whether a stream payload carries every field of a {@link GdexLiquidityEvent}. */
859
+ function isGdexLiquidityEvent(value) {
860
+ const { pool } = value;
861
+ 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";
862
+ }
863
+ /** A JSON-RPC error answered by the stream. */
864
+ var GdexStreamError = class extends Error {
865
+ code;
866
+ data;
867
+ constructor(code, message, data) {
868
+ super(message);
869
+ this.name = "GdexStreamError";
870
+ this.code = code;
871
+ if (data !== void 0) this.data = data;
872
+ }
873
+ };
874
+ /**
875
+ * Client for the gSwap realtime stream (gdex WebSocket Protocol v1): JSON-RPC 2.0 over one raw
876
+ * WebSocket, with automatic reconnect and resubscribe.
877
+ *
878
+ * @example
879
+ * ```typescript
880
+ * const stream = new GdexStreamService();
881
+ * await stream.connect();
882
+ * await stream.subscribeLiquidity(event => console.log(event.action, event.owner), {
883
+ * owner: 'client|618ae395c1c653111d3315be',
884
+ * });
885
+ * ```
886
+ */
887
+ var GdexStreamService = class {
888
+ url;
889
+ requestTimeoutMs;
890
+ webSocketConstructor;
891
+ backoff;
892
+ socket;
893
+ connectPromise;
894
+ nextRequestId = 0;
895
+ pending = /* @__PURE__ */ new Map();
896
+ subscriptionsByServerId = /* @__PURE__ */ new Map();
897
+ activeSubscriptions = /* @__PURE__ */ new Set();
898
+ intentionalClose = false;
899
+ reconnecting = false;
900
+ reconnectTimer;
901
+ reconnectDelayResolve;
902
+ constructor(config = {}) {
903
+ this.url = config.url ?? GSWAP_ENVIRONMENTS.prod.dexBackendWsUrl;
904
+ this.requestTimeoutMs = config.requestTimeoutMs ?? 15e3;
905
+ this.backoff = new ReconnectionBackoff({
906
+ maxAttempts: config.reconnectAttempts ?? 5,
907
+ baseDelayMs: config.reconnectDelayMs ?? 2e3
908
+ });
909
+ const implementation = config.webSocketImpl ?? globalThis.WebSocket;
910
+ 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).");
911
+ this.webSocketConstructor = implementation;
912
+ }
913
+ /** Open the connection. Resolves at once when already connected. */
914
+ connect() {
915
+ if (this.isConnected()) return Promise.resolve();
916
+ if (this.connectPromise) return this.connectPromise;
917
+ this.intentionalClose = false;
918
+ this.clearReconnectTimer();
919
+ this.connectPromise = this.openSocket();
920
+ return this.connectPromise;
921
+ }
922
+ /** Close the connection and stop reconnecting. */
923
+ disconnect() {
924
+ this.intentionalClose = true;
925
+ this.reconnecting = false;
926
+ this.clearReconnectTimer();
927
+ this.rejectPending(/* @__PURE__ */ new Error("GDEX stream disconnected"));
928
+ const socket = this.socket;
929
+ this.socket = void 0;
930
+ this.connectPromise = void 0;
931
+ socket === null || socket === void 0 || socket.close(1e3, "client disconnect");
932
+ }
933
+ isConnected() {
934
+ var _this$socket;
935
+ return ((_this$socket = this.socket) === null || _this$socket === void 0 ? void 0 : _this$socket.readyState) === WEBSOCKET_OPEN;
936
+ }
937
+ /** Raw JSON-RPC escape hatch. */
938
+ request(method, params) {
939
+ if (!this.isConnected() || !this.socket) return Promise.reject(/* @__PURE__ */ new Error("GDEX stream is not connected. Call connect() first."));
940
+ const id = ++this.nextRequestId;
941
+ const frame = {
942
+ jsonrpc: "2.0",
943
+ id,
944
+ method
945
+ };
946
+ if (params !== void 0) frame["params"] = params;
947
+ return new Promise((resolve, reject) => {
948
+ const timeout = setTimeout(() => {
949
+ this.pending.delete(id);
950
+ reject(/* @__PURE__ */ new Error(`GDEX request "${method}" timed out after ${this.requestTimeoutMs}ms`));
951
+ }, this.requestTimeoutMs);
952
+ this.pending.set(id, {
953
+ resolve: (value) => resolve(value),
954
+ reject,
955
+ timeout
956
+ });
957
+ try {
958
+ var _this$socket2;
959
+ (_this$socket2 = this.socket) === null || _this$socket2 === void 0 || _this$socket2.send(JSON.stringify(frame));
960
+ } catch (error) {
961
+ clearTimeout(timeout);
962
+ this.pending.delete(id);
963
+ reject(error instanceof Error ? error : new Error(String(error)));
964
+ }
965
+ });
966
+ }
967
+ serverInfo() {
968
+ return this.request("gdex_serverInfo");
969
+ }
970
+ ping() {
971
+ return this.request("gdex_ping");
972
+ }
973
+ getPool(selector) {
974
+ return this.request("gdex_getPool", selector);
975
+ }
976
+ getBalance(owner, tokenClassKey) {
977
+ return this.request("gdex_getBalance", tokenClassKey === void 0 ? { owner } : {
978
+ owner,
979
+ tokenClassKey
980
+ });
981
+ }
982
+ getPositions(opts) {
983
+ return this.request("gdex_getPositions", opts);
984
+ }
985
+ getBlockHeight() {
986
+ return this.request("gdex_getBlockHeight");
987
+ }
988
+ quote(params) {
989
+ return this.request("gdex_quote", params);
990
+ }
991
+ getToken(tokenClassKey) {
992
+ return this.request("gdex_getToken", { tokenClassKey });
993
+ }
994
+ /** One event per committed swap. Omit the pool to receive every pool's swaps. */
995
+ subscribeSwaps(cb, opts = {}) {
996
+ return this.subscribe("swap", cb, opts);
997
+ }
998
+ /**
999
+ * State changes of one pool (price, tick, reserves, liquidity). These events carry no acting wallet:
1000
+ * on v2 `creator` is whoever created the pool, not whoever just traded or added liquidity. For
1001
+ * "who did it", use {@link subscribeLiquidity} (`owner`) or {@link subscribeSwaps} (`sender`).
1002
+ */
1003
+ subscribePool(selector, cb, opts = {}) {
1004
+ return this.subscribe("pool", cb, {
1005
+ ...selector,
1006
+ ...opts
1007
+ });
1008
+ }
1009
+ /** Balance changes of one wallet. */
1010
+ subscribeBalances(owner, cb, opts = {}) {
1011
+ return this.subscribe("balance", cb, {
1012
+ owner,
1013
+ ...opts
1014
+ });
1015
+ }
1016
+ /** Each newly created pool. */
1017
+ subscribePoolCreated(cb, opts = {}) {
1018
+ return this.subscribe("poolCreated", cb, opts);
1019
+ }
1020
+ /**
1021
+ * One event per committed AddLiquidity, RemoveLiquidity and CollectPositionFees, on both contract
1022
+ * versions. Every filter is optional; with none, every liquidity event arrives. These events never
1023
+ * appear on {@link subscribeSwaps}. There is no snapshot: read positions with {@link getPositions}.
1024
+ * Deduplicate by `transactionId` plus `positionId`: a v1 BatchSubmit can hold several operations
1025
+ * under one transaction id.
1026
+ */
1027
+ subscribeLiquidity(cb, opts = {}) {
1028
+ return this.subscribe("liquidity", (event) => {
1029
+ if (isGdexLiquidityEvent(event)) cb(event);
1030
+ else debugLog("Ignoring a malformed liquidity event from the GDEX stream");
1031
+ }, opts);
1032
+ }
1033
+ /** Each block-height advance. */
1034
+ subscribeBlocks(cb, opts = {}) {
1035
+ return this.subscribe("blocks", cb, opts);
1036
+ }
1037
+ openSocket() {
1038
+ return new Promise((resolve, reject) => {
1039
+ let opened = false;
1040
+ const socket = new this.webSocketConstructor(this.url, GDEX_SUBPROTOCOL);
1041
+ this.socket = socket;
1042
+ socket.onopen = () => {
1043
+ if (this.socket !== socket) return;
1044
+ opened = true;
1045
+ this.connectPromise = void 0;
1046
+ if (!this.reconnecting) this.backoff.reset();
1047
+ debugLog("Connected to GDEX stream");
1048
+ resolve();
1049
+ };
1050
+ socket.onmessage = (event) => this.handleMessage(event.data);
1051
+ socket.onerror = () => {
1052
+ if (!opened) reject(/* @__PURE__ */ new Error(`Failed to connect to GDEX stream at ${this.url}`));
1053
+ };
1054
+ socket.onclose = (event) => {
1055
+ if (this.socket !== socket) return;
1056
+ this.socket = void 0;
1057
+ this.connectPromise = void 0;
1058
+ if (!opened) reject(/* @__PURE__ */ new Error(`GDEX stream closed before connecting (code ${event.code ?? 0})`));
1059
+ this.rejectPending(/* @__PURE__ */ new Error(`GDEX stream connection closed (code ${event.code ?? 0})`));
1060
+ if (!this.intentionalClose && !this.reconnecting) this.startReconnectLoop();
1061
+ };
1062
+ });
1063
+ }
1064
+ handleMessage(data) {
1065
+ if (typeof data !== "string") {
1066
+ debugLog("Ignoring non-text GDEX WebSocket frame");
1067
+ return;
1068
+ }
1069
+ let message;
1070
+ try {
1071
+ message = JSON.parse(data);
1072
+ } catch {
1073
+ debugLog("Ignoring invalid JSON from GDEX stream");
1074
+ return;
1075
+ }
1076
+ if (typeof message.id === "number") {
1077
+ const pending = this.pending.get(message.id);
1078
+ if (!pending) return;
1079
+ clearTimeout(pending.timeout);
1080
+ this.pending.delete(message.id);
1081
+ if (message.error) {
1082
+ const code = typeof message.error.code === "number" ? message.error.code : -32603;
1083
+ const errorMessage = typeof message.error.message === "string" ? message.error.message : "GDEX request failed";
1084
+ pending.reject(new GdexStreamError(code, errorMessage, message.error.data));
1085
+ } else pending.resolve(message.result);
1086
+ return;
1087
+ }
1088
+ if (message.method !== "gdex_subscription" || !this.isRecord(message.params)) return;
1089
+ const subscriptionId = message.params["subscription"];
1090
+ const result = message.params["result"];
1091
+ if (typeof subscriptionId !== "string" || !this.isRecord(result)) return;
1092
+ const subscription = this.subscriptionsByServerId.get(subscriptionId);
1093
+ if (!(subscription === null || subscription === void 0 ? void 0 : subscription.active)) return;
1094
+ try {
1095
+ subscription.callback(result);
1096
+ } catch (error) {
1097
+ debugLog("GDEX subscription callback failed", error);
1098
+ }
1099
+ }
1100
+ async subscribe(channel, callback, options) {
1101
+ const params = {
1102
+ channel,
1103
+ ...options
1104
+ };
1105
+ const result = await this.request("gdex_subscribe", params);
1106
+ let active;
1107
+ const handle = {
1108
+ subscriptionId: result.subscriptionId,
1109
+ unsubscribe: async () => this.unsubscribe(active)
1110
+ };
1111
+ active = {
1112
+ serverId: result.subscriptionId,
1113
+ params,
1114
+ callback,
1115
+ handle,
1116
+ active: true
1117
+ };
1118
+ this.activeSubscriptions.add(active);
1119
+ this.subscriptionsByServerId.set(active.serverId, active);
1120
+ return handle;
1121
+ }
1122
+ async unsubscribe(subscription) {
1123
+ if (!subscription.active) return;
1124
+ subscription.active = false;
1125
+ this.activeSubscriptions.delete(subscription);
1126
+ this.subscriptionsByServerId.delete(subscription.serverId);
1127
+ if (this.isConnected()) await this.request("gdex_unsubscribe", { subscriptionId: subscription.serverId });
1128
+ }
1129
+ startReconnectLoop() {
1130
+ if (this.reconnecting || this.intentionalClose) return;
1131
+ this.reconnecting = true;
1132
+ this.reconnectLoop();
1133
+ }
1134
+ async reconnectLoop() {
1135
+ while (!this.intentionalClose && this.backoff.shouldRetry()) {
1136
+ const delay = this.backoff.nextDelayMs();
1137
+ this.backoff.recordAttempt();
1138
+ debugLog(`GDEX reconnect attempt ${this.backoff.attemptCount}/${this.backoff.maxAttempts} in ${delay}ms`);
1139
+ await this.waitForReconnectDelay(delay);
1140
+ if (this.intentionalClose) break;
1141
+ try {
1142
+ await this.openSocket();
1143
+ await this.resubscribeAll();
1144
+ this.backoff.reset();
1145
+ this.reconnecting = false;
1146
+ return;
1147
+ } catch (error) {
1148
+ debugLog(`GDEX reconnect failed: ${error instanceof Error ? error.message : String(error)}`);
1149
+ }
1150
+ }
1151
+ this.reconnecting = false;
1152
+ if (!this.intentionalClose) debugLog("GDEX reconnection attempts exhausted");
1153
+ }
1154
+ async resubscribeAll() {
1155
+ this.subscriptionsByServerId.clear();
1156
+ for (const subscription of this.activeSubscriptions) {
1157
+ if (!subscription.active) continue;
1158
+ const params = {
1159
+ ...subscription.params,
1160
+ snapshot: true
1161
+ };
1162
+ const result = await this.resubscribeWithRateLimitRetry(params);
1163
+ if (!subscription.active) {
1164
+ await this.request("gdex_unsubscribe", { subscriptionId: result.subscriptionId });
1165
+ continue;
1166
+ }
1167
+ subscription.serverId = result.subscriptionId;
1168
+ subscription.handle.subscriptionId = result.subscriptionId;
1169
+ this.subscriptionsByServerId.set(result.subscriptionId, subscription);
1170
+ }
1171
+ }
1172
+ async resubscribeWithRateLimitRetry(params) {
1173
+ for (let attempt = 0;; attempt++) try {
1174
+ return await this.request("gdex_subscribe", params);
1175
+ } catch (error) {
1176
+ if (!(error instanceof GdexStreamError) || error.code !== RATE_LIMITED || attempt >= MAX_RESUBSCRIBE_RATE_RETRIES) throw error;
1177
+ const retryAfterMs = this.readRetryAfterMs(error.data);
1178
+ debugLog(`GDEX resubscribe rate limited; retrying in ${retryAfterMs}ms`);
1179
+ await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
1180
+ }
1181
+ }
1182
+ waitForReconnectDelay(delay) {
1183
+ return new Promise((resolve) => {
1184
+ this.reconnectTimer = setTimeout(() => {
1185
+ this.reconnectTimer = void 0;
1186
+ this.reconnectDelayResolve = void 0;
1187
+ resolve();
1188
+ }, delay);
1189
+ this.reconnectDelayResolve = resolve;
1190
+ });
1191
+ }
1192
+ clearReconnectTimer() {
1193
+ if (this.reconnectTimer !== void 0) clearTimeout(this.reconnectTimer);
1194
+ this.reconnectTimer = void 0;
1195
+ const resolve = this.reconnectDelayResolve;
1196
+ this.reconnectDelayResolve = void 0;
1197
+ resolve === null || resolve === void 0 || resolve();
1198
+ }
1199
+ rejectPending(error) {
1200
+ for (const pending of this.pending.values()) {
1201
+ clearTimeout(pending.timeout);
1202
+ pending.reject(error);
1203
+ }
1204
+ this.pending.clear();
1205
+ }
1206
+ readRetryAfterMs(data) {
1207
+ if (!this.isRecord(data) || typeof data["retryAfterMs"] !== "number" || data["retryAfterMs"] < 0) return 1e3;
1208
+ return data["retryAfterMs"];
1209
+ }
1210
+ isRecord(value) {
1211
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1212
+ }
1213
+ };
1214
+
794
1215
  //#endregion
795
1216
  //#region src/version.ts
796
1217
  /** Package version embedded by the bundler, with a source-test fallback. */
797
- const SDK_VERSION = "1.0.0";
1218
+ const SDK_VERSION = "1.1.1";
798
1219
 
799
1220
  //#endregion
800
1221
  //#region src/classes/http_client.ts
@@ -1926,14 +2347,6 @@ async function resolveSymbol(symbols, token) {
1926
2347
  throw new GSwapSDKError("Token could not be resolved to a trading symbol.", "SYMBOL_NOT_FOUND", { token });
1927
2348
  }
1928
2349
 
1929
- //#endregion
1930
- //#region src/types/env.ts
1931
- /** Built-in GalaSwap deployment environments. */
1932
- const GSWAP_ENVIRONMENTS = {
1933
- prod: { dexBackendBaseUrl: "https://dex-backend-prod1.defi.gala.com" },
1934
- stage: { dexBackendBaseUrl: "https://swap-backend.stage.defi.ovh.gala.com" }
1935
- };
1936
-
1937
2350
  //#endregion
1938
2351
  //#region src/classes/gswap.ts
1939
2352
  /** Main entry point for the current GalaChainDex SDK. */
@@ -1949,6 +2362,9 @@ var GSwap = class {
1949
2362
  positions;
1950
2363
  swaps;
1951
2364
  assets;
2365
+ dexBackendWsUrl;
2366
+ webSocketImpl;
2367
+ streamClient;
1952
2368
  /**
1953
2369
  * Create an SDK client for prod or stage.
1954
2370
  *
@@ -1977,6 +2393,26 @@ var GSwap = class {
1977
2393
  this.positions = new Positions(this.gateway, this.symbols, this.signer, this.walletAddress);
1978
2394
  this.swaps = new Swaps(this.gateway, this.symbols, this.signer, this.walletAddress);
1979
2395
  this.assets = new Assets(this.dexBackendBaseUrl, httpClient);
2396
+ 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`);
2397
+ this.webSocketImpl = options === null || options === void 0 ? void 0 : options.webSocketImpl;
2398
+ }
2399
+ /**
2400
+ * The realtime stream client for this environment (created on first use, not connected until you
2401
+ * call `connect()`).
2402
+ *
2403
+ * @example
2404
+ * ```typescript
2405
+ * const gSwap = new GSwap({ env: 'stage' });
2406
+ * await gSwap.stream.connect();
2407
+ * await gSwap.stream.subscribeLiquidity((event) => console.log(event.action, event.amount0));
2408
+ * ```
2409
+ */
2410
+ get stream() {
2411
+ this.streamClient ??= new GdexStreamService({
2412
+ url: this.dexBackendWsUrl,
2413
+ ...this.webSocketImpl === void 0 ? {} : { webSocketImpl: this.webSocketImpl }
2414
+ });
2415
+ return this.streamClient;
1980
2416
  }
1981
2417
  };
1982
2418
  function trimTrailingSlash(value) {
@@ -2434,6 +2870,8 @@ exports.GSWAP_ENVIRONMENTS = GSWAP_ENVIRONMENTS;
2434
2870
  exports.GSwap = GSwap;
2435
2871
  exports.GSwapSDKError = GSwapSDKError;
2436
2872
  exports.GalaWalletSigner = GalaWalletSigner;
2873
+ exports.GdexStreamError = GdexStreamError;
2874
+ exports.GdexStreamService = GdexStreamService;
2437
2875
  exports.Pools = Pools;
2438
2876
  exports.Positions = Positions;
2439
2877
  exports.PrivateKeySigner = PrivateKeySigner;
@@ -2448,6 +2886,7 @@ exports.assertTickRange = assertTickRange;
2448
2886
  exports.compositeKeyOf = compositeKeyOf;
2449
2887
  exports.getObjectProperty = getObjectProperty;
2450
2888
  exports.getStringProperty = getStringProperty;
2889
+ exports.isGdexLiquidityEvent = isGdexLiquidityEvent;
2451
2890
  exports.orderSymbols = orderSymbols;
2452
2891
  exports.parseJson = parseJson;
2453
2892
  exports.parseTokenClassKey = parseTokenClassKey;