@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.cjs CHANGED
@@ -787,14 +787,431 @@ 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
+ /** State changes of one pool. */
999
+ subscribePool(selector, cb, opts = {}) {
1000
+ return this.subscribe("pool", cb, {
1001
+ ...selector,
1002
+ ...opts
1003
+ });
1004
+ }
1005
+ /** Balance changes of one wallet. */
1006
+ subscribeBalances(owner, cb, opts = {}) {
1007
+ return this.subscribe("balance", cb, {
1008
+ owner,
1009
+ ...opts
1010
+ });
1011
+ }
1012
+ /** Each newly created pool. */
1013
+ subscribePoolCreated(cb, opts = {}) {
1014
+ return this.subscribe("poolCreated", cb, opts);
1015
+ }
1016
+ /**
1017
+ * One event per committed AddLiquidity, RemoveLiquidity and CollectPositionFees, on both contract
1018
+ * versions. Every filter is optional; with none, every liquidity event arrives. These events never
1019
+ * appear on {@link subscribeSwaps}. There is no snapshot: read positions with {@link getPositions}.
1020
+ * Deduplicate by `transactionId` plus `positionId`: a v1 BatchSubmit can hold several operations
1021
+ * under one transaction id.
1022
+ */
1023
+ subscribeLiquidity(cb, opts = {}) {
1024
+ return this.subscribe("liquidity", (event) => {
1025
+ if (isGdexLiquidityEvent(event)) cb(event);
1026
+ else debugLog("Ignoring a malformed liquidity event from the GDEX stream");
1027
+ }, opts);
1028
+ }
1029
+ /** Each block-height advance. */
1030
+ subscribeBlocks(cb, opts = {}) {
1031
+ return this.subscribe("blocks", cb, opts);
1032
+ }
1033
+ openSocket() {
1034
+ return new Promise((resolve, reject) => {
1035
+ let opened = false;
1036
+ const socket = new this.webSocketConstructor(this.url, GDEX_SUBPROTOCOL);
1037
+ this.socket = socket;
1038
+ socket.onopen = () => {
1039
+ if (this.socket !== socket) return;
1040
+ opened = true;
1041
+ this.connectPromise = void 0;
1042
+ if (!this.reconnecting) this.backoff.reset();
1043
+ debugLog("Connected to GDEX stream");
1044
+ resolve();
1045
+ };
1046
+ socket.onmessage = (event) => this.handleMessage(event.data);
1047
+ socket.onerror = () => {
1048
+ if (!opened) reject(/* @__PURE__ */ new Error(`Failed to connect to GDEX stream at ${this.url}`));
1049
+ };
1050
+ socket.onclose = (event) => {
1051
+ if (this.socket !== socket) return;
1052
+ this.socket = void 0;
1053
+ this.connectPromise = void 0;
1054
+ if (!opened) reject(/* @__PURE__ */ new Error(`GDEX stream closed before connecting (code ${event.code ?? 0})`));
1055
+ this.rejectPending(/* @__PURE__ */ new Error(`GDEX stream connection closed (code ${event.code ?? 0})`));
1056
+ if (!this.intentionalClose && !this.reconnecting) this.startReconnectLoop();
1057
+ };
1058
+ });
1059
+ }
1060
+ handleMessage(data) {
1061
+ if (typeof data !== "string") {
1062
+ debugLog("Ignoring non-text GDEX WebSocket frame");
1063
+ return;
1064
+ }
1065
+ let message;
1066
+ try {
1067
+ message = JSON.parse(data);
1068
+ } catch {
1069
+ debugLog("Ignoring invalid JSON from GDEX stream");
1070
+ return;
1071
+ }
1072
+ if (typeof message.id === "number") {
1073
+ const pending = this.pending.get(message.id);
1074
+ if (!pending) return;
1075
+ clearTimeout(pending.timeout);
1076
+ this.pending.delete(message.id);
1077
+ if (message.error) {
1078
+ const code = typeof message.error.code === "number" ? message.error.code : -32603;
1079
+ const errorMessage = typeof message.error.message === "string" ? message.error.message : "GDEX request failed";
1080
+ pending.reject(new GdexStreamError(code, errorMessage, message.error.data));
1081
+ } else pending.resolve(message.result);
1082
+ return;
1083
+ }
1084
+ if (message.method !== "gdex_subscription" || !this.isRecord(message.params)) return;
1085
+ const subscriptionId = message.params["subscription"];
1086
+ const result = message.params["result"];
1087
+ if (typeof subscriptionId !== "string" || !this.isRecord(result)) return;
1088
+ const subscription = this.subscriptionsByServerId.get(subscriptionId);
1089
+ if (!(subscription === null || subscription === void 0 ? void 0 : subscription.active)) return;
1090
+ try {
1091
+ subscription.callback(result);
1092
+ } catch (error) {
1093
+ debugLog("GDEX subscription callback failed", error);
1094
+ }
1095
+ }
1096
+ async subscribe(channel, callback, options) {
1097
+ const params = {
1098
+ channel,
1099
+ ...options
1100
+ };
1101
+ const result = await this.request("gdex_subscribe", params);
1102
+ let active;
1103
+ const handle = {
1104
+ subscriptionId: result.subscriptionId,
1105
+ unsubscribe: async () => this.unsubscribe(active)
1106
+ };
1107
+ active = {
1108
+ serverId: result.subscriptionId,
1109
+ params,
1110
+ callback,
1111
+ handle,
1112
+ active: true
1113
+ };
1114
+ this.activeSubscriptions.add(active);
1115
+ this.subscriptionsByServerId.set(active.serverId, active);
1116
+ return handle;
1117
+ }
1118
+ async unsubscribe(subscription) {
1119
+ if (!subscription.active) return;
1120
+ subscription.active = false;
1121
+ this.activeSubscriptions.delete(subscription);
1122
+ this.subscriptionsByServerId.delete(subscription.serverId);
1123
+ if (this.isConnected()) await this.request("gdex_unsubscribe", { subscriptionId: subscription.serverId });
1124
+ }
1125
+ startReconnectLoop() {
1126
+ if (this.reconnecting || this.intentionalClose) return;
1127
+ this.reconnecting = true;
1128
+ this.reconnectLoop();
1129
+ }
1130
+ async reconnectLoop() {
1131
+ while (!this.intentionalClose && this.backoff.shouldRetry()) {
1132
+ const delay = this.backoff.nextDelayMs();
1133
+ this.backoff.recordAttempt();
1134
+ debugLog(`GDEX reconnect attempt ${this.backoff.attemptCount}/${this.backoff.maxAttempts} in ${delay}ms`);
1135
+ await this.waitForReconnectDelay(delay);
1136
+ if (this.intentionalClose) break;
1137
+ try {
1138
+ await this.openSocket();
1139
+ await this.resubscribeAll();
1140
+ this.backoff.reset();
1141
+ this.reconnecting = false;
1142
+ return;
1143
+ } catch (error) {
1144
+ debugLog(`GDEX reconnect failed: ${error instanceof Error ? error.message : String(error)}`);
1145
+ }
1146
+ }
1147
+ this.reconnecting = false;
1148
+ if (!this.intentionalClose) debugLog("GDEX reconnection attempts exhausted");
1149
+ }
1150
+ async resubscribeAll() {
1151
+ this.subscriptionsByServerId.clear();
1152
+ for (const subscription of this.activeSubscriptions) {
1153
+ if (!subscription.active) continue;
1154
+ const params = {
1155
+ ...subscription.params,
1156
+ snapshot: true
1157
+ };
1158
+ const result = await this.resubscribeWithRateLimitRetry(params);
1159
+ if (!subscription.active) {
1160
+ await this.request("gdex_unsubscribe", { subscriptionId: result.subscriptionId });
1161
+ continue;
1162
+ }
1163
+ subscription.serverId = result.subscriptionId;
1164
+ subscription.handle.subscriptionId = result.subscriptionId;
1165
+ this.subscriptionsByServerId.set(result.subscriptionId, subscription);
1166
+ }
1167
+ }
1168
+ async resubscribeWithRateLimitRetry(params) {
1169
+ for (let attempt = 0;; attempt++) try {
1170
+ return await this.request("gdex_subscribe", params);
1171
+ } catch (error) {
1172
+ if (!(error instanceof GdexStreamError) || error.code !== RATE_LIMITED || attempt >= MAX_RESUBSCRIBE_RATE_RETRIES) throw error;
1173
+ const retryAfterMs = this.readRetryAfterMs(error.data);
1174
+ debugLog(`GDEX resubscribe rate limited; retrying in ${retryAfterMs}ms`);
1175
+ await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
1176
+ }
1177
+ }
1178
+ waitForReconnectDelay(delay) {
1179
+ return new Promise((resolve) => {
1180
+ this.reconnectTimer = setTimeout(() => {
1181
+ this.reconnectTimer = void 0;
1182
+ this.reconnectDelayResolve = void 0;
1183
+ resolve();
1184
+ }, delay);
1185
+ this.reconnectDelayResolve = resolve;
1186
+ });
1187
+ }
1188
+ clearReconnectTimer() {
1189
+ if (this.reconnectTimer !== void 0) clearTimeout(this.reconnectTimer);
1190
+ this.reconnectTimer = void 0;
1191
+ const resolve = this.reconnectDelayResolve;
1192
+ this.reconnectDelayResolve = void 0;
1193
+ resolve === null || resolve === void 0 || resolve();
1194
+ }
1195
+ rejectPending(error) {
1196
+ for (const pending of this.pending.values()) {
1197
+ clearTimeout(pending.timeout);
1198
+ pending.reject(error);
1199
+ }
1200
+ this.pending.clear();
1201
+ }
1202
+ readRetryAfterMs(data) {
1203
+ if (!this.isRecord(data) || typeof data["retryAfterMs"] !== "number" || data["retryAfterMs"] < 0) return 1e3;
1204
+ return data["retryAfterMs"];
1205
+ }
1206
+ isRecord(value) {
1207
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1208
+ }
1209
+ };
1210
+
794
1211
  //#endregion
