@symmio/trading-core 4.4.0 → 4.5.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 (123) hide show
  1. package/dist/candles/adapters/tradingview/map-resolution.d.ts.map +1 -1
  2. package/dist/candles/adapters/tradingview/map-resolution.js +2 -0
  3. package/dist/candles/adapters/tradingview/map-resolution.js.map +1 -1
  4. package/dist/candles/adapters/tradingview/to-tradingview-datafeed.d.ts.map +1 -1
  5. package/dist/candles/adapters/tradingview/to-tradingview-datafeed.js +6 -4
  6. package/dist/candles/adapters/tradingview/to-tradingview-datafeed.js.map +1 -1
  7. package/dist/candles/history-query.d.ts +67 -0
  8. package/dist/candles/history-query.d.ts.map +1 -0
  9. package/dist/candles/history-query.js +80 -0
  10. package/dist/candles/history-query.js.map +1 -0
  11. package/dist/candles/index.d.ts +3 -0
  12. package/dist/candles/index.d.ts.map +1 -1
  13. package/dist/candles/merge-candle-pages.d.ts +5 -0
  14. package/dist/candles/merge-candle-pages.d.ts.map +1 -0
  15. package/dist/candles/merge-candle-pages.js +13 -0
  16. package/dist/candles/merge-candle-pages.js.map +1 -0
  17. package/dist/candles/query.d.ts +5 -1
  18. package/dist/candles/query.d.ts.map +1 -1
  19. package/dist/candles/query.js +3 -2
  20. package/dist/candles/query.js.map +1 -1
  21. package/dist/candles/refresh-candle-history.d.ts +31 -0
  22. package/dist/candles/refresh-candle-history.d.ts.map +1 -0
  23. package/dist/candles/refresh-candle-history.js +91 -0
  24. package/dist/candles/refresh-candle-history.js.map +1 -0
  25. package/dist/candles/resolution.d.ts +3 -3
  26. package/dist/candles/resolution.d.ts.map +1 -1
  27. package/dist/candles/resolution.js +1 -0
  28. package/dist/candles/resolution.js.map +1 -1
  29. package/dist/candles/sources/binance/create-binance-candle-source.d.ts.map +1 -1
  30. package/dist/candles/sources/binance/create-binance-candle-source.js +3 -1
  31. package/dist/candles/sources/binance/create-binance-candle-source.js.map +1 -1
  32. package/dist/candles/sources/lowcap/create-lowcap-candle-source.d.ts +35 -0
  33. package/dist/candles/sources/lowcap/create-lowcap-candle-source.d.ts.map +1 -0
  34. package/dist/candles/sources/lowcap/create-lowcap-candle-source.js +104 -0
  35. package/dist/candles/sources/lowcap/create-lowcap-candle-source.js.map +1 -0
  36. package/dist/candles/sources/lowcap/create-lowcap-symbol-loader.d.ts +4 -0
  37. package/dist/candles/sources/lowcap/create-lowcap-symbol-loader.d.ts.map +1 -0
  38. package/dist/candles/sources/lowcap/create-lowcap-symbol-loader.js +40 -0
  39. package/dist/candles/sources/lowcap/create-lowcap-symbol-loader.js.map +1 -0
  40. package/dist/candles/sources/lowcap/get-lowcap-candles.d.ts +12 -0
  41. package/dist/candles/sources/lowcap/get-lowcap-candles.d.ts.map +1 -0
  42. package/dist/candles/sources/lowcap/get-lowcap-candles.js +48 -0
  43. package/dist/candles/sources/lowcap/get-lowcap-candles.js.map +1 -0
  44. package/dist/candles/sources/lowcap/index.d.ts +2 -0
  45. package/dist/candles/sources/lowcap/index.d.ts.map +1 -0
  46. package/dist/candles/sources/lowcap/lowcap-candle-time.d.ts +9 -0
  47. package/dist/candles/sources/lowcap/lowcap-candle-time.d.ts.map +1 -0
  48. package/dist/candles/sources/lowcap/lowcap-candle-time.js +24 -0
  49. package/dist/candles/sources/lowcap/lowcap-candle-time.js.map +1 -0
  50. package/dist/candles/sources/lowcap/map-resolution.d.ts +16 -0
  51. package/dist/candles/sources/lowcap/map-resolution.d.ts.map +1 -0
  52. package/dist/candles/sources/lowcap/map-resolution.js +26 -0
  53. package/dist/candles/sources/lowcap/map-resolution.js.map +1 -0
  54. package/dist/candles/sources/lowcap/resolve-lowcap-symbol.d.ts +12 -0
  55. package/dist/candles/sources/lowcap/resolve-lowcap-symbol.d.ts.map +1 -0
  56. package/dist/candles/sources/lowcap/resolve-lowcap-symbol.js +8 -0
  57. package/dist/candles/sources/lowcap/resolve-lowcap-symbol.js.map +1 -0
  58. package/dist/candles/sources/lowcap/watch-lowcap-candles.d.ts +19 -0
  59. package/dist/candles/sources/lowcap/watch-lowcap-candles.d.ts.map +1 -0
  60. package/dist/candles/sources/lowcap/watch-lowcap-candles.js +104 -0
  61. package/dist/candles/sources/lowcap/watch-lowcap-candles.js.map +1 -0
  62. package/dist/candles/types.d.ts +32 -16
  63. package/dist/candles/types.d.ts.map +1 -1
  64. package/dist/gasless/get-gasless-batch-funding/batch-fee-approvals.d.ts +20 -0
  65. package/dist/gasless/get-gasless-batch-funding/batch-fee-approvals.d.ts.map +1 -0
  66. package/dist/gasless/get-gasless-batch-funding/batch-fee-approvals.js +29 -0
  67. package/dist/gasless/get-gasless-batch-funding/batch-fee-approvals.js.map +1 -0
  68. package/dist/gasless/get-gasless-batch-funding/get-gasless-batch-funding.d.ts +43 -0
  69. package/dist/gasless/get-gasless-batch-funding/get-gasless-batch-funding.d.ts.map +1 -0
  70. package/dist/gasless/get-gasless-batch-funding/get-gasless-batch-funding.js +96 -0
  71. package/dist/gasless/get-gasless-batch-funding/get-gasless-batch-funding.js.map +1 -0
  72. package/dist/gasless/get-gasless-batch-funding/index.d.ts +4 -0
  73. package/dist/gasless/get-gasless-batch-funding/index.d.ts.map +1 -0
  74. package/dist/gasless/get-gasless-batch-funding/query.d.ts +31 -0
  75. package/dist/gasless/get-gasless-batch-funding/query.d.ts.map +1 -0
  76. package/dist/gasless/get-gasless-batch-funding/query.js +22 -0
  77. package/dist/gasless/get-gasless-batch-funding/query.js.map +1 -0
  78. package/dist/gasless/get-gasless-batch-funding/types.d.ts +80 -0
  79. package/dist/gasless/get-gasless-batch-funding/types.d.ts.map +1 -0
  80. package/dist/gasless/get-gasless-margin-funding/get-gasless-margin-funding.d.ts +33 -0
  81. package/dist/gasless/get-gasless-margin-funding/get-gasless-margin-funding.d.ts.map +1 -0
  82. package/dist/gasless/get-gasless-margin-funding/get-gasless-margin-funding.js +31 -0
  83. package/dist/gasless/get-gasless-margin-funding/get-gasless-margin-funding.js.map +1 -0
  84. package/dist/gasless/get-gasless-margin-funding/index.d.ts +4 -0
  85. package/dist/gasless/get-gasless-margin-funding/index.d.ts.map +1 -0
  86. package/dist/gasless/get-gasless-margin-funding/query.d.ts +31 -0
  87. package/dist/gasless/get-gasless-margin-funding/query.d.ts.map +1 -0
  88. package/dist/gasless/get-gasless-margin-funding/query.js +22 -0
  89. package/dist/gasless/get-gasless-margin-funding/query.js.map +1 -0
  90. package/dist/gasless/get-gasless-margin-funding/types.d.ts +27 -0
  91. package/dist/gasless/get-gasless-margin-funding/types.d.ts.map +1 -0
  92. package/dist/gasless/index.d.ts +2 -0
  93. package/dist/gasless/index.d.ts.map +1 -1
  94. package/dist/index.d.ts +2 -2
  95. package/dist/index.d.ts.map +1 -1
  96. package/dist/index.js +505 -498
  97. package/dist/pools/listing-config/to-listing-config.d.ts +10 -3
  98. package/dist/pools/listing-config/to-listing-config.d.ts.map +1 -1
  99. package/dist/pools/listing-config/to-listing-config.js +5 -1
  100. package/dist/pools/listing-config/to-listing-config.js.map +1 -1
  101. package/dist/pools/types/generated/listing-backend.d.ts +266 -1
  102. package/dist/pools/types/generated/listing-backend.d.ts.map +1 -1
  103. package/dist/pools/types/generated/listing-backend.js.map +1 -1
  104. package/dist/pools/types.d.ts +7 -0
  105. package/dist/pools/types.d.ts.map +1 -1
  106. package/dist/pools/types.js.map +1 -1
  107. package/dist/price-service/enigma/ohlcv/fetch-enigma-ohlcv.d.ts +39 -0
  108. package/dist/price-service/enigma/ohlcv/fetch-enigma-ohlcv.d.ts.map +1 -0
  109. package/dist/price-service/enigma/ohlcv/fetch-enigma-ohlcv.js +43 -0
  110. package/dist/price-service/enigma/ohlcv/fetch-enigma-ohlcv.js.map +1 -0
  111. package/dist/price-service/enigma/ohlcv/generated/enigma-price-service-ohlcv.d.ts +67 -0
  112. package/dist/price-service/enigma/ohlcv/generated/enigma-price-service-ohlcv.d.ts.map +1 -0
  113. package/dist/price-service/enigma/ohlcv/generated/enigma-price-service-ohlcv.js +15 -0
  114. package/dist/price-service/enigma/ohlcv/generated/enigma-price-service-ohlcv.js.map +1 -0
  115. package/dist/price-service/enigma/ohlcv/parse-enigma-ohlcv.d.ts +21 -0
  116. package/dist/price-service/enigma/ohlcv/parse-enigma-ohlcv.d.ts.map +1 -0
  117. package/dist/price-service/enigma/ohlcv/parse-enigma-ohlcv.js +36 -0
  118. package/dist/price-service/enigma/ohlcv/parse-enigma-ohlcv.js.map +1 -0
  119. package/dist/price-service/enigma/symbols-info/get-enigma-price-service-symbols-info.d.ts +2 -0
  120. package/dist/price-service/enigma/symbols-info/get-enigma-price-service-symbols-info.d.ts.map +1 -1
  121. package/dist/price-service/enigma/symbols-info/get-enigma-price-service-symbols-info.js +12 -8
  122. package/dist/price-service/enigma/symbols-info/get-enigma-price-service-symbols-info.js.map +1 -1
  123. package/package.json +1 -1
