@formo/analytics 1.35.2 → 1.37.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 (51) hide show
  1. package/dist/cjs/src/FormoAnalytics.d.ts +79 -363
  2. package/dist/cjs/src/FormoAnalytics.js +368 -2234
  3. package/dist/cjs/src/event/EventManager.d.ts +3 -1
  4. package/dist/cjs/src/event/EventManager.js +5 -1
  5. package/dist/cjs/src/event/type.d.ts +1 -0
  6. package/dist/cjs/src/evm/EvmEventTracker.d.ts +175 -0
  7. package/dist/cjs/src/evm/EvmEventTracker.js +1030 -0
  8. package/dist/cjs/src/evm/EvmProviderRegistry.d.ts +132 -0
  9. package/dist/cjs/src/evm/EvmProviderRegistry.js +348 -0
  10. package/dist/cjs/src/evm/EvmRequestTracker.d.ts +98 -0
  11. package/dist/cjs/src/evm/EvmRequestTracker.js +713 -0
  12. package/dist/cjs/src/evm/batch.d.ts +94 -0
  13. package/dist/cjs/src/evm/batch.js +130 -0
  14. package/dist/cjs/src/queue/EventQueue.d.ts +28 -0
  15. package/dist/cjs/src/queue/EventQueue.js +97 -19
  16. package/dist/cjs/src/queue/type.d.ts +1 -0
  17. package/dist/cjs/src/tracking/TrackingPolicy.d.ts +146 -0
  18. package/dist/cjs/src/tracking/TrackingPolicy.js +200 -0
  19. package/dist/cjs/src/validators/address.d.ts +1 -1
  20. package/dist/cjs/src/version.d.ts +1 -1
  21. package/dist/cjs/src/version.js +1 -1
  22. package/dist/cjs/src/wagmi/WagmiEventHandler.d.ts +43 -0
  23. package/dist/cjs/src/wagmi/WagmiEventHandler.js +253 -2
  24. package/dist/cjs/src/wallet/WalletStateStore.d.ts +223 -0
  25. package/dist/cjs/src/wallet/WalletStateStore.js +515 -0
  26. package/dist/esm/src/FormoAnalytics.d.ts +79 -363
  27. package/dist/esm/src/FormoAnalytics.js +369 -2235
  28. package/dist/esm/src/event/EventManager.d.ts +3 -1
  29. package/dist/esm/src/event/EventManager.js +5 -1
  30. package/dist/esm/src/event/type.d.ts +1 -0
  31. package/dist/esm/src/evm/EvmEventTracker.d.ts +175 -0
  32. package/dist/esm/src/evm/EvmEventTracker.js +1027 -0
  33. package/dist/esm/src/evm/EvmProviderRegistry.d.ts +132 -0
  34. package/dist/esm/src/evm/EvmProviderRegistry.js +345 -0
  35. package/dist/esm/src/evm/EvmRequestTracker.d.ts +98 -0
  36. package/dist/esm/src/evm/EvmRequestTracker.js +710 -0
  37. package/dist/esm/src/evm/batch.d.ts +94 -0
  38. package/dist/esm/src/evm/batch.js +123 -0
  39. package/dist/esm/src/queue/EventQueue.d.ts +28 -0
  40. package/dist/esm/src/queue/EventQueue.js +97 -19
  41. package/dist/esm/src/queue/type.d.ts +1 -0
  42. package/dist/esm/src/tracking/TrackingPolicy.d.ts +146 -0
  43. package/dist/esm/src/tracking/TrackingPolicy.js +197 -0
  44. package/dist/esm/src/version.d.ts +1 -1
  45. package/dist/esm/src/version.js +1 -1
  46. package/dist/esm/src/wagmi/WagmiEventHandler.d.ts +43 -0
  47. package/dist/esm/src/wagmi/WagmiEventHandler.js +253 -2
  48. package/dist/esm/src/wallet/WalletStateStore.d.ts +223 -0
  49. package/dist/esm/src/wallet/WalletStateStore.js +512 -0
  50. package/dist/index.umd.min.js +1 -1
  51. package/package.json +6 -4
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TrackingPolicy = void 0;
4
+ var timezone_1 = require("../utils/timezone");
5
+ var validators_1 = require("../validators");
6
+ /**
7
+ * Every "may we track this?" decision, in one place.
8
+ *
9
+ * Split out of `FormoAnalytics` so the rules can be read and tested without
10
+ * an SDK instance, and so option parsing happens once rather than being
11
+ * re-derived at each gate.
12
+ */
13
+ var TrackingPolicy = /** @class */ (function () {
14
+ function TrackingPolicy(deps) {
15
+ this.deps = deps;
16
+ }
17
+ /**
18
+ * `tracking` as an options object, or null when it is absent, a boolean, or
19
+ * anything else. Every exclusion rule lives on the object form, so a null
20
+ * here means "no exclusions configured", not "excluded".
21
+ */
22
+ TrackingPolicy.prototype.trackingOptions = function () {
23
+ var tracking = this.deps.options().tracking;
24
+ if (tracking === null ||
25
+ typeof tracking !== "object" ||
26
+ Array.isArray(tracking)) {
27
+ return null;
28
+ }
29
+ return tracking;
30
+ };
31
+ /**
32
+ * Visitor-level tracking suppression.
33
+ *
34
+ * True when the SDK must not persist any identity/session/chain state or
35
+ * send any events for this visitor: an explicit opt-out, or a
36
+ * jurisdiction/timezone/host/path exclusion. Public entry points that write
37
+ * state before reaching `shouldTrack()` (identify / connect / detect) check
38
+ * this first, so a suppressed visitor leaves no cookies or session state.
39
+ */
40
+ TrackingPolicy.prototype.isTrackingSuppressed = function () {
41
+ return this.deps.hasOptedOut() || this.isEnvironmentExcluded();
42
+ };
43
+ /**
44
+ * Whether the environment is excluded: the visitor's timezone, the current
45
+ * hostname, or the current pathname.
46
+ *
47
+ * Timezone is visitor-level and stable for the session. Host and path are
48
+ * current-page-level and transient, so a SPA navigating back to an allowed
49
+ * path resumes tracking for later actions.
50
+ */
51
+ TrackingPolicy.prototype.isEnvironmentExcluded = function () {
52
+ return (this.isTimezoneExcluded() ||
53
+ this.isHostExcluded() ||
54
+ this.isPathExcluded());
55
+ };
56
+ /** Exact match against `tracking.excludeHosts`. */
57
+ TrackingPolicy.prototype.isHostExcluded = function () {
58
+ var tracking = this.trackingOptions();
59
+ if (!tracking)
60
+ return false;
61
+ if (typeof window === "undefined")
62
+ return false;
63
+ var _a = tracking.excludeHosts, excludeHosts = _a === void 0 ? [] : _a;
64
+ return excludeHosts.includes(window.location.hostname);
65
+ };
66
+ /** Exact match against `tracking.excludePaths`. */
67
+ TrackingPolicy.prototype.isPathExcluded = function () {
68
+ var tracking = this.trackingOptions();
69
+ if (!tracking)
70
+ return false;
71
+ if (typeof window === "undefined")
72
+ return false;
73
+ var _a = tracking.excludePaths, excludePaths = _a === void 0 ? [] : _a;
74
+ return excludePaths.includes(window.location.pathname);
75
+ };
76
+ /**
77
+ * Case-insensitive match of the browser-resolved timezone against
78
+ * `tracking.excludeTimezones`. Client-side and best-effort; see the option's
79
+ * own documentation.
80
+ */
81
+ TrackingPolicy.prototype.isTimezoneExcluded = function () {
82
+ var tracking = this.trackingOptions();
83
+ if (!tracking)
84
+ return false;
85
+ var _a = tracking.excludeTimezones, excludeTimezones = _a === void 0 ? [] : _a;
86
+ if (excludeTimezones.length === 0)
87
+ return false;
88
+ var timezone = (0, timezone_1.getTimezone)();
89
+ if (!timezone)
90
+ return false;
91
+ var lowerTimezone = timezone.toLowerCase();
92
+ return excludeTimezones.some(function (tz) { return typeof tz === "string" && tz.toLowerCase() === lowerTimezone; });
93
+ };
94
+ /**
95
+ * Whether the CURRENT PAGE is excluded, as opposed to the visitor.
96
+ *
97
+ * Host and path exclusions are transient: identity written on an allowed
98
+ * page must survive a visit to an excluded route, so callers that persist
99
+ * or restore identity skip the work here rather than purging.
100
+ */
101
+ TrackingPolicy.prototype.isPageExcluded = function () {
102
+ return this.isHostExcluded() || this.isPathExcluded();
103
+ };
104
+ /**
105
+ * Whether a persisted identity cookie should be actively purged, not merely
106
+ * left unwritten.
107
+ *
108
+ * Host and path exclusions are deliberately absent: they are transient
109
+ * current-page states, so a cookie legitimately written on an allowed page
110
+ * must survive a visit to an excluded route.
111
+ */
112
+ TrackingPolicy.prototype.isPersistedIdentityPurgeRequired = function () {
113
+ return this.deps.hasOptedOut() || this.isTimezoneExcluded();
114
+ };
115
+ /**
116
+ * Whether the chain in play is in `tracking.excludeChains`.
117
+ *
118
+ * Separate from `shouldTrack()` so `identify()` can ask *before* mutating
119
+ * identity state. `trackEvent()` drops an excluded event silently, but
120
+ * `identify()` marks the wallet as identified first, so without this an
121
+ * identify on an excluded chain is dedup-marked and then discarded, and the
122
+ * wallet never re-emits for the rest of the session even after switching to
123
+ * an allowed chain. On the Privy path that loses a whole cluster at once.
124
+ */
125
+ TrackingPolicy.prototype.isChainExcluded = function (context) {
126
+ var tracking = this.trackingOptions();
127
+ if (!tracking)
128
+ return false;
129
+ var _a = tracking.excludeChains, excludeChains = _a === void 0 ? [] : _a;
130
+ if (excludeChains.length === 0)
131
+ return false;
132
+ return this.isChainRefused(excludeChains, context);
133
+ };
134
+ /**
135
+ * The shared chain rule, so `shouldTrack()` and `isChainExcluded()` cannot
136
+ * drift apart. Callers have already established that `excludeChains` is
137
+ * non-empty.
138
+ *
139
+ * Fails CLOSED on an unknown chain. `resolveChainIdForProvider` reports 0
140
+ * when it has never heard a chain from the signing wallet, and 0 is in no
141
+ * exclusion list, so treating it as "not excluded" would let through exactly
142
+ * the events an operator excluded: the wallet on the excluded chain is often
143
+ * the one we know least about. An explicit exclusion is a directive, so an
144
+ * unresolvable chain is refused.
145
+ *
146
+ * Keyed on 0 and deliberately NOT on `undefined`. 0 is the explicit "we
147
+ * asked and could not tell" marker. `undefined` means no chain state yet,
148
+ * which is a legitimate transient (the Privy path reconciles a Solana wallet
149
+ * through exactly that state), and refusing it would drop real events.
150
+ * `backfillActiveWallet()` never persists 0, so an unresolvable chain cannot
151
+ * leak into the central value and reach the unscoped events (page / track /
152
+ * identify) that fall back to it.
153
+ */
154
+ TrackingPolicy.prototype.isChainRefused = function (excludeChains, context) {
155
+ var _a;
156
+ var chainToCheck = (_a = context === null || context === void 0 ? void 0 : context.chainId) !== null && _a !== void 0 ? _a : this.deps.currentChainId();
157
+ if (chainToCheck === 0)
158
+ return true;
159
+ if (chainToCheck === undefined)
160
+ return false;
161
+ return excludeChains.includes(chainToCheck);
162
+ };
163
+ /** Whether an event may be tracked at all, given consent and configuration. */
164
+ TrackingPolicy.prototype.shouldTrack = function (context) {
165
+ if (this.deps.hasOptedOut())
166
+ return false;
167
+ // An explicit boolean is the whole answer; no exclusions apply to it.
168
+ var tracking = this.deps.options().tracking;
169
+ if (typeof tracking === "boolean")
170
+ return tracking;
171
+ var configured = this.trackingOptions();
172
+ if (configured) {
173
+ if (this.isEnvironmentExcluded())
174
+ return false;
175
+ var _a = configured.excludeChains, excludeChains = _a === void 0 ? [] : _a;
176
+ if (excludeChains.length > 0 && this.isChainRefused(excludeChains, context)) {
177
+ return false;
178
+ }
179
+ return true;
180
+ }
181
+ // Nothing configured: track everywhere except localhost.
182
+ return !(0, validators_1.isLocalhost)();
183
+ };
184
+ /** Whether a wallet event kind is enabled for autocapture. Defaults to on. */
185
+ TrackingPolicy.prototype.isAutocaptureEnabled = function (eventType) {
186
+ var autocapture = this.deps.options().autocapture;
187
+ if (autocapture === undefined)
188
+ return true;
189
+ if (typeof autocapture === "boolean")
190
+ return autocapture;
191
+ if (autocapture !== null && typeof autocapture === "object") {
192
+ // Only an explicit false disables a kind.
193
+ return autocapture[eventType] !== false;
194
+ }
195
+ return true;
196
+ };
197
+ return TrackingPolicy;
198
+ }());
199
+ exports.TrackingPolicy = TrackingPolicy;
200
+ //# sourceMappingURL=TrackingPolicy.js.map
@@ -1,5 +1,5 @@
1
1
  import { ValidInputTypes } from "../types";