795
1212
  //#region src/version.ts
796
1213
  /** Package version embedded by the bundler, with a source-test fallback. */
797
- const SDK_VERSION = "1.0.0";
1214
+ const SDK_VERSION = "1.1.0";
798
1215
 
799
1216
  //#endregion
800
1217
  //#region src/classes/http_client.ts
@@ -1926,14 +2343,6 @@ async function resolveSymbol(symbols, token) {
1926
2343
  throw new GSwapSDKError("Token could not be resolved to a trading symbol.", "SYMBOL_NOT_FOUND", { token });
1927
2344
  }
1928
2345
 
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
2346
  //#endregion
1938
2347
  //#region src/classes/gswap.ts
1939
2348
  /** Main entry point for the current GalaChainDex SDK. */
@@ -1949,6 +2358,9 @@ var GSwap = class {
1949
2358
  positions;
1950
2359
  swaps;
1951
2360
  assets;
2361
+ dexBackendWsUrl;
2362
+ webSocketImpl;
2363
+ streamClient;
1952
2364
  /**
1953
2365
  * Create an SDK client for prod or stage.
1954
2366
  *
@@ -1977,6 +2389,26 @@ var GSwap = class {
1977
2389
  this.positions = new Positions(this.gateway, this.symbols, this.signer, this.walletAddress);
1978
2390
  this.swaps = new Swaps(this.gateway, this.symbols, this.signer, this.walletAddress);
1979
2391
  this.assets = new Assets(this.dexBackendBaseUrl, httpClient);
2392
+ 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`);
2393
+ this.webSocketImpl = options === null || options === void 0 ? void 0 : options.webSocketImpl;
2394
+ }
2395
+ /**
2396
+ * The realtime stream client for this environment (created on first use, not connected until you
2397
+ * call `connect()`).
2398
+ *
2399
+ * @example
2400
+ * ```typescript
2401
+ * const gSwap = new GSwap({ env: 'stage' });
2402
+ * await gSwap.stream.connect();
2403
+ * await gSwap.stream.subscribeLiquidity((event) => console.log(event.action, event.amount0));
2404
+ * ```
2405
+ */
2406
+ get stream() {
2407
+ this.streamClient ??= new GdexStreamService({
2408
+ url: this.dexBackendWsUrl,
2409
+ ...this.webSocketImpl === void 0 ? {} : { webSocketImpl: this.webSocketImpl }
2410
+ });
2411
+ return this.streamClient;
1980
2412
  }
1981
2413
  };
1982
2414
  function trimTrailingSlash(value) {
@@ -2434,6 +2866,8 @@ exports.GSWAP_ENVIRONMENTS = GSWAP_ENVIRONMENTS;
2434
2866
  exports.GSwap = GSwap;
2435
2867
  exports.GSwapSDKError = GSwapSDKError;
2436
2868
  exports.GalaWalletSigner = GalaWalletSigner;
2869
+ exports.GdexStreamError = GdexStreamError;
2870
+ exports.GdexStreamService = GdexStreamService;
2437
2871
  exports.Pools = Pools;
2438
2872
  exports.Positions = Positions;
2439
2873
  exports.PrivateKeySigner = PrivateKeySigner;
@@ -2448,6 +2882,7 @@ exports.assertTickRange = assertTickRange;
2448
2882
  exports.compositeKeyOf = compositeKeyOf;
2449
2883
  exports.getObjectProperty = getObjectProperty;
2450
2884
  exports.getStringProperty = getStringProperty;
2885
+ exports.isGdexLiquidityEvent = isGdexLiquidityEvent;
2451
2886
  exports.orderSymbols = orderSymbols;
2452
2887
  exports.parseJson = parseJson;
2453
2888
  exports.parseTokenClassKey = parseTokenClassKey;