@@ -0,0 +1,104 @@
1
+ import { SymmError as e } from "../../../shared/errors/symm-error.js";
2
+ import { watchEnigmaPrices as t } from "../../../websocket/prices/watch-enigma-prices.js";
3
+ import { floorLowcapCandleTime as n, shiftLowcapCandleTime as r } from "./lowcap-candle-time.js";
4
+ //#region src/candles/sources/lowcap/watch-lowcap-candles.ts
5
+ function i(e, t) {
6
+ return e?.time === t?.time && e?.open === t?.open && e?.high === t?.high && e?.low === t?.low && e?.close === t?.close && e?.volume === t?.volume;
7
+ }
8
+ function a(a, o) {
9
+ let { marketName: s, resolution: c, onCandle: l, onReset: u, onError: d, refreshIntervalMs: f } = o, p = !0, m = !1, h, g, _ = -Infinity, v = -Infinity, y = -Infinity, b = /* @__PURE__ */ new Map(), x, S = !1, C = [], w = [], T, E, D = Date.now();
10
+ function O(t) {
11
+ p && d?.(t instanceof e ? t : new e("api", "LOWCAP_CANDLE_STREAM_ERROR", t instanceof Error ? t.message : String(t)));
12
+ }
13
+ function k(e, t = !1) {
14
+ if (!p || e.time < y || !o.includeFlat && x !== void 0 && e.volume === 0 && [
15
+ e.open,
16
+ e.high,
17
+ e.low,
18
+ e.close
19
+ ].every((e) => e === x)) return;
20
+ y = e.time, b.set(e.time, { ...e });
21
+ let n = b.keys().next().value;
22
+ b.size > 2 && n !== void 0 && b.delete(n), l({ ...e }, { closed: t });
23
+ }
24
+ function A(e) {
25
+ if (e.name !== s || e.address && e.address !== h) return;
26
+ let t = Number(e.markPrice), r = e.time;
27
+ if (!Number.isFinite(t) || t <= 0 || r === void 0 || !Number.isSafeInteger(r) || r < _) return;
28
+ let i = n(r, c);
29
+ g && i < g.time || (_ = r, !g || i > g.time ? (g && (k(g, !0), x = g.close), g = {
30
+ time: i,
31
+ open: t,
32
+ high: t,
33
+ low: t,
34
+ close: t,
35
+ volume: 0
36
+ }) : g = {
37
+ ...g,
38
+ high: Math.max(g.high, t),
39
+ low: Math.min(g.low, t),
40
+ close: t
41
+ }, k(g));
42
+ }
43
+ async function j() {
44
+ if (!p || T) return;
45
+ let e = new AbortController();
46
+ T = e;
47
+ let t = v;
48
+ C = [];
49
+ try {
50
+ if (h ??= await o.resolveAddress(e.signal), !p || e.signal.aborted) return;
51
+ let a = Date.now(), s = r(n(a, c), c, -1), l = await o.getHistory(h, {
52
+ from: s,
53
+ to: a + 1,
54
+ signal: e.signal
55
+ });
56
+ if (!p || e.signal.aborted) return;
57
+ let d = l.candles, f = w.some((e) => e.time === y && e.time >= s) && !d.some((e) => e.time === y), m = [...new Set([...w, ...d].map((e) => e.time))].filter((e) => e >= s && e < y && !i(b.get(e) ?? w.find((t) => t.time === e), d.find((t) => t.time === e)));
58
+ f && m.push(y), S && a - D >= 36e5 ? (D = a, u?.()) : S && m.length > 0 && u?.({
59
+ from: Math.min(...m),
60
+ to: r(Math.max(...m), c, 1)
61
+ }), w = d;
62
+ for (let e of b.keys()) {
63
+ if (e < s || e >= y) continue;
64
+ let t = d.find((t) => t.time === e);
65
+ t ? b.set(e, t) : b.delete(e);
66
+ }
67
+ f && (g = void 0);
68
+ let T = d.at(-1);
69
+ T && (!g || T.time >= g.time) && (g && T.time > g.time && k(d.find((e) => e.time === g?.time) ?? g, !0), g = { ...T }, x = d.at(-2)?.close, k(g, r(g.time, c, 1) <= v)), S = !0;
70
+ let E = C;
71
+ C = [], _ = Math.max(t, T?.time ?? -Infinity);
72
+ for (let e of E) e.time !== void 0 && e.time >= t && A(e);
73
+ } catch (t) {
74
+ e.signal.aborted || (S && (C = []), O(t));
75
+ } finally {
76
+ T === e && (T = void 0, p && (E = setTimeout(() => {
77
+ j();
78
+ }, f)));
79
+ }
80
+ }
81
+ let M = t(a, {
82
+ chainId: o.chainId,
83
+ solverId: o.solverId,
84
+ names: [s],
85
+ onPrices(e) {
86
+ if (p) for (let t of e) {
87
+ if (t.name !== s || h && t.address && t.address !== h) continue;
88
+ let e = Number(t.markPrice);
89
+ t.time === void 0 || !Number.isSafeInteger(t.time) || !Number.isFinite(e) || e <= 0 || t.time < v || (v = t.time, (T || !S) && (C.length >= 1e3 && (C = [], S = !1, g = void 0, T?.abort(), T = void 0, clearTimeout(E), u?.(), j()), C.push(t)), S && A(t));
90
+ }
91
+ },
92
+ onStatusChange(e) {
93
+ p && (o.onStatusChange?.(e), e === "open" && (m && (T?.abort(), T = void 0, clearTimeout(E), C = [], S = !1, g = void 0, w = [], b.clear(), _ = -Infinity, v = -Infinity, u?.(), j()), m = !0));
94
+ },
95
+ onError: O
96
+ });
97
+ return j(), () => {
98
+ p = !1, clearTimeout(E), T?.abort(), C = [], M();
99
+ };
100
+ }
101
+ //#endregion
102
+ export { a as watchLowcapCandles };
103
+
104
+ //# sourceMappingURL=watch-lowcap-candles.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"watch-lowcap-candles.js","names":[],"sources":["../../../../src/candles/sources/lowcap/watch-lowcap-candles.ts"],"sourcesContent":["import type { SolverId } from \"../../../core/chains/types\";\nimport type { Config } from \"../../../core/config\";\nimport { SymmError } from \"../../../shared/errors/symm-error\";\nimport type { EnigmaPriceTick } from \"../../../websocket/prices/types\";\nimport { watchEnigmaPrices } from \"../../../websocket/prices/watch-enigma-prices\";\nimport type { Candle, GetCandlesReturnType, WatchCandlesParameters } from \"../../types\";\nimport { floorLowcapCandleTime, shiftLowcapCandleTime } from \"./lowcap-candle-time\";\n\ninterface Parameters extends WatchCandlesParameters {\n chainId?: number;\n solverId?: SolverId;\n includeFlat: boolean;\n refreshIntervalMs: number;\n resolveAddress: (signal: AbortSignal) => Promise<string>;\n getHistory: (\n address: string,\n range: { from: number; to: number; signal: AbortSignal },\n ) => Promise<GetCandlesReturnType>;\n}\n\nfunction equalCandle(a: Candle | undefined, b: Candle | undefined): boolean {\n return (\n a?.time === b?.time &&\n a?.open === b?.open &&\n a?.high === b?.high &&\n a?.low === b?.low &&\n a?.close === b?.close &&\n a?.volume === b?.volume\n );\n}\n\n/** Seed from OHLCV, apply timestamped price ticks, and reconcile without caching final history. @internal */\nexport function watchLowcapCandles(config: Config, parameters: Parameters): () => void {\n const { marketName, resolution, onCandle, onReset, onError, refreshIntervalMs } = parameters;\n let active = true;\n let opened = false;\n let address: string | undefined;\n let current: Candle | undefined;\n let lastTickTime = -Infinity;\n let lastReceivedTickTime = -Infinity;\n let lastEmittedTime = -Infinity;\n const emittedHistory = new Map<number, Candle>();\n let previousClose: number | undefined;\n let seeded = false;\n let pending: EnigmaPriceTick[] = [];\n let previousHistory: Candle[] = [];\n let controller: AbortController | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let lastReset = Date.now();\n\n function report(error: unknown) {\n if (!active) return;\n onError?.(\n error instanceof SymmError\n ? error\n : new SymmError(\"api\", \"LOWCAP_CANDLE_STREAM_ERROR\", error instanceof Error ? error.message : String(error)),\n );\n }\n\n function emit(candle: Candle, closed = false) {\n if (!active || candle.time < lastEmittedTime) return;\n if (\n !parameters.includeFlat &&\n previousClose !== undefined &&\n candle.volume === 0 &&\n [candle.open, candle.high, candle.low, candle.close].every((price) => price === previousClose)\n )\n return;\n lastEmittedTime = candle.time;\n emittedHistory.set(candle.time, { ...candle });\n const oldest = emittedHistory.keys().next().value;\n if (emittedHistory.size > 2 && oldest !== undefined) emittedHistory.delete(oldest);\n onCandle({ ...candle }, { closed });\n }\n\n function applyTick(tick: EnigmaPriceTick) {\n if (tick.name !== marketName || (tick.address && tick.address !== address)) return;\n const price = Number(tick.markPrice);\n const time = tick.time;\n if (\n !Number.isFinite(price) ||\n price <= 0 ||\n time === undefined ||\n !Number.isSafeInteger(time) ||\n time < lastTickTime\n )\n return;\n const start = floorLowcapCandleTime(time, resolution);\n if (current && start < current.time) return;\n lastTickTime = time;\n if (!current || start > current.time) {\n if (current) {\n emit(current, true);\n previousClose = current.close;\n }\n current = { time: start, open: price, high: price, low: price, close: price, volume: 0 };\n } else {\n current = { ...current, high: Math.max(current.high, price), low: Math.min(current.low, price), close: price };\n }\n emit(current);\n }\n\n async function refresh() {\n if (!active || controller) return;\n const request = new AbortController();\n controller = request;\n const tickTimeAtStart = lastReceivedTickTime;\n pending = [];\n try {\n address ??= await parameters.resolveAddress(request.signal);\n if (!active || request.signal.aborted) return;\n const now = Date.now();\n const from = shiftLowcapCandleTime(floorLowcapCandleTime(now, resolution), resolution, -1);\n const result = await parameters.getHistory(address, { from, to: now + 1, signal: request.signal });\n if (!active || request.signal.aborted) return;\n const history = result.candles;\n const removedCurrent =\n previousHistory.some((bar) => bar.time === lastEmittedTime && bar.time >= from) &&\n !history.some((bar) => bar.time === lastEmittedTime);\n const times = new Set([...previousHistory, ...history].map((candle) => candle.time));\n const corrected = [...times].filter(\n (time) =>\n time >= from &&\n time < lastEmittedTime &&\n !equalCandle(\n emittedHistory.get(time) ?? previousHistory.find((bar) => bar.time === time),\n history.find((bar) => bar.time === time),\n ),\n );\n if (removedCurrent) corrected.push(lastEmittedTime);\n /** Unknown historical backfills still require a full hourly reconciliation. */\n if (seeded && now - lastReset >= 3_600_000) {\n lastReset = now;\n onReset?.();\n } else if (seeded && corrected.length > 0) {\n onReset?.({\n from: Math.min(...corrected),\n to: shiftLowcapCandleTime(Math.max(...corrected), resolution, 1),\n });\n }\n previousHistory = history;\n /** A reset replaces these snapshots; do not report the same correction again. */\n for (const time of emittedHistory.keys()) {\n if (time < from || time >= lastEmittedTime) continue;\n const snapshot = history.find((bar) => bar.time === time);\n if (snapshot) emittedHistory.set(time, snapshot);\n else emittedHistory.delete(time);\n }\n if (removedCurrent) current = undefined;\n const latest = history.at(-1);\n if (latest && (!current || latest.time >= current.time)) {\n if (current && latest.time > current.time) {\n emit(history.find((bar) => bar.time === current?.time) ?? current, true);\n }\n current = { ...latest };\n previousClose = history.at(-2)?.close;\n emit(current, shiftLowcapCandleTime(current.time, resolution, 1) <= lastReceivedTickTime);\n }\n seeded = true;\n const buffered = pending;\n pending = [];\n /** Compare service timestamps with other service timestamps, never the client's clock. */\n lastTickTime = Math.max(tickTimeAtStart, latest?.time ?? -Infinity);\n for (const tick of buffered) {\n if (tick.time !== undefined && tick.time >= tickTimeAtStart) applyTick(tick);\n }\n } catch (error) {\n if (!request.signal.aborted) {\n if (seeded) pending = [];\n report(error);\n }\n } finally {\n if (controller === request) {\n controller = undefined;\n if (active)\n timer = setTimeout(() => {\n void refresh();\n }, refreshIntervalMs);\n }\n }\n }\n\n const unwatch = watchEnigmaPrices(config, {\n chainId: parameters.chainId,\n solverId: parameters.solverId,\n names: [marketName],\n onPrices(ticks) {\n if (!active) return;\n for (const tick of ticks) {\n if (tick.name !== marketName || (address && tick.address && tick.address !== address)) continue;\n const price = Number(tick.markPrice);\n if (\n tick.time === undefined ||\n !Number.isSafeInteger(tick.time) ||\n !Number.isFinite(price) ||\n price <= 0 ||\n tick.time < lastReceivedTickTime\n )\n continue;\n lastReceivedTickTime = tick.time;\n if (controller || !seeded) {\n // Bounded buffering while HTTP is in flight. If it overflows, reseed\n // from HTTP rather than constructing an OHLC bar from incomplete ticks.\n if (pending.length >= 1_000) {\n pending = [];\n seeded = false;\n current = undefined;\n controller?.abort();\n controller = undefined;\n clearTimeout(timer);\n onReset?.();\n void refresh();\n }\n pending.push(tick);\n }\n if (seeded) applyTick(tick);\n }\n },\n onStatusChange(status) {\n if (!active) return;\n parameters.onStatusChange?.(status);\n if (status === \"open\") {\n if (opened) {\n controller?.abort();\n controller = undefined;\n clearTimeout(timer);\n pending = [];\n seeded = false;\n current = undefined;\n previousHistory = [];\n emittedHistory.clear();\n lastTickTime = -Infinity;\n lastReceivedTickTime = -Infinity;\n onReset?.();\n void refresh();\n }\n opened = true;\n }\n },\n onError: report,\n });\n void refresh();\n\n return () => {\n active = false;\n clearTimeout(timer);\n controller?.abort();\n pending = [];\n unwatch();\n };\n}\n"],"mappings":";;;;AAoBA,SAAS,EAAY,GAAuB,GAAgC;CAC1E,OACE,GAAG,SAAS,GAAG,QACf,GAAG,SAAS,GAAG,QACf,GAAG,SAAS,GAAG,QACf,GAAG,QAAQ,GAAG,OACd,GAAG,UAAU,GAAG,SAChB,GAAG,WAAW,GAAG;AAErB;AAGA,SAAgB,EAAmB,GAAgB,GAAoC;CACrF,IAAM,EAAE,eAAY,eAAY,aAAU,YAAS,YAAS,yBAAsB,GAC9E,IAAS,IACT,IAAS,IACT,GACA,GACA,IAAe,WACf,IAAuB,WACvB,IAAkB,WAChB,oBAAiB,IAAI,IAAoB,GAC3C,GACA,IAAS,IACT,IAA6B,CAAC,GAC9B,IAA4B,CAAC,GAC7B,GACA,GACA,IAAY,KAAK,IAAI;CAEzB,SAAS,EAAO,GAAgB;EACzB,KACL,IACE,aAAiB,IACb,IACA,IAAI,EAAU,OAAO,8BAA8B,aAAiB,QAAQ,EAAM,UAAU,OAAO,CAAK,CAAC,CAC/G;CACF;CAEA,SAAS,EAAK,GAAgB,IAAS,IAAO;EAE5C,IADI,CAAC,KAAU,EAAO,OAAO,KAE3B,CAAC,EAAW,eACZ,MAAkB,KAAA,KAClB,EAAO,WAAW,KAClB;GAAC,EAAO;GAAM,EAAO;GAAM,EAAO;GAAK,EAAO;EAAK,EAAE,OAAO,MAAU,MAAU,CAAa,GAE7F;EAEF,AADA,IAAkB,EAAO,MACzB,EAAe,IAAI,EAAO,MAAM,EAAE,GAAG,EAAO,CAAC;EAC7C,IA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AAA,GACV,IAAkB,CAAC,GACnB,EAAe,MAAM,GACrB,IAAe,WACf,IAAuB,WACvB,IAAU,GACV,EAAa,IAEf,IAAS;EAEb;EACA,SAAS;CACX,CAAC;CAGD,OAFA,EAAa,SAEA;EAKX,AAJA,IAAS,IACT,aAAa,CAAK,GAClB,GAAY,MAAM,GAClB,IAAU,CAAC,GACX,EAAQ;CACV;AACF"}
@@ -9,7 +9,7 @@ import { SocketStatus } from '../websocket/socket/index.js';
9
9
  * the subset it can actually serve via {@link CandleSource.supportedResolutions}