2
2
  export declare const isAddress: (value: ValidInputTypes, checksum?: boolean) => boolean;
3
3
  export declare const checkAddressChecksum: (data: string) => boolean;
4
- export declare function ensureIfUint8Array<T = any>(data: T): Uint8Array<ArrayBuffer> | T;
4
+ export declare function ensureIfUint8Array<T = any>(data: T): T | Uint8Array<ArrayBuffer>;
5
5
  //# sourceMappingURL=address.d.ts.map
@@ -1,2 +1,2 @@
1
- export declare const version = "1.35.2";
1
+ export declare const version = "1.37.0";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -3,5 +3,5 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.version = void 0;
4
4
  // This file is auto-generated by scripts/update-version.js during npm version
5
5
  // Do not edit manually - it will be overwritten
6
- exports.version = '1.35.2';
6
+ exports.version = '1.37.0';
7
7
  //# sourceMappingURL=version.js.map
@@ -96,6 +96,8 @@ export declare class WagmiEventHandler {
96
96
  * broadcast to match the receipt against.
97
97
  */
98
98
  private get pendingTransactions();
99
+ /** Broadcast batches awaiting `callsStatus`, shared like the map above. */
100
+ private get pendingBatches();
99
101
  constructor(formoAnalytics: FormoAnalytics, wagmiConfig: WagmiConfig, queryClient?: QueryClient);
100
102
  /**
101
103
  * Set up listeners for wallet connection, disconnection, and chain changes
@@ -228,6 +230,30 @@ export declare class WagmiEventHandler {
228
230
  * Handle query cache events (transaction confirmations)
229
231
  */
230
232
  private handleQueryEvent;
233
+ /**
234
+ * Settle a just-registered batch from a status query that already ran.
235
+ *
236
+ * Best-effort by design: the minimal QueryClient interface the SDK
237
+ * accepts is not guaranteed to expose cache lookup, and a missing
238
+ * `getAll` just means settlement waits for the next query event, which
239
+ * is where it normally comes from anyway.
240
+ */
241
+ private settleFromCachedCallsStatus;
242
+ /**
243
+ * Settle an EIP-5792 batch from a `callsStatus` query.
244
+ *
245
+ * Only batches whose broadcast this SDK observed are settled: the batch id
246
+ * must be in `pendingBatches`, for the same reason receipt queries are
247
+ * gated on an observed hash - queries are visible to any code sharing the
248
+ * QueryClient, and emitting for an id we never saw broadcast would let a
249
+ * forged query invent transactions.
250
+ *
251
+ * Outcome semantics are shared with the EIP-1193 path (`src/evm/batch.ts`):
252
+ * per-call receipts outrank the batch verdict, an atomic batch's single
253
+ * receipt reaches every call, and a 600 leaves receipt-less calls
254
+ * unsettled rather than guessed.
255
+ */
256
+ private handleCallsStatusQuery;
231
257
  /**
232
258
  * Handle waitForTransactionReceipt query completion
233
259
  * Emits CONFIRMED or REVERTED transaction status
@@ -245,6 +271,23 @@ export declare class WagmiEventHandler {
245
271
  * Handle transaction mutations (sendTransaction, writeContract)
246
272
  */
247
273
  private handleTransactionMutation;
274
+ /**
275
+ * One `transaction` event per call in an EIP-5792 batch, wagmi path.
276
+ *
277
+ * Mirrors `EvmRequestTracker.trackBatchedCalls` exactly: the CALL is the
278
+ * unit of attribution, so each call gets its own STARTED at pending and
279
+ * BROADCASTED (with `batch_id`) when the wallet returns an id. The batch's
280
+ * on-chain outcome arrives through the `callsStatus` query, handled in
281
+ * `handleCallsStatusQuery`.
282
+ *
283
+ * Rejection matches the 1193 path's rule: only a user rejection (4001
284
+ * anywhere in the error chain) marks the calls rejected - one dismissal
285
+ * dismisses the whole prompt, so every call in it is rejected, and
286
+ * reporting only the first would undercount. Any other error (a wallet
287
+ * without EIP-5792 support, a transport failure) emits nothing further:
288
+ * inventing a rejection the user never made would be worse.
289
+ */
290
+ private handleSendCallsMutation;
248
291
  /**
249
292
  * Get the current Wagmi state
250
293
  * Supports both getState() method and direct state property access
@@ -58,6 +58,7 @@ exports.WagmiEventHandler = exports.MARKER_GRACE_MS = void 0;
58
58
  exports.__resetSeededWallet = __resetSeededWallet;
59
59
  var events_1 = require("../types/events");
60
60
  var logger_1 = require("../logger");
61
+ var batch_1 = require("../evm/batch");
61
62
  var utils_1 = require("./utils");
62
63
  /**
63
64
  * Built-in transaction fields that could collide with function args.
@@ -200,6 +201,25 @@ var ownerKey = function (writeKey, config) {
200
201
  }
201
202
  return "".concat(writeKey, ":").concat(id);
202
203
  };
204
+ /**
205
+ * Was this mutation error the user dismissing the wallet prompt?
206
+ *
207
+ * Matches the EIP-1193 path's rule (code 4001), but a wagmi mutation error
208
+ * arrives wrapped: viem nests the RPC error under `cause`, sometimes twice.
209
+ * Walk the chain rather than trusting the top level, and accept viem's
210
+ * `UserRejectedRequestError` by name for wallets that map the rejection to a
211
+ * typed error without preserving the numeric code.
212
+ */
213
+ function isUserRejection(error) {
214
+ var cursor = error;
215
+ for (var depth = 0; cursor && depth < 5; depth++) {
216
+ if (cursor.code === 4001 || cursor.name === "UserRejectedRequestError") {
217
+ return true;
218
+ }
219
+ cursor = cursor.cause;
220
+ }
221
+ return false;
222
+ }
203
223
  /**
204
224
  * Pending transactions, shared per destination rather than per handler.
205
225
  *
@@ -209,6 +229,7 @@ var ownerKey = function (writeKey, config) {
209
229
  * broadcast to match the receipt against.
210
230
  */
211
231
  var pendingTransactionsByDestination = new Map();
232
+ var pendingBatchesByDestination = new Map();
212
233
  /**
213
234
  * Pending records outlive a rebuild by the same grace period as the markers.
214
235
  * The ordinary rebuild is cleanup THEN remount, so dropping them the instant
@@ -223,6 +244,7 @@ function schedulePendingTransactionExpiry(key) {
223
244
  var timer = setTimeout(function () {
224
245
  pendingTransactionExpiry.delete(key);
225
246
  pendingTransactionsByDestination.delete(key);
247
+ pendingBatchesByDestination.delete(key);
226
248
  }, exports.MARKER_GRACE_MS);
227
249
  (_b = (_a = timer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
228
250
  pendingTransactionExpiry.set(key, timer);
@@ -289,6 +311,7 @@ function __resetSeededWallet() {
289
311
  pendingTransactionExpiry.forEach(function (t) { return clearTimeout(t); });
290
312
  pendingTransactionExpiry.clear();
291
313
  pendingTransactionsByDestination.clear();
314
+ pendingBatchesByDestination.clear();
292
315
  announcedConnections.clear();
293
316
  liveHandlers.clear();
294
317
  markerExpiry.forEach(function (timer) { return clearTimeout(timer); });
@@ -501,6 +524,21 @@ var WagmiEventHandler = /** @class */ (function () {
501
524
  enumerable: false,
502
525
  configurable: true
503
526
  });
527
+ Object.defineProperty(WagmiEventHandler.prototype, "pendingBatches", {
528
+ /** Broadcast batches awaiting `callsStatus`, shared like the map above. */
529
+ get: function () {
530
+ var _a;
531
+ var key = (_a = this.ownerKey) !== null && _a !== void 0 ? _a : "";
532
+ var map = pendingBatchesByDestination.get(key);
533
+ if (!map) {
534
+ map = new Map();
535
+ pendingBatchesByDestination.set(key, map);
536
+ }
537
+ return map;
538
+ },
539
+ enumerable: false,
540
+ configurable: true
541
+ });
504
542
  /**
505
543
  * Set up listeners for wallet connection, disconnection, and chain changes
506
544
  */
@@ -1453,8 +1491,23 @@ var WagmiEventHandler = /** @class */ (function () {
1453
1491
  return;
1454
1492
  }
1455
1493
  var queryType = queryKey[0];
1456
- // Only handle waitForTransactionReceipt queries
1457
- if (queryType !== "waitForTransactionReceipt") {
1494
+ // Only the two query families that settle something we broadcast:
1495
+ // waitForTransactionReceipt for single transactions, callsStatus for
1496
+ // EIP-5792 batches (both useCallsStatus and useWaitForCallsStatus share
1497
+ // the 'callsStatus' key, in wagmi 2 and 3 alike).
1498
+ if (queryType !== "waitForTransactionReceipt" && queryType !== "callsStatus") {
1499
+ return;
1500
+ }
1501
+ // Batch settlement dedupes on the pending-batch registry, NOT on
1502
+ // processedQueries: settling deletes the registration, so a duplicate
1503
+ // delivery finds nothing to do. A processed-key here would be worse
1504
+ // than redundant - the status query can complete BEFORE the sendCalls
1505
+ // mutation registers the batch (TanStack dispatches a mutation's
1506
+ // success state after its onSuccess callbacks, and apps await the
1507
+ // status inside onSuccess), and a key recorded on that early skip
1508
+ // would block every refetch from ever settling the batch.
1509
+ if (queryType === "callsStatus") {
1510
+ this.handleCallsStatusQuery(query);
1458
1511
  return;
1459
1512
  }
1460
1513
  var state = query.state;
@@ -1487,6 +1540,111 @@ var WagmiEventHandler = /** @class */ (function () {
1487
1540
  // Clean up old processed queries to prevent memory leaks
1488
1541
  cleanupOldEntries(this.processedQueries);
1489
1542
  };
1543
+ /**
1544
+ * Settle a just-registered batch from a status query that already ran.
1545
+ *
1546
+ * Best-effort by design: the minimal QueryClient interface the SDK
1547
+ * accepts is not guaranteed to expose cache lookup, and a missing
1548
+ * `getAll` just means settlement waits for the next query event, which
1549
+ * is where it normally comes from anyway.
1550
+ */
1551
+ WagmiEventHandler.prototype.settleFromCachedCallsStatus = function (batchId) {
1552
+ var _a, _b, _c;
1553
+ try {
1554
+ var cache = (_a = this.queryClient) === null || _a === void 0 ? void 0 : _a.getQueryCache();
1555
+ var queries = (_b = cache === null || cache === void 0 ? void 0 : cache.getAll) === null || _b === void 0 ? void 0 : _b.call(cache);
1556
+ if (!Array.isArray(queries))
1557
+ return;
1558
+ for (var _i = 0, queries_1 = queries; _i < queries_1.length; _i++) {
1559
+ var query = queries_1[_i];
1560
+ var key = query === null || query === void 0 ? void 0 : query.queryKey;
1561
+ if (Array.isArray(key) &&
1562
+ key[0] === "callsStatus" &&
1563
+ ((_c = key[1]) === null || _c === void 0 ? void 0 : _c.id) === batchId) {
1564
+ this.handleCallsStatusQuery(query);
1565
+ }
1566
+ }
1567
+ }
1568
+ catch (error) {
1569
+ logger_1.logger.debug("WagmiEventHandler: cached callsStatus scan failed", error);
1570
+ }
1571
+ };
1572
+ /**
1573
+ * Settle an EIP-5792 batch from a `callsStatus` query.
1574
+ *
1575
+ * Only batches whose broadcast this SDK observed are settled: the batch id
1576
+ * must be in `pendingBatches`, for the same reason receipt queries are
1577
+ * gated on an observed hash - queries are visible to any code sharing the
1578
+ * QueryClient, and emitting for an id we never saw broadcast would let a
1579
+ * forged query invent transactions.
1580
+ *
1581
+ * Outcome semantics are shared with the EIP-1193 path (`src/evm/batch.ts`):
1582
+ * per-call receipts outrank the batch verdict, an atomic batch's single
1583
+ * receipt reaches every call, and a 600 leaves receipt-less calls
1584
+ * unsettled rather than guessed.
1585
+ */
1586
+ WagmiEventHandler.prototype.handleCallsStatusQuery = function (query) {
1587
+ var _this = this;
1588
+ var _a;
1589
+ if (!this.formo.isAutocaptureEnabled("transaction")) {
1590
+ return;
1591
+ }
1592
+ var queryKey = query.queryKey;
1593
+ // Query key format: ['callsStatus', { id, ... }]
1594
+ var params = queryKey[1];
1595
+ var batchId = params === null || params === void 0 ? void 0 : params.id;
1596
+ if (!batchId) {
1597
+ return;
1598
+ }
1599
+ var pending = this.pendingBatches.get(batchId);
1600
+ if (!pending) {
1601
+ logger_1.logger.debug("WagmiEventHandler: unobserved batch", { batchId: batchId });
1602
+ return;
1603
+ }
1604
+ var state = query.state;
1605
+ if (state.status !== "success" || !state.data) {
1606
+ return;
1607
+ }
1608
+ try {
1609
+ var res_1 = state.data;
1610
+ var code_1 = (0, batch_1.readBatchStatusCode)(res_1);
1611
+ // Below 200 the batch is still pending; the query will update again.
1612
+ if (code_1 === undefined || code_1 < 200) {
1613
+ return;
1614
+ }
1615
+ logger_1.logger.debug("WagmiEventHandler: batch settled", { batchId: batchId, code: code_1 });
1616
+ // An explicit mutation chain is authoritative. Otherwise prefer the
1617
+ // chain the settlement result names - EIP-5792 v2 reports where the
1618
+ // batch actually landed - over one inferred from the connection at
1619
+ // broadcast, which goes stale if the wallet moves chains while the
1620
+ // prompt is up. Same precedence as the single-transaction receipt
1621
+ // path.
1622
+ var settledChainId_1 = pending.chainIdWasExplicit
1623
+ ? pending.chainId
1624
+ : (_a = (0, batch_1.readBatchChainId)(res_1)) !== null && _a !== void 0 ? _a : pending.chainId;
1625
+ pending.calls.forEach(function (call, index) {
1626
+ var receipt = (0, batch_1.batchReceiptForCall)(res_1, index, pending.calls.length);
1627
+ var outcome = (0, batch_1.batchCallOutcome)(code_1, receipt);
1628
+ // 600 means SOME calls reverted, so a call with no receipt of its
1629
+ // own has not been decided. Reporting it either way would invent a
1630
+ // result; leaving it unsettled is the honest answer.
1631
+ if (outcome === undefined)
1632
+ return;
1633
+ _this.formo.transaction(__assign(__assign(__assign(__assign({ status: outcome, chainId: settledChainId_1 || 0, address: pending.address }, (call.data && { data: call.data })), (call.to && { to: call.to })), (call.value && { value: call.value })), ((receipt === null || receipt === void 0 ? void 0 : receipt.transactionHash)
1634
+ ? { transactionHash: receipt.transactionHash }
1635
+ : {})), {
1636
+ batch_size: pending.calls.length,
1637
+ batch_index: index,
1638
+ batch_id: batchId,
1639
+ });
1640
+ });
1641
+ // Settled; a later refetch of the same query must not re-emit.
1642
+ this.pendingBatches.delete(batchId);
1643
+ }
1644
+ catch (error) {
1645
+ logger_1.logger.error("WagmiEventHandler: callsStatus error:", error);
1646
+ }
1647
+ };
1490
1648
  /**
1491
1649
  * Handle waitForTransactionReceipt query completion
1492
1650
  * Emits CONFIRMED or REVERTED transaction status
@@ -1616,6 +1774,13 @@ var WagmiEventHandler = /** @class */ (function () {
1616
1774
  if (mutationType === "sendTransaction" || mutationType === "writeContract") {
1617
1775
  this.handleTransactionMutation(mutationType, mutation);
1618
1776
  }
1777
+ // Handle EIP-5792 batch mutations (useSendCalls). Absent this branch,
1778
+ // wagmi-mode apps captured nothing for a batch: the EIP-1193 request
1779
+ // wrapper that handles `wallet_sendCalls` is never installed in wagmi
1780
+ // mode, so the mutation was the only place the batch was visible at all.
1781
+ if (mutationType === "sendCalls") {
1782
+ this.handleSendCallsMutation(mutation);
1783
+ }
1619
1784
  // Clean up old processed mutations to prevent memory leaks
1620
1785
  cleanupOldEntries(this.processedMutations);
1621
1786
  };
@@ -1805,6 +1970,92 @@ var WagmiEventHandler = /** @class */ (function () {
1805
1970
  logger_1.logger.error("WagmiEventHandler: Error handling transaction mutation:", error);
1806
1971
  }
1807
1972
  };
1973
+ /**
1974
+ * One `transaction` event per call in an EIP-5792 batch, wagmi path.
1975
+ *
1976
+ * Mirrors `EvmRequestTracker.trackBatchedCalls` exactly: the CALL is the
1977
+ * unit of attribution, so each call gets its own STARTED at pending and
1978
+ * BROADCASTED (with `batch_id`) when the wallet returns an id. The batch's
1979
+ * on-chain outcome arrives through the `callsStatus` query, handled in
1980
+ * `handleCallsStatusQuery`.
1981
+ *
1982
+ * Rejection matches the 1193 path's rule: only a user rejection (4001
1983
+ * anywhere in the error chain) marks the calls rejected - one dismissal
1984
+ * dismisses the whole prompt, so every call in it is rejected, and
1985
+ * reporting only the first would undercount. Any other error (a wallet
1986
+ * without EIP-5792 support, a transport failure) emits nothing further:
1987
+ * inventing a rejection the user never made would be worse.
1988
+ */
1989
+ WagmiEventHandler.prototype.handleSendCallsMutation = function (mutation) {
1990
+ var _this = this;
1991
+ if (!this.formo.isAutocaptureEnabled("transaction")) {
1992
+ return;
1993
+ }
1994
+ var state = mutation.state;
1995
+ var variables = state.variables || {};
1996
+ var rawCalls = Array.isArray(variables.calls) ? variables.calls : [];
1997
+ if (rawCalls.length === 0) {
1998
+ return;
1999
+ }
2000
+ // Same resolution order as single transactions: an explicit per-call
2001
+ // value beats the tracked connection.
2002
+ var explicitChainId = normalizeChainId(variables.chainId);
2003
+ var chainId = explicitChainId !== null && explicitChainId !== void 0 ? explicitChainId : this.trackingState.lastChainId;
2004
+ var accountAddress = resolveAccountAddress(variables.account);
2005
+ var userAddress = accountAddress || this.trackingState.lastAddress;
2006
+ if (!userAddress) {
2007
+ logger_1.logger.warn("WagmiEventHandler: sendCalls without address");
2008
+ return;
2009
+ }
2010
+ try {
2011
+ var calls_1 = rawCalls.map(function (call) { return ({
2012
+ to: call === null || call === void 0 ? void 0 : call.to,
2013
+ value: (call === null || call === void 0 ? void 0 : call.value) !== undefined ? String(call.value) : undefined,
2014
+ data: call === null || call === void 0 ? void 0 : call.data,
2015
+ }); });
2016
+ var emitAll = function (status, extra) {
2017
+ calls_1.forEach(function (call, index) {
2018
+ _this.formo.transaction(__assign(__assign(__assign({ status: status, chainId: chainId || 0, address: userAddress }, (call.data && { data: call.data })), (call.to && { to: call.to })), (call.value && { value: call.value })), __assign({ batch_size: calls_1.length, batch_index: index }, extra));
2019
+ });
2020
+ };
2021
+ if (state.status === "pending") {
2022
+ // STARTED carries no batch id, exactly as a single transaction has
2023
+ // no hash yet: the wallet has not issued one.
2024
+ logger_1.logger.debug("WagmiEventHandler: sendCalls start", { calls: calls_1.length });
2025
+ emitAll(events_1.TransactionStatus.STARTED);
2026
+ }
2027
+ else if (state.status === "success") {
2028
+ var batchId = (0, batch_1.readBatchId)(state.data);
2029
+ logger_1.logger.debug("WagmiEventHandler: sendCalls broadcast", { batchId: batchId });
2030
+ emitAll(events_1.TransactionStatus.BROADCASTED, batchId ? { batch_id: batchId } : undefined);
2031
+ if (batchId) {
2032
+ this.pendingBatches.set(batchId, __assign(__assign({ address: userAddress }, (chainId !== undefined && { chainId: chainId })), { chainIdWasExplicit: explicitChainId !== undefined, calls: calls_1 }));
2033
+ // Same bound as pendingTransactions, same reason.
2034
+ if (this.pendingBatches.size > 100) {
2035
+ var keys = Array.from(this.pendingBatches.keys());
2036
+ for (var i = 0; i < 50 && i < keys.length; i++) {
2037
+ this.pendingBatches.delete(keys[i]);
2038
+ }
2039
+ }
2040
+ // The status query can have completed BEFORE this registration:
2041
+ // TanStack dispatches a mutation's success state after its
2042
+ // onSuccess callbacks, and apps await waitForCallsStatus inside
2043
+ // onSuccess. That early query event found no registration and did
2044
+ // nothing, so look for its settled result in the cache now.
2045
+ this.settleFromCachedCallsStatus(batchId);
2046
+ }
2047
+ }
2048
+ else if (state.status === "error") {
2049
+ if (isUserRejection(state.error)) {
2050
+ logger_1.logger.debug("WagmiEventHandler: sendCalls rejected");
2051
+ emitAll(events_1.TransactionStatus.REJECTED);
2052
+ }
2053
+ }
2054
+ }
2055
+ catch (error) {
2056
+ logger_1.logger.error("WagmiEventHandler: sendCalls error:", error);
2057
+ }
2058
+ };
1808
2059
  /**
1809
2060
  * Get the current Wagmi state
1810
2061
  * Supports both getState() method and direct state property access