10
10
  * — no venue supports all of them.
11
11
  */
12
- export type CandleResolution = "1s" | "10s" | "1m" | "3m" | "5m" | "15m" | "30m" | "1h" | "2h" | "4h" | "6h" | "8h" | "12h" | "1d" | "3d" | "1w" | "1M";
12
+ export type CandleResolution = "1s" | "10s" | "1m" | "3m" | "5m" | "10m" | "15m" | "30m" | "1h" | "2h" | "4h" | "6h" | "8h" | "12h" | "1d" | "3d" | "1w" | "1M";
13
13
  /**
14
14
  * What the prices in a candle series actually represent.
15
15
  *
@@ -20,8 +20,9 @@ export type CandleResolution = "1s" | "10s" | "1m" | "3m" | "5m" | "15m" | "30m"
20
20
  * - `reference-exchange` — mark price of a third-party perp venue (e.g. Binance USD-M).
21
21
  * - `dex-pool` — spot price of an on-chain liquidity pool, USD-denominated.
22
22
  * - `solver-mark` — the SYMMIO solver's own mark price, the basis execution settles against.
23
+ * - `price-service` — the configured price service's OHLCV series and provisional live prices.
23
24
  */
24
- export type CandlePriceBasis = "reference-exchange" | "dex-pool" | "solver-mark";
25
+ export type CandlePriceBasis = "reference-exchange" | "dex-pool" | "solver-mark" | "price-service";
25
26
  /**
26
27
  * A single OHLCV bar.
27
28
  *
@@ -42,8 +43,10 @@ export interface Candle {
42
43
  /** Closing price — the latest price while the bar is still in progress. */
43
44
  close: number;
44
45
  /**
45
- * Base-asset volume over the bar. `0` when the source cannot report volume,
46
- * which is the case for any source that folds a price-tick stream into bars.
46
+ * Volume over the bar, in the unit reported by {@link CandleSymbol.volumeUnit}
47
+ * and {@link CandleSymbol.volumeCurrency}. Sources may report base-asset or
48
+ * quote-currency volume (for example USD). `0` can mean no traded volume or
49
+ * no volume data; it does not identify the unit.
47
50
  */
48
51
  volume: number;
49
52
  }
@@ -62,6 +65,10 @@ export interface CandleSymbol {
62
65
  pricePrecision: number;
63
66
  /** Decimal places volume should be rendered at. */
64
67
  volumePrecision: number;
68
+ /** Whether volume measures the base asset or quote currency. Absent means unspecified. */
69
+ volumeUnit?: "base" | "quote";
70
+ /** Currency of the volume values (e.g. `"BTC"` or `"USD"`), when known. */
71
+ volumeCurrency?: string;
65
72
  }
66
73
  /**
67
74
  * Parameters for {@link CandleSource.getCandles}.
@@ -90,9 +97,11 @@ export interface GetCandlesReturnType {
90
97
  /** Bars in ascending time order, de-duplicated and clipped to the requested range. */
91
98
  candles: Candle[];
92
99
  /**
93
- * `true` when the source has nothing at or before `from` — typically because
94
- * the request predates the instrument's listing. A chart paging backwards
95
- * should stop when it sees this instead of issuing requests that return empty.
100
+ * `true` when the source confirms there is no earlier history to page into.
101
+ * A chart paging backwards should stop when it sees this. The result can
102
+ * still contain candles, including the instrument's earliest available bar.
103
+ * `false` also covers unknown exhaustion when a provider supplies no boundary
104
+ * metadata. An empty window alone is not proof that older history is absent.
96
105
  */
97
106
  noMoreData: boolean;
98
107
  }
@@ -101,11 +110,18 @@ export interface GetCandlesReturnType {
101
110
  */
102
111
  export interface CandleUpdateMeta {
103
112
  /**
104
- * `true` when this bar has finalized and the next update starts a new bar.
105
- * `false` while it is still forming.
113
+ * `true` when the bar's interval has ended; `false` while it is forming.
114
+ * A provider may still correct a completed bar later.
106
115
  */
107
116
  closed: boolean;
108
117
  }
118
+ /** A candle-start range in Unix milliseconds, inclusive at `from` and exclusive at `to`. */
119
+ export interface CandleHistoryRange {
120
+ /** Inclusive start of the requested or corrected window. */
121
+ from: number;
122
+ /** Exclusive end of the requested or corrected window. */
123
+ to: number;
124
+ }
109
125
  /**
110
126
  * Parameters for {@link CandleSource.watchCandles}.
111
127
  */
@@ -120,11 +136,12 @@ export interface WatchCandlesParameters {
120
136
  */
121
137
  onCandle: (candle: Candle, meta: CandleUpdateMeta) => void;
122
138
  /**
123
- * Called after a reconnect, when bars may have been missed while the socket
124
- * was down. A chart should drop its cached bars and refetch history rather
125
- * than splice a live bar onto a stale series.
139
+ * Called after a reconnect or historical correction. When supplied, `range`
140
+ * identifies corrected candle starts; refresh loaded windows intersecting it.
141
+ * Without a range, refresh all retained history. Handlers may ignore the range
142
+ * and perform a full reset, including adapters that cannot refresh a subset.
126
143
  */
127
- onReset?: () => void;
144
+ onReset?: (range?: CandleHistoryRange) => void;
128
145
  /** Called whenever the underlying connection status changes. */
129
146
  onStatusChange?: (status: SocketStatus) => void;
130
147
  /** Called on a transport or parse error; does not stop the subscription. */
@@ -139,9 +156,8 @@ export interface WatchCandlesParameters {
139
156
  * (`toTradingViewDatafeed`) and framework hooks (`useCandles`) are written
140
157
  * against this interface, never against a specific venue.
141
158
  *
142
- * Unlike most SDK actions, a source is **not** derived from {@link Config}: a
143
- * reference exchange is not a SYMMIO chain deployment, and which venue to chart
144
- * is the consumer's choice. Construct one and pass it in explicitly.
159
+ * Construct a source explicitly. Reference exchanges have their own endpoints;
160
+ * deployment-specific sources can resolve their endpoints from {@link Config}.
145
161
  *
146
162
  * @example
147
163
  * ```ts
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/candles/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gDAAgD,CAAC;AAC9E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD;;;;;;;GAOG;AACH,MAAM,MAAM,gBAAgB,GACxB,IAAI,GACJ,KAAK,GACL,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,KAAK,GACL,KAAK,GAC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MAAM,WAAW,YAAY;IAC3B,oFAAoF;IACpF,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,kDAAkD;IAClD,QAAQ,CAAC,UAAU,EAAE,gBAAgB,CAAC;IACtC,yCAAyC;IACzC,QAAQ,CAAC,oBAAoB,EAAE,SAAS,gBAAgB,EAAE,CAAC;IAC3D;;;;OAIG;IACH,QAAQ,CAAC,oBAAoB,EAAE,MAAM,CAAC;IACtC;;;;;OAKG;IACH,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,SAAS,CAAC,CAAC;IACjE;;;;OAIG;IACH,UAAU,CAAC,UAAU,EAAE,oBAAoB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAC5E;;;;;;OAMG;IACH,YAAY,CAAC,CAAC,UAAU,EAAE,sBAAsB,GAAG,OAAO,CAAC;CAC5D"}
@@ -0,0 +1,20 @@
1
+ import { Address } from 'viem';
2
+ import { GaslessBatchCall } from '../batch/calls.js';
3
+ /**
4
+ * The operational-fee allowance the batch itself sets for `charger`, keyed by
5
+ * lowercase payer, or nothing for a payer the batch does not approve.
6
+ *
7
+ * Every relayed call runs as the batch `account`, so a core `approveOperationalFee`
8
+ * or `approveOperationalFeeWithMultiplier` in the batch sets that account's
9
+ * allowance. The contract stores the named amount (`LibOperationalFee.setAllowance`)
10
+ * and fees are collected after every call has run, so the last approval wins. A
11
+ * reduction the contract would delay is taken as immediate, which can only
12
+ * under-state the allowance. GaslessWallet calls run as the wallet, and calls
13
+ * wrapped in `executeTimelockOp` are not decoded, so neither counts.
14
+ * `approveOperationalFeeWithMultiplier` may also change the fee multiplier;
15
+ * the quoted fees were priced before the batch, so that change is not reflected.
16
+ *
17
+ * @internal
18
+ */
19
+ export declare function batchFeeApprovals(account: Address, calls: readonly GaslessBatchCall[], charger: Address): ReadonlyMap<Address, bigint>;
20
+ //# sourceMappingURL=batch-fee-approvals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch-fee-approvals.d.ts","sourceRoot":"","sources":["../../../src/gasless/get-gasless-batch-funding/batch-fee-approvals.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsD,KAAK,OAAO,EAAY,MAAM,MAAM,CAAC;AAElG,OAAO,EAIL,KAAK,gBAAgB,EACtB,MAAM,gBAAgB,CAAC;AAQxB;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,OAAO,EAChB,KAAK,EAAE,SAAS,gBAAgB,EAAE,EAClC,OAAO,EAAE,OAAO,GACf,WAAW,CAAC,OAAO,EAAE,MAAM,CAAC,CAkB9B"}
@@ -0,0 +1,29 @@
1
+ import { symmioAbi as e } from "../../symmio-contracts/abi/v0.8.6/symmio.js";
2
+ import { gaslessBatchCallData as t, gaslessCallDataSelector as n, isGaslessBatchWalletExecute as r } from "../batch/calls.js";
3
+ import { decodeFunctionData as i, getAbiItem as a, toFunctionSelector as o } from "viem";
4
+ //#region src/gasless/get-gasless-batch-funding/batch-fee-approvals.ts
5
+ var s = new Set(["approveOperationalFee", "approveOperationalFeeWithMultiplier"].map((t) => o(a({
6
+ abi: e,
7
+ name: t
8
+ }))));
9
+ function c(a, o, c) {
10
+ let l = /* @__PURE__ */ new Map(), u = c.toLowerCase();
11
+ for (let c of o) {
12
+ if (r(c)) continue;
13
+ let o = t(c);
14
+ if (!s.has(n(o))) continue;
15
+ let { args: d } = i({
16
+ abi: e,
17
+ data: o
18
+ }), [f, p] = d;
19
+ f.forEach((e, t) => {
20
+ let n = p[t];
21
+ n !== void 0 && e.toLowerCase() === u && l.set(a.toLowerCase(), n);
22
+ });
23
+ }
24
+ return l;
25
+ }
26
+ //#endregion
27
+ export { c as batchFeeApprovals };
28
+
29
+ //# sourceMappingURL=batch-fee-approvals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch-fee-approvals.js","names":[],"sources":["../../../src/gasless/get-gasless-batch-funding/batch-fee-approvals.ts"],"sourcesContent":["import { decodeFunctionData, getAbiItem, toFunctionSelector, type Address, type Hex } from \"viem\";\nimport { symmioAbi } from \"../../symmio-contracts/abi/v0.8.6/symmio\";\nimport {\n gaslessBatchCallData,\n gaslessCallDataSelector,\n isGaslessBatchWalletExecute,\n type GaslessBatchCall,\n} from \"../batch/calls\";\n\nconst APPROVE_SELECTORS: ReadonlySet<Hex> = new Set(\n ([\"approveOperationalFee\", \"approveOperationalFeeWithMultiplier\"] as const).map((name) =>\n toFunctionSelector(getAbiItem({ abi: symmioAbi, name })),\n ),\n);\n\n/**\n * The operational-fee allowance the batch itself sets for `charger`, keyed by\n * lowercase payer, or nothing for a payer the batch does not approve.\n *\n * Every relayed call runs as the batch `account`, so a core `approveOperationalFee`\n * or `approveOperationalFeeWithMultiplier` in the batch sets that account's\n * allowance. The contract stores the named amount (`LibOperationalFee.setAllowance`)\n * and fees are collected after every call has run, so the last approval wins. A\n * reduction the contract would delay is taken as immediate, which can only\n * under-state the allowance. GaslessWallet calls run as the wallet, and calls\n * wrapped in `executeTimelockOp` are not decoded, so neither counts.\n * `approveOperationalFeeWithMultiplier` may also change the fee multiplier;\n * the quoted fees were priced before the batch, so that change is not reflected.\n *\n * @internal\n */\nexport function batchFeeApprovals(\n account: Address,\n calls: readonly GaslessBatchCall[],\n charger: Address,\n): ReadonlyMap<Address, bigint> {\n const approvals = new Map<Address, bigint>();\n // Compare lowercase, as payers are keyed: a checksum mismatch must not throw mid-check.\n const chargerKey = charger.toLowerCase();\n for (const call of calls) {\n if (isGaslessBatchWalletExecute(call)) continue;\n const data = gaslessBatchCallData(call);\n if (!APPROVE_SELECTORS.has(gaslessCallDataSelector(data))) continue;\n const { args } = decodeFunctionData({ abi: symmioAbi, data });\n const [chargers, amounts] = args as unknown as readonly [readonly Address[], readonly bigint[]];\n chargers.forEach((approved, index) => {\n const amount = amounts[index];\n if (amount !== undefined && approved.toLowerCase() === chargerKey) {\n approvals.set(account.toLowerCase() as Address, amount);\n }\n });\n }\n return approvals;\n}\n"],"mappings":";;;;AASA,IAAM,IAAsC,IAAI,IAC7C,CAAC,yBAAyB,qCAAqC,EAAY,KAAK,MAC/E,EAAmB,EAAW;CAAE,KAAK;CAAW;AAAK,CAAC,CAAC,CACzD,CACF;AAkBA,SAAgB,EACd,GACA,GACA,GAC8B;CAC9B,IAAM,oBAAY,IAAI,IAAqB,GAErC,IAAa,EAAQ,YAAY;CACvC,KAAK,IAAM,KAAQ,GAAO;EACxB,IAAI,EAA4B,CAAI,GAAG;EACvC,IAAM,IAAO,EAAqB,CAAI;EACtC,IAAI,CAAC,EAAkB,IAAI,EAAwB,CAAI,CAAC,GAAG;EAC3D,IAAM,EAAE,YAAS,EAAmB;GAAE,KAAK;GAAW;EAAK,CAAC,GACtD,CAAC,GAAU,KAAW;EAC5B,EAAS,SAAS,GAAU,MAAU;GACpC,IAAM,IAAS,EAAQ;GACvB,AAAI,MAAW,KAAA,KAAa,EAAS,YAAY,MAAM,KACrD,EAAU,IAAI,EAAQ,YAAY,GAAc,CAAM;EAE1D,CAAC;CACH;CACA,OAAO;AACT"}
@@ -0,0 +1,43 @@
1
+ import { Config } from '../../core/config/index.js';
2
+ import { GetGaslessBatchFundingParameters, GetGaslessBatchFundingReturnType } from './types.js';
3
+ /**
4
+ * Quote an exact batch and check whether every payer can be charged its fees.
5
+ *
6
+ * Fees are collected after operations, and the GaslessLayer charges a payer only
7
+ * when **both** its Core balance and its operational-fee allowance cover them. So
8
+ * each payer gets two checks and a `missing` list naming which one fails:
9
+ *
10
+ * - **Balance**: free plus allocated Core balance after the batch, against all
11
+ * quoted fees and native gas collateral. Supply known Core balance movements in
12
+ * `balanceChanges`; the action does not decode or simulate arbitrary calls.
13
+ * - **Allowance**: the payer's remaining allowance for the GaslessLayer, after
14
+ * any fee approval in the batch itself, against its operational and
15
+ * wallet-creation fees.
16
+ *
17
+ * Charges are grouped by their quoted payer, never pooled across accounts. All
18
+ * amounts are internal 18-decimal units. Every payer's balances and allowance use
19
+ * one fresh RPC block number; the fee quote is read separately and is not pinned
20
+ * to that snapshot.
21
+ *
22
+ * This is advisory: allowances, payer selection and balances can change before
23
+ * execution. It does not validate the operation's own spending/risk limits or
24
+ * guarantee relay acceptance. Use a fresh read after reconciling pending work
25
+ * and before a new submission; a cached preview is not a submission guard.
26
+ *
27
+ * @param config - SDK config; no wallet client is needed.
28
+ * @param parameters - Exact relay account/calls, chain and known balance movements.
29
+ * @returns The quote, overall `isCovered`, and per-payer balance and allowance coverage.
30
+ * @throws {SymmError} `GASLESS_FUNDING_SOURCE_UNSUPPORTED` for non-Core fee sources,
31
+ * or `GASLESS_FUNDING_QUOTE_INCONSISTENT` for inconsistent/negative quoted debits.
32
+ * @throws Quote errors, including `GASLESS_FREE_QUOTA_EXHAUSTED`, and balance- or allowance-read errors unchanged.
33
+ * @example
34
+ * ```ts
35
+ * const funding = await getGaslessBatchFunding(config, { account, calls });
36
+ * for (const payer of funding.payers) {
37
+ * if (payer.missing.includes("balance")) askForDeposit(payer.payer, payer.shortfall18);
38
+ * if (payer.missing.includes("allowance")) askForApproval(payer.payer, payer.allowanceShortfall18);
39
+ * }
40
+ * ```
41
+ */
42
+ export declare function getGaslessBatchFunding(config: Config, parameters: GetGaslessBatchFundingParameters): Promise<GetGaslessBatchFundingReturnType>;
43
+ //# sourceMappingURL=get-gasless-batch-funding.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-gasless-batch-funding.d.ts","sourceRoot":"","sources":["../../../src/gasless/get-gasless-batch-funding/get-gasless-batch-funding.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAOhD,OAAO,KAAK,EAGV,gCAAgC,EAChC,gCAAgC,EACjC,MAAM,SAAS,CAAC;AAMjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,wBAAsB,sBAAsB,CAC1C,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,gCAAgC,GAC3C,OAAO,CAAC,gCAAgC,CAAC,CAkG3C"}
@@ -0,0 +1,96 @@
1
+ import { symmioAbi as e } from "../../symmio-contracts/abi/v0.8.6/symmio.js";
2
+ import { SymmError as t } from "../../shared/errors/symm-error.js";
3
+ import { resolveGaslessService as n } from "../resolve-gasless.js";
4
+ import { GaslessFeeSource as r } from "../types.js";
5
+ import { getGaslessBatchFeeQuote as i } from "../get-gasless-batch-fee-quote/get-gasless-batch-fee-quote.js";
6
+ import { batchFeeApprovals as a } from "./batch-fee-approvals.js";
7
+ //#region src/gasless/get-gasless-batch-funding/get-gasless-batch-funding.ts
8
+ function o(e, t) {
9
+ return e > t ? e - t : 0n;
10
+ }
11
+ async function s(s, c) {
12
+ let { chainId: l, account: u, calls: d, balanceChanges: f = [] } = c, p = await i(s, {
13
+ chainId: l,
14
+ account: u,
15
+ calls: d
16
+ }), m = /* @__PURE__ */ new Map();
17
+ for (let e of p.payments) {
18
+ if (e.source !== r.SYMMIO_ACCOUNT) throw new t("validation", "GASLESS_FUNDING_SOURCE_UNSUPPORTED", "Funding projections require SYMMIO account fee sources.");
19
+ let n = [
20
+ e.operationalFee18,
21
+ e.depositFee18,
22
+ e.walletCreationFee18,
23
+ e.nativeTopUpFee18,
24
+ e.nativeGasCollateral18
25
+ ];
26
+ if (n.some((e) => e < 0n)) throw new t("validation", "GASLESS_FUNDING_QUOTE_INCONSISTENT", "Quoted fee debits must be nonnegative.");
27
+ let i = e.payer.toLowerCase(), a = m.get(i) ?? {
28
+ debit18: 0n,
29
+ allowanceDebit18: 0n
30
+ };
31
+ m.set(i, {
32
+ debit18: a.debit18 + n.reduce((e, t) => e + t, 0n),
33
+ allowanceDebit18: a.allowanceDebit18 + e.operationalFee18 + e.walletCreationFee18
34
+ });
35
+ }
36
+ if ([...m.values()].reduce((e, { debit18: t }) => e + t, 0n) !== p.totalDebit18) throw new t("validation", "GASLESS_FUNDING_QUOTE_INCONSISTENT", "Quoted payer debits do not match the total debit.");
37
+ let h = /* @__PURE__ */ new Map();
38
+ for (let e of f) {
39
+ let t = e.account.toLowerCase();
40
+ h.set(t, (h.get(t) ?? 0n) + e.delta18);
41
+ }
42
+ let g = [...m].filter(([, { debit18: e }]) => e > 0n);
43
+ if (g.length === 0) return {
44
+ quote: p,
45
+ hasSufficientBalance: !0,
46
+ hasSufficientAllowance: !0,
47
+ isCovered: !0,
48
+ payers: []
49
+ };
50
+ let { gaslessLayerAddress: _ } = n(s, { chainId: l }), v = a(u, d, _), { addresses: y } = s.getChainConfig(l), b = s.getClient({ chainId: l }), x = await b.getBlockNumber({ cacheTime: 0 }), S = {
51
+ address: y.symmioAddress,
52
+ abi: e,
53
+ blockNumber: x
54
+ }, C = await Promise.all(g.map(async ([e, { debit18: t, allowanceDebit18: n }]) => {
55
+ let [r, i, [a]] = await Promise.all([
56
+ b.readContract({
57
+ ...S,
58
+ functionName: "balanceOf",
59
+ args: [e]
60
+ }),
61
+ b.readContract({
62
+ ...S,
63
+ functionName: "balanceInfoOfPartyA",
64
+ args: [e]
65
+ }),
66
+ b.readContract({
67
+ ...S,
68
+ functionName: "getOperationalFeeAllowance",
69
+ args: [e, _]
70
+ })
71
+ ]), s = r + i[0], c = s + (h.get(e) ?? 0n), l = c > 0n ? c : 0n, u = o(t, l), d = v.get(e) ?? a, f = o(n, d), p = [];
72
+ return u > 0n && p.push("balance"), f > 0n && p.push("allowance"), {
73
+ payer: e,
74
+ debit18: t,
75
+ freeBalance18: r,
76
+ balanceBefore18: s,
77
+ projectedBalance18: l,
78
+ shortfall18: u,
79
+ allowanceDebit18: n,
80
+ allowance18: d,
81
+ allowanceShortfall18: f,
82
+ missing: p
83
+ };
84
+ })), w = C.every((e) => e.shortfall18 === 0n), T = C.every((e) => e.allowanceShortfall18 === 0n);
85
+ return {
86
+ quote: p,
87
+ hasSufficientBalance: w,
88
+ hasSufficientAllowance: T,
89
+ isCovered: w && T,
90
+ payers: C
91
+ };
92
+ }
93
+ //#endregion
94
+ export { s as getGaslessBatchFunding };
95
+
96
+ //# sourceMappingURL=get-gasless-batch-funding.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-gasless-batch-funding.js","names":[],"sources":["../../../src/gasless/get-gasless-batch-funding/get-gasless-batch-funding.ts"],"sourcesContent":["import type { Address } from \"viem\";\nimport type { Config } from \"../../core/config\";\nimport { SymmError } from \"../../shared/errors/symm-error\";\nimport { symmioAbi } from \"../../symmio-contracts/abi/v0.8.6/symmio\";\nimport { getGaslessBatchFeeQuote } from \"../get-gasless-batch-fee-quote\";\nimport { resolveGaslessService } from \"../resolve-gasless\";\nimport { GaslessFeeSource } from \"../types\";\nimport { batchFeeApprovals } from \"./batch-fee-approvals\";\nimport type {\n GaslessFundingShortage,\n GaslessPayerFunding,\n GetGaslessBatchFundingParameters,\n GetGaslessBatchFundingReturnType,\n} from \"./types\";\n\nfunction shortfall(needed: bigint, available: bigint): bigint {\n return needed > available ? needed - available : 0n;\n}\n\n/**\n * Quote an exact batch and check whether every payer can be charged its fees.\n *\n * Fees are collected after operations, and the GaslessLayer charges a payer only\n * when **both** its Core balance and its operational-fee allowance cover them. So\n * each payer gets two checks and a `missing` list naming which one fails:\n *\n * - **Balance**: free plus allocated Core balance after the batch, against all\n * quoted fees and native gas collateral. Supply known Core balance movements in\n * `balanceChanges`; the action does not decode or simulate arbitrary calls.\n * - **Allowance**: the payer's remaining allowance for the GaslessLayer, after\n * any fee approval in the batch itself, against its operational and\n * wallet-creation fees.\n *\n * Charges are grouped by their quoted payer, never pooled across accounts. All\n * amounts are internal 18-decimal units. Every payer's balances and allowance use\n * one fresh RPC block number; the fee quote is read separately and is not pinned\n * to that snapshot.\n *\n * This is advisory: allowances, payer selection and balances can change before\n * execution. It does not validate the operation's own spending/risk limits or\n * guarantee relay acceptance. Use a fresh read after reconciling pending work\n * and before a new submission; a cached preview is not a submission guard.\n *\n * @param config - SDK config; no wallet client is needed.\n * @param parameters - Exact relay account/calls, chain and known balance movements.\n * @returns The quote, overall `isCovered`, and per-payer balance and allowance coverage.\n * @throws {SymmError} `GASLESS_FUNDING_SOURCE_UNSUPPORTED` for non-Core fee sources,\n * or `GASLESS_FUNDING_QUOTE_INCONSISTENT` for inconsistent/negative quoted debits.\n * @throws Quote errors, including `GASLESS_FREE_QUOTA_EXHAUSTED`, and balance- or allowance-read errors unchanged.\n * @example\n * ```ts\n * const funding = await getGaslessBatchFunding(config, { account, calls });\n * for (const payer of funding.payers) {\n * if (payer.missing.includes(\"balance\")) askForDeposit(payer.payer, payer.shortfall18);\n * if (payer.missing.includes(\"allowance\")) askForApproval(payer.payer, payer.allowanceShortfall18);\n * }\n * ```\n */\nexport async function getGaslessBatchFunding(\n config: Config,\n parameters: GetGaslessBatchFundingParameters,\n): Promise<GetGaslessBatchFundingReturnType> {\n const { chainId, account, calls, balanceChanges = [] } = parameters;\n const quote = await getGaslessBatchFeeQuote(config, { chainId, account, calls });\n /** Per payer: everything it is charged, and the part charged against its allowance. */\n const due = new Map<Address, { debit18: bigint; allowanceDebit18: bigint }>();\n for (const payment of quote.payments) {\n if (payment.source !== GaslessFeeSource.SYMMIO_ACCOUNT) {\n throw new SymmError(\n \"validation\",\n \"GASLESS_FUNDING_SOURCE_UNSUPPORTED\",\n \"Funding projections require SYMMIO account fee sources.\",\n );\n }\n const components = [\n payment.operationalFee18,\n payment.depositFee18,\n payment.walletCreationFee18,\n payment.nativeTopUpFee18,\n payment.nativeGasCollateral18,\n ];\n if (components.some((amount) => amount < 0n)) {\n throw new SymmError(\"validation\", \"GASLESS_FUNDING_QUOTE_INCONSISTENT\", \"Quoted fee debits must be nonnegative.\");\n }\n const payer = payment.payer.toLowerCase() as Address;\n const totals = due.get(payer) ?? { debit18: 0n, allowanceDebit18: 0n };\n due.set(payer, {\n debit18: totals.debit18 + components.reduce((sum, amount) => sum + amount, 0n),\n // GaslessFeeQuoteLib charges these two through chargeOperationalFee, which spends the allowance.\n allowanceDebit18: totals.allowanceDebit18 + payment.operationalFee18 + payment.walletCreationFee18,\n });\n }\n if ([...due.values()].reduce((sum, { debit18 }) => sum + debit18, 0n) !== quote.totalDebit18) {\n throw new SymmError(\n \"validation\",\n \"GASLESS_FUNDING_QUOTE_INCONSISTENT\",\n \"Quoted payer debits do not match the total debit.\",\n );\n }\n const movements = new Map<Address, bigint>();\n for (const change of balanceChanges) {\n const payer = change.account.toLowerCase() as Address;\n movements.set(payer, (movements.get(payer) ?? 0n) + change.delta18);\n }\n const chargedPayers = [...due].filter(([, { debit18 }]) => debit18 > 0n);\n if (chargedPayers.length === 0) {\n return { quote, hasSufficientBalance: true, hasSufficientAllowance: true, isCovered: true, payers: [] };\n }\n\n const { gaslessLayerAddress } = resolveGaslessService(config, { chainId });\n const approvals = batchFeeApprovals(account, calls, gaslessLayerAddress);\n const { addresses } = config.getChainConfig(chainId);\n const client = config.getClient({ chainId });\n // quote.blockNumber can be an L1 estimate on Arbitrum, not the RPC's L2 height.\n const blockNumber = await client.getBlockNumber({ cacheTime: 0 });\n const readParameters = { address: addresses.symmioAddress, abi: symmioAbi, blockNumber };\n const payers = await Promise.all(\n chargedPayers.map(async ([payer, { debit18, allowanceDebit18 }]): Promise<GaslessPayerFunding> => {\n const [freeBalance18, info, [allowanceBefore18]] = await Promise.all([\n client.readContract({ ...readParameters, functionName: \"balanceOf\", args: [payer] }),\n client.readContract({ ...readParameters, functionName: \"balanceInfoOfPartyA\", args: [payer] }),\n client.readContract({\n ...readParameters,\n functionName: \"getOperationalFeeAllowance\",\n args: [payer, gaslessLayerAddress],\n }),\n ]);\n const balanceBefore18 = freeBalance18 + info[0];\n const projected = balanceBefore18 + (movements.get(payer) ?? 0n);\n const projectedBalance18 = projected > 0n ? projected : 0n;\n const shortfall18 = shortfall(debit18, projectedBalance18);\n const allowance18 = approvals.get(payer) ?? allowanceBefore18;\n const allowanceShortfall18 = shortfall(allowanceDebit18, allowance18);\n const missing: GaslessFundingShortage[] = [];\n if (shortfall18 > 0n) missing.push(\"balance\");\n if (allowanceShortfall18 > 0n) missing.push(\"allowance\");\n return {\n payer,\n debit18,\n freeBalance18,\n balanceBefore18,\n projectedBalance18,\n shortfall18,\n allowanceDebit18,\n allowance18,\n allowanceShortfall18,\n missing,\n };\n }),\n );\n const hasSufficientBalance = payers.every((payer) => payer.shortfall18 === 0n);\n const hasSufficientAllowance = payers.every((payer) => payer.allowanceShortfall18 === 0n);\n return {\n quote,\n hasSufficientBalance,\n hasSufficientAllowance,\n isCovered: hasSufficientBalance && hasSufficientAllowance,\n payers,\n };\n}\n"],"mappings":";;;;;;;AAeA,SAAS,EAAU,GAAgB,GAA2B;CAC5D,OAAO,IAAS,IAAY,IAAS,IAAY;AACnD;AAyCA,eAAsB,EACpB,GACA,GAC2C;CAC3C,IAAM,EAAE,YAAS,YAAS,UAAO,oBAAiB,CAAC,MAAM,GACnD,IAAQ,MAAM,EAAwB,GAAQ;EAAE;EAAS;EAAS;CAAM,CAAC,GAEzE,oBAAM,IAAI,IAA4D;CAC5E,KAAK,IAAM,KAAW,EAAM,UAAU;EACpC,IAAI,EAAQ,WAAW,EAAiB,gBACtC,MAAM,IAAI,EACR,cACA,sCACA,yDACF;EAEF,IAAM,IAAa;GACjB,EAAQ;GACR,EAAQ;GACR,EAAQ;GACR,EAAQ;GACR,EAAQ;EACV;EACA,IAAI,EAAW,MAAM,MAAW,IAAS,EAAE,GACzC,MAAM,IAAI,EAAU,cAAc,sCAAsC,wCAAwC;EAElH,IAAM,IAAQ,EAAQ,MAAM,YAAY,GAClC,IAAS,EAAI,IAAI,CAAK,KAAK;GAAE,SAAS;GAAI,kBAAkB;EAAG;EACrE,EAAI,IAAI,GAAO;GACb,SAAS,EAAO,UAAU,EAAW,QAAQ,GAAK,MAAW,IAAM,GAAQ,EAAE;GAE7E,kBAAkB,EAAO,mBAAmB,EAAQ,mBAAmB,EAAQ;EACjF,CAAC;CACH;CACA,IAAI,CAAC,GAAG,EAAI,OAAO,CAAC,EAAE,QAAQ,GAAK,EAAE,iBAAc,IAAM,GAAS,EAAE,MAAM,EAAM,cAC9E,MAAM,IAAI,EACR,cAC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AK,KAAK,GACtC,IAAuB,EAAU,GAAkB,CAAW,GAC9D,IAAoC,CAAC;EAG3C,OAFI,IAAc,MAAI,EAAQ,KAAK,SAAS,GACxC,IAAuB,MAAI,EAAQ,KAAK,WAAW,GAChD;GACL;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;CACF,CAAC,CACH,GACM,IAAuB,EAAO,OAAO,MAAU,EAAM,gBAAgB,EAAE,GACvE,IAAyB,EAAO,OAAO,MAAU,EAAM,yBAAyB,EAAE;CACxF,OAAO;EACL;EACA;EACA;EACA,WAAW,KAAwB;EACnC;CACF;AACF"}
@@ -0,0 +1,4 @@
1
+ export * from './get-gasless-batch-funding.js';
2
+ export * from './query.js';
3
+ export * from './types.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/gasless/get-gasless-batch-funding/index.ts"],"names":[],"mappings":"AAAA,cAAc,6BAA6B,CAAC;AAC5C,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC"}
@@ -0,0 +1,31 @@
1
+ import { Config } from '../../core/config/index.js';
2
+ import { Compute, ConfigKeyParameter, ExactPartial } from '../../shared/types/properties.js';
3
+ import { QueryParameter, SymmioQueryOptions } from '../../shared/types/query.js';
4
+ import { GetGaslessBatchFundingParameters, GetGaslessBatchFundingReturnType } from './types.js';
5
+ /** Data resolved by the batch-funding query. */
6
+ export type GetGaslessBatchFundingData = GetGaslessBatchFundingReturnType;
7
+ /**
8
+ * Key a funding preview by config, chain, account, encoded calls and balance movements.
9
+ * @param options - Partial funding inputs and optional config identity.
10
+ * @returns Stable query key; unencodable calls are deferred to the query function.
11
+ */
12
+ export declare function getGaslessBatchFundingQueryKey(options?: Compute<ExactPartial<GetGaslessBatchFundingParameters> & ConfigKeyParameter>): readonly ["getGaslessBatchFunding", Record<string, unknown>];
13
+ /** Query-key type for batch funding. */
14
+ export type GetGaslessBatchFundingQueryKey = ReturnType<typeof getGaslessBatchFundingQueryKey>;
15
+ /** Required action inputs plus optional query overrides. */
16
+ export type GetGaslessBatchFundingOptions = Compute<GetGaslessBatchFundingParameters & QueryParameter<GetGaslessBatchFundingData, Error, GetGaslessBatchFundingData, GetGaslessBatchFundingQueryKey>>;
17
+ /** TanStack Query options for a batch-funding preview. */
18
+ export type GetGaslessBatchFundingQueryOptions = SymmioQueryOptions<GetGaslessBatchFundingData, Error, GetGaslessBatchFundingData, GetGaslessBatchFundingQueryKey>;
19
+ /**
20
+ * Build query options for a read-only funding preview. Read the core action fresh before submission.
21
+ * @param config - SDK config.
22
+ * @param options - Required funding inputs and query overrides.
23
+ * @returns Options for a TanStack query, stale immediately by default.
24
+ * @example
25
+ * ```ts
26
+ * const options = getGaslessBatchFundingQueryOptions(config, { account, calls, balanceChanges });
27
+ * const preview = await queryClient.fetchQuery(options);
28
+ * ```
29
+ */
30
+ export declare function getGaslessBatchFundingQueryOptions(config: Config, options: GetGaslessBatchFundingOptions): GetGaslessBatchFundingQueryOptions;
31
+ //# sourceMappingURL=query.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../../../src/gasless/get-gasless-batch-funding/query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC/F,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAGnF,OAAO,KAAK,EAAE,gCAAgC,EAAE,gCAAgC,EAAE,MAAM,SAAS,CAAC;AAElG,gDAAgD;AAChD,MAAM,MAAM,0BAA0B,GAAG,gCAAgC,CAAC;AAE1E;;;;GAIG;AACH,wBAAgB,8BAA8B,CAC5C,OAAO,GAAE,OAAO,CAAC,YAAY,CAAC,gCAAgC,CAAC,GAAG,kBAAkB,CAAM,gEAG3F;AAED,wCAAwC;AACxC,MAAM,MAAM,8BAA8B,GAAG,UAAU,CAAC,OAAO,8BAA8B,CAAC,CAAC;AAE/F,4DAA4D;AAC5D,MAAM,MAAM,6BAA6B,GAAG,OAAO,CACjD,gCAAgC,GAC9B,cAAc,CAAC,0BAA0B,EAAE,KAAK,EAAE,0BAA0B,EAAE,8BAA8B,CAAC,CAChH,CAAC;AAEF,0DAA0D;AAC1D,MAAM,MAAM,kCAAkC,GAAG,kBAAkB,CACjE,0BAA0B,EAC1B,KAAK,EACL,0BAA0B,EAC1B,8BAA8B,CAC/B,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,kCAAkC,CAChD,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,6BAA6B,GACrC,kCAAkC,CAQpC"}
@@ -0,0 +1,22 @@
1
+ import { getGaslessBatchFeeQuoteQueryKey as e } from "../get-gasless-batch-fee-quote/query.js";
2
+ import { getGaslessBatchFunding as t } from "./get-gasless-batch-funding.js";
3
+ //#region src/gasless/get-gasless-batch-funding/query.ts
4
+ function n(t = {}) {
5
+ return ["getGaslessBatchFunding", e(t)[1]];
6
+ }
7
+ function r(e, r) {
8
+ return {
9
+ staleTime: 0,
10
+ ...r.query,
11
+ queryKey: n({
12
+ ...r,
13
+ configKey: e.getChainConfigKey(r.chainId)
14
+ }),
15
+ enabled: r.query?.enabled ?? !0,
16
+ queryFn: () => t(e, r)
17
+ };
18
+ }
19
+ //#endregion
20
+ export { n as getGaslessBatchFundingQueryKey, r as getGaslessBatchFundingQueryOptions };
21
+
22
+ //# sourceMappingURL=query.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query.js","names":[],"sources":["../../../src/gasless/get-gasless-batch-funding/query.ts"],"sourcesContent":["import type { Config } from \"../../core/config\";\nimport type { Compute, ConfigKeyParameter, ExactPartial } from \"../../shared/types/properties\";\nimport type { QueryParameter, SymmioQueryOptions } from \"../../shared/types/query\";\nimport { getGaslessBatchFeeQuoteQueryKey } from \"../get-gasless-batch-fee-quote\";\nimport { getGaslessBatchFunding } from \"./get-gasless-batch-funding\";\nimport type { GetGaslessBatchFundingParameters, GetGaslessBatchFundingReturnType } from \"./types\";\n\n/** Data resolved by the batch-funding query. */\nexport type GetGaslessBatchFundingData = GetGaslessBatchFundingReturnType;\n\n/**\n * Key a funding preview by config, chain, account, encoded calls and balance movements.\n * @param options - Partial funding inputs and optional config identity.\n * @returns Stable query key; unencodable calls are deferred to the query function.\n */\nexport function getGaslessBatchFundingQueryKey(\n options: Compute<ExactPartial<GetGaslessBatchFundingParameters> & ConfigKeyParameter> = {},\n) {\n return [\"getGaslessBatchFunding\", getGaslessBatchFeeQuoteQueryKey(options)[1]] as const;\n}\n\n/** Query-key type for batch funding. */\nexport type GetGaslessBatchFundingQueryKey = ReturnType<typeof getGaslessBatchFundingQueryKey>;\n\n/** Required action inputs plus optional query overrides. */\nexport type GetGaslessBatchFundingOptions = Compute<\n GetGaslessBatchFundingParameters &\n QueryParameter<GetGaslessBatchFundingData, Error, GetGaslessBatchFundingData, GetGaslessBatchFundingQueryKey>\n>;\n\n/** TanStack Query options for a batch-funding preview. */\nexport type GetGaslessBatchFundingQueryOptions = SymmioQueryOptions<\n GetGaslessBatchFundingData,\n Error,\n GetGaslessBatchFundingData,\n GetGaslessBatchFundingQueryKey\n>;\n\n/**\n * Build query options for a read-only funding preview. Read the core action fresh before submission.\n * @param config - SDK config.\n * @param options - Required funding inputs and query overrides.\n * @returns Options for a TanStack query, stale immediately by default.\n * @example\n * ```ts\n * const options = getGaslessBatchFundingQueryOptions(config, { account, calls, balanceChanges });\n * const preview = await queryClient.fetchQuery(options);\n * ```\n */\nexport function getGaslessBatchFundingQueryOptions(\n config: Config,\n options: GetGaslessBatchFundingOptions,\n): GetGaslessBatchFundingQueryOptions {\n return {\n staleTime: 0,\n ...options.query,\n queryKey: getGaslessBatchFundingQueryKey({ ...options, configKey: config.getChainConfigKey(options.chainId) }),\n enabled: options.query?.enabled ?? true,\n queryFn: () => getGaslessBatchFunding(config, options),\n };\n}\n"],"mappings":";;;AAeA,SAAgB,EACd,IAAwF,CAAC,GACzF;CACA,OAAO,CAAC,0BAA0B,EAAgC,CAAO,EAAE,EAAE;AAC/E;AA8BA,SAAgB,EACd,GACA,GACoC;CACpC,OAAO;EACL,WAAW;EACX,GAAG,EAAQ;EACX,UAAU,EAA+B;GAAE,GAAG;GAAS,WAAW,EAAO,kBAAkB,EAAQ,OAAO;EAAE,CAAC;EAC7G,SAAS,EAAQ,OAAO,WAAW;EACnC,eAAe,EAAuB,GAAQ,CAAO;CACvD;AACF"}