@gearbox-protocol/sdk 15.1.0-next.10 → 15.1.0-next.11

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 (36) hide show
  1. package/dist/cjs/dev/compareOpportunities.js +45 -126
  2. package/dist/cjs/dev/comparePositions.js +183 -0
  3. package/dist/cjs/dev/fieldDiff.js +241 -0
  4. package/dist/cjs/sdk/market/math.js +8 -1
  5. package/dist/cjs/sdk/pools/PoolService.js +1 -1
  6. package/dist/cjs/sdk/positions/PositionsService.js +6 -1
  7. package/dist/esm/dev/AccountOpener.js +1 -1
  8. package/dist/esm/dev/compareOpportunities.js +44 -125
  9. package/dist/esm/dev/comparePositions.js +181 -0
  10. package/dist/esm/dev/fieldDiff.js +224 -0
  11. package/dist/esm/dev/withdrawalUtils.js +1 -1
  12. package/dist/esm/plugins/adapters/contracts/ERC4626AdapterContract.js +1 -1
  13. package/dist/esm/preview/simulate/simulatePoolOperation.js +1 -1
  14. package/dist/esm/preview/trace/extractTransfers.js +1 -1
  15. package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +2 -2
  16. package/dist/esm/sdk/accounts/liquidations/LiquidationsService.js +1 -1
  17. package/dist/esm/sdk/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
  18. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
  19. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
  20. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  21. package/dist/esm/sdk/base/TokensMeta.js +3 -3
  22. package/dist/esm/sdk/chain/detectNetwork.js +1 -1
  23. package/dist/esm/sdk/core/createAddressProvider.js +1 -1
  24. package/dist/esm/sdk/market/credit/CreditFacadeV310BaseContract.js +1 -1
  25. package/dist/esm/sdk/market/math.js +8 -1
  26. package/dist/esm/sdk/market/pool/PoolV310Contract.js +1 -1
  27. package/dist/esm/sdk/market/zapper/IETHZapperContract.js +1 -1
  28. package/dist/esm/sdk/market/zapper/ZapperContract.js +1 -1
  29. package/dist/esm/sdk/pools/PoolService.js +2 -2
  30. package/dist/esm/sdk/positions/PositionsService.js +6 -1
  31. package/dist/esm/sdk/utils/viem/simulateWithPriceUpdates.js +1 -1
  32. package/dist/types/dev/compareOpportunities.d.ts +13 -61
  33. package/dist/types/dev/comparePositions.d.ts +149 -0
  34. package/dist/types/dev/fieldDiff.d.ts +167 -0
  35. package/dist/types/sdk/market/math.d.ts +2 -0
  36. package/package.json +1 -1
@@ -2,6 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_sdk_utils_AddressMap = require("../utils/AddressMap.js");
3
3
  require("../constants/math.js");
4
4
  require("../constants/index.js");
5
+ const require_sdk_utils_hex = require("../utils/hex.js");
5
6
  require("../utils/index.js");
6
7
  const require_sdk_base_SDKConstruct = require("../base/SDKConstruct.js");
7
8
  require("../base/index.js");
@@ -147,7 +148,11 @@ var PositionsService = class extends require_sdk_base_SDKConstruct.SDKConstruct
147
148
  const { pool } = market.pool;
148
149
  const token = this.sdk.tokensMeta.mustGetToken(market.unwrappedUnderlying);
149
150
  const totalDebtValue = ca.debt + ca.accruedInterest + ca.accruedFees;
150
- const collateral = require_sdk_market_credit_dominantCollateral.dominantCollateral(ca, market);
151
+ let collateral = require_sdk_market_credit_dominantCollateral.dominantCollateral(ca, market);
152
+ if (collateral) {
153
+ const source = this.sdk.withdrawalCompressor?.getWithdrawalSourceToken(collateral);
154
+ if (source) collateral = require_sdk_utils_hex.hexEq(source, market.underlying) ? void 0 : source;
155
+ }
151
156
  const snapshot = require_sdk_positions_types.accountSnapshotFromCreditAccountData(ca);
152
157
  const borrowRate = this.borrowRate(snapshot);
153
158
  const timeToLiquidation = this.timeToLiquidation(snapshot);
@@ -1,9 +1,9 @@
1
- import { ierc20Abi } from "../abi/iERC20.js";
2
1
  import { iCreditFacadeV310Abi } from "../abi/310/generated.js";
3
2
  import { AddressMap } from "../sdk/utils/AddressMap.js";
4
3
  import { AddressSet } from "../sdk/utils/AddressSet.js";
5
4
  import { AssetsMap } from "../sdk/utils/AssetsMap.js";
6
5
  import { childLogger } from "../sdk/utils/childLogger.js";
6
+ import { ierc20Abi } from "../abi/iERC20.js";
7
7
  import "../sdk/constants/addresses.js";
8
8
  import { MAX_UINT256, PERCENTAGE_FACTOR } from "../sdk/constants/math.js";
9
9
  import { SDKConstruct } from "../sdk/base/SDKConstruct.js";
@@ -1,14 +1,15 @@
1
1
  import { opportunityId } from "../model/opportunities.js";
2
2
  import "../model/index.js";
3
+ import { countPaths, diffObjects, isAmountWithinTolerance, isBpsWithinTolerance, isUsdWithinTolerance, toCompareCounts, union, withExpected } from "./fieldDiff.js";
3
4
  //#region src/dev/compareOpportunities.ts
4
5
  /**
5
6
  * Matches two opportunity listings by {@link opportunityId} and reports every
6
7
  * field the two sources disagree on.
7
8
  *
8
- * Nothing is filtered out: a diff that is expected — a field only the backend
9
- * can fill, a formula the two sides define differently, a USD value smoothed on
10
- * one side — is reported like any other, tagged by {@link DiffKind} so that a
11
- * reader can bucket it afterwards.
9
+ * Nothing is filtered out. A field only the backend can fill, or a USD value
10
+ * that drifted within snapshot-lag noise, is still reported — tagged
11
+ * {@link FieldDiff.expected} so that {@link CompareCounts.clean} can ignore it
12
+ * while {@link CompareCounts.identical} stays strict.
12
13
  **/
13
14
  function compareOpportunities(input) {
14
15
  const onchainRows = indexById(input.onchain.data);
@@ -30,6 +31,7 @@ function compareOpportunities(input) {
30
31
  onchainName: row.name,
31
32
  offchainName: counterpart.name,
32
33
  identical: diffs.length === 0,
34
+ clean: diffs.every((diff) => diff.expected),
33
35
  diffs
34
36
  });
35
37
  }
@@ -75,142 +77,59 @@ function toRef(row) {
75
77
  * Every field two versions of one opportunity disagree on.
76
78
  **/
77
79
  function diffOpportunity(onchain, offchain) {
78
- const diffs = [];
79
- diffValue("", onchain, offchain, diffs);
80
- return diffs;
81
- }
82
- function diffValue(path, onchain, offchain, out) {
83
- if (isAbsent(onchain) && isAbsent(offchain)) return;
84
- if (isAbsent(onchain) || isAbsent(offchain)) {
85
- out.push({
86
- path,
87
- onchain,
88
- offchain,
89
- kind: "presence"
90
- });
91
- return;
92
- }
93
- if (Array.isArray(onchain) && Array.isArray(offchain)) {
94
- diffArray(path, onchain, offchain, out);
95
- return;
96
- }
97
- if (isRecord(onchain) && isRecord(offchain)) {
98
- for (const key of union(Object.keys(onchain), Object.keys(offchain))) diffValue(join(path, key), onchain[key], offchain[key], out);
99
- return;
100
- }
101
- if (!sameScalar(onchain, offchain)) out.push({
102
- path,
103
- onchain,
104
- offchain,
105
- kind: scalarKind(path, onchain)
106
- });
80
+ return diffObjects(onchain, offchain).map((diff) => tagDiff(diff, onchain.kind));
107
81
  }
108
82
  /**
109
- * Arrays whose elements identify themselves — collateral tokens, points
110
- * programs — are matched by that identity, so a token present on one side only
111
- * is reported as such rather than shifting every later element into a diff.
83
+ * Paths whose values are basis-point rates that routinely differ by ±1 from
84
+ * truncation vs rounding, plus pool `utilization` for the same reason.
112
85
  **/
113
- function diffArray(path, onchain, offchain, out) {
114
- const onchainKeyed = keyElements(onchain);
115
- const offchainKeyed = keyElements(offchain);
116
- if (!onchainKeyed || !offchainKeyed) {
117
- if (onchain.length !== offchain.length) {
118
- out.push({
119
- path,
120
- onchain,
121
- offchain,
122
- kind: "other"
123
- });
124
- return;
125
- }
126
- onchain.forEach((element, index) => {
127
- diffValue(`${path}[${index}]`, element, offchain[index], out);
128
- });
129
- return;
130
- }
131
- for (const key of union([...onchainKeyed.keys()], [...offchainKeyed.keys()])) diffValue(`${path}[${key}]`, onchainKeyed.get(key), offchainKeyed.get(key), out);
132
- }
86
+ const BPS_RATE_PATHS = /* @__PURE__ */ new Set([
87
+ "borrowApy",
88
+ "supplyApy.organicApy",
89
+ "additionalBorrowApy",
90
+ "utilization"
91
+ ]);
133
92
  /**
134
- * The array indexed by each element's own identity, or `undefined` when its
135
- * elements have none and order is all there is to go by.
93
+ * Amount fields whose bigint `value` moves with expected-liquidity accrual
94
+ * between the backend's last sync and the current block. Strategy
95
+ * `totalBorrow.value` and `maxBorrowAmount.value` are not in this set: those
96
+ * disagreements are formula bugs, not lag.
136
97
  **/
137
- function keyElements(values) {
138
- const keyed = /* @__PURE__ */ new Map();
139
- for (const value of values) {
140
- if (!isRecord(value)) return;
141
- const identity = value.address ?? value.id ?? value.token;
142
- if (typeof identity !== "string") return;
143
- keyed.set(identity.toLowerCase(), value);
144
- }
145
- return keyed.size === values.length ? keyed : void 0;
146
- }
147
- const ADDRESS = /^0x[0-9a-f]{40}$/i;
98
+ const LAG_AMOUNT_PATHS = /* @__PURE__ */ new Set(["totalSupply.value", "availableLiquidity.value"]);
148
99
  /**
149
- * Only addresses are compared case-insensitively: the backend lowercases them
150
- * while the chain hands out checksummed ones, which is not a disagreement. A
151
- * symbol or a name spelled differently is.
100
+ * Fields documented `@mode offchain` in the model: the chain has nothing to
101
+ * put there, so a presence (or nested) mismatch is expected. Strategy
102
+ * `utilization` is in this set; pool `utilization` is not.
152
103
  **/
153
- function sameScalar(onchain, offchain) {
154
- if (typeof onchain === "string" && typeof offchain === "string" && ADDRESS.test(onchain) && ADDRESS.test(offchain)) return onchain.toLowerCase() === offchain.toLowerCase();
155
- return onchain === offchain;
156
- }
157
- function scalarKind(path, onchain) {
158
- if (path.endsWith("valueUsd")) return "usd";
159
- return typeof onchain === "number" || typeof onchain === "bigint" ? "numeric" : "other";
104
+ function isModeScoped(path, kind) {
105
+ if (path === "curator.url") return true;
106
+ if (path === "totalApy" || path.endsWith(".totalApy")) return true;
107
+ if (path === "rewards" || path.startsWith("rewards[") || path.includes(".rewards[") || path.endsWith(".rewards")) return true;
108
+ if (kind !== "strategy") return false;
109
+ return path === "utilization" || path === "collateralApy" || path.startsWith("collateralApy.") || path === "maxLeverageApy" || path.startsWith("maxLeverageApy.") || path === "totalValue" || path.startsWith("totalValue.");
110
+ }
111
+ function tagDiff(diff, kind) {
112
+ if (isModeScoped(diff.path, kind)) return withExpected(diff, "mode-scoped");
113
+ if (withinTolerance(diff)) return withExpected(diff, "tolerance");
114
+ return diff;
115
+ }
116
+ function withinTolerance(diff) {
117
+ if (diff.kind === "usd") return isUsdWithinTolerance(diff.onchain, diff.offchain);
118
+ if (diff.kind !== "numeric") return false;
119
+ if (BPS_RATE_PATHS.has(diff.path)) return isBpsWithinTolerance(diff.onchain, diff.offchain);
120
+ if (LAG_AMOUNT_PATHS.has(diff.path)) return isAmountWithinTolerance(diff.onchain, diff.offchain);
121
+ return false;
160
122
  }
161
123
  function summarize(onchain, offchain, onlyOnchain, onlyOffchain, matched) {
162
124
  const byChain = union(onchain.map((row) => String(row.chainId)), offchain.map((row) => String(row.chainId))).map((chainId) => ({
163
125
  chainId: Number(chainId),
164
- ...count(onchain.filter((row) => String(row.chainId) === chainId), offchain.filter((row) => String(row.chainId) === chainId), onlyOnchain.filter((ref) => String(ref.chainId) === chainId), onlyOffchain.filter((ref) => String(ref.chainId) === chainId), matched.filter((match) => String(match.chainId) === chainId))
126
+ ...toCompareCounts(onchain.filter((row) => String(row.chainId) === chainId).length, offchain.filter((row) => String(row.chainId) === chainId).length, onlyOnchain.filter((ref) => String(ref.chainId) === chainId).length, onlyOffchain.filter((ref) => String(ref.chainId) === chainId).length, matched.filter((match) => String(match.chainId) === chainId))
165
127
  })).sort((a, b) => a.chainId - b.chainId);
166
128
  return {
167
- ...count(onchain, offchain, onlyOnchain, onlyOffchain, matched),
129
+ ...toCompareCounts(onchain.length, offchain.length, onlyOnchain.length, onlyOffchain.length, matched),
168
130
  byChain,
169
- diffsByPath: countPaths(matched)
131
+ diffsByPath: countPaths(matched.flatMap((match) => match.diffs))
170
132
  };
171
133
  }
172
- function count(onchain, offchain, onlyOnchain, onlyOffchain, matched) {
173
- const identical = matched.filter((match) => match.identical).length;
174
- return {
175
- onchainRows: onchain.length,
176
- offchainRows: offchain.length,
177
- matched: matched.length,
178
- identical,
179
- differing: matched.length - identical,
180
- onlyOnchain: onlyOnchain.length,
181
- onlyOffchain: onlyOffchain.length
182
- };
183
- }
184
- /**
185
- * How often each field differed, with array keys collapsed so that the same
186
- * field of a hundred collateral tokens counts as one path.
187
- **/
188
- function countPaths(matched) {
189
- const counts = /* @__PURE__ */ new Map();
190
- for (const match of matched) for (const diff of match.diffs) {
191
- const path = diff.path.replace(/\[[^\]]*\]/g, "[]");
192
- const entry = counts.get(path) ?? {
193
- path,
194
- kinds: [],
195
- count: 0
196
- };
197
- entry.count += 1;
198
- if (!entry.kinds.includes(diff.kind)) entry.kinds.push(diff.kind);
199
- counts.set(path, entry);
200
- }
201
- return [...counts.values()].sort((a, b) => b.count - a.count || a.path.localeCompare(b.path));
202
- }
203
- function isAbsent(value) {
204
- return value === void 0 || value === null;
205
- }
206
- function isRecord(value) {
207
- return typeof value === "object" && value !== null && !Array.isArray(value);
208
- }
209
- function union(left, right) {
210
- return [.../* @__PURE__ */ new Set([...left, ...right])];
211
- }
212
- function join(path, key) {
213
- return path ? `${path}.${key}` : key;
214
- }
215
134
  //#endregion
216
135
  export { compareOpportunities, diffOpportunity };
@@ -0,0 +1,181 @@
1
+ import { positionId } from "../model/positions.js";
2
+ import "../model/index.js";
3
+ import { USD_RELATIVE_EPSILON, asFiniteNumber, countPaths, diffObjects, isAmountWithinTolerance, isBpsWithinTolerance, isRecord, isUsdWithinTolerance, toCompareCounts, union, withExpected, withinRelative } from "./fieldDiff.js";
4
+ //#region src/dev/comparePositions.ts
5
+ /**
6
+ * Matches two position listings per wallet by {@link positionId} and reports
7
+ * every field the two sources disagree on.
8
+ *
9
+ * Nothing is filtered out. A field only one mode can fill, or a USD value that
10
+ * drifted within snapshot-lag noise, is still reported — tagged
11
+ * {@link FieldDiff.expected} so that {@link CompareCounts.clean} can ignore it
12
+ * while {@link CompareCounts.identical} stays strict.
13
+ **/
14
+ function comparePositions(input) {
15
+ const failures = input.failures ?? [];
16
+ const wallets = [...input.wallets.map(compareWallet), ...failures.map((failure) => ({
17
+ wallet: failure.wallet,
18
+ error: failure.error,
19
+ onlyOnchain: [],
20
+ onlyOffchain: [],
21
+ matched: []
22
+ }))];
23
+ wallets.sort((a, b) => a.wallet.localeCompare(b.wallet));
24
+ return {
25
+ generatedAt: input.generatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
26
+ backendUrl: input.backendUrl,
27
+ networks: [...input.networks],
28
+ onchainChains: collectChains(input.wallets, "onchain"),
29
+ offchainChains: collectChains(input.wallets, "offchain"),
30
+ summary: summarize(input.wallets, wallets, failures.length),
31
+ wallets
32
+ };
33
+ }
34
+ /**
35
+ * Every field two versions of one position disagree on.
36
+ **/
37
+ function diffPosition(onchain, offchain) {
38
+ return diffObjects(onchain, offchain, { keyOf: keyOfPositionArray }).map((diff) => tagDiff(diff, onchain.kind));
39
+ }
40
+ function compareWallet(input) {
41
+ const onchainRows = indexById(input.onchain.data);
42
+ const offchainRows = indexById(input.offchain.data);
43
+ const onlyOnchain = [];
44
+ const onlyOffchain = [];
45
+ const matched = [];
46
+ for (const [id, row] of onchainRows) {
47
+ const counterpart = offchainRows.get(id);
48
+ if (!counterpart) {
49
+ onlyOnchain.push(toRef(row));
50
+ continue;
51
+ }
52
+ const diffs = diffPosition(row, counterpart);
53
+ matched.push({
54
+ id,
55
+ kind: row.kind,
56
+ chainId: row.chainId,
57
+ onchainName: row.name,
58
+ offchainName: counterpart.name,
59
+ identical: diffs.length === 0,
60
+ clean: diffs.every((diff) => diff.expected),
61
+ diffs
62
+ });
63
+ }
64
+ for (const [id, row] of offchainRows) if (!onchainRows.has(id)) onlyOffchain.push(toRef(row));
65
+ onlyOnchain.sort((a, b) => a.id.localeCompare(b.id));
66
+ onlyOffchain.sort((a, b) => a.id.localeCompare(b.id));
67
+ matched.sort((a, b) => a.id.localeCompare(b.id));
68
+ return {
69
+ wallet: input.wallet,
70
+ onlyOnchain,
71
+ onlyOffchain,
72
+ matched
73
+ };
74
+ }
75
+ function indexById(rows) {
76
+ return new Map(rows.map((row) => [positionId(row), row]));
77
+ }
78
+ function toRef(row) {
79
+ const base = {
80
+ id: positionId(row),
81
+ kind: row.kind,
82
+ chainId: row.chainId,
83
+ name: row.name
84
+ };
85
+ switch (row.kind) {
86
+ case "pool": return {
87
+ ...base,
88
+ pool: row.pool
89
+ };
90
+ case "strategy": return {
91
+ ...base,
92
+ creditAccount: row.creditAccount,
93
+ creditManager: row.creditManager
94
+ };
95
+ case "liquidation": return base;
96
+ }
97
+ }
98
+ /**
99
+ * `collaterals[]` is keyed by the collateral token, not by a top-level
100
+ * address. Rewards-points programs already identify themselves by `id`.
101
+ **/
102
+ function keyOfPositionArray(path, value) {
103
+ if (path !== "collaterals" || !isRecord(value) || !isRecord(value.collateral)) return;
104
+ const token = value.collateral.token;
105
+ return isRecord(token) && typeof token.address === "string" ? token.address : void 0;
106
+ }
107
+ const BPS_RATE_PATHS = /* @__PURE__ */ new Set([
108
+ "borrowApy",
109
+ "apy.organicApy",
110
+ "healthFactor"
111
+ ]);
112
+ /**
113
+ * Amount fields whose bigint `value` moves with interest accrual between the
114
+ * backend's last sync and the current block.
115
+ **/
116
+ function isLagAmountPath(path) {
117
+ return path === "totalDebt.value" || path === "totalValue.value" || path === "netValue.value" || path.endsWith(".collateral.value") || path.endsWith(".quota.value");
118
+ }
119
+ /**
120
+ * Fields documented `@mode offchain` or `@mode onchain` in the model.
121
+ **/
122
+ function isModeScoped(path, kind) {
123
+ if (path === "pnl" || path.startsWith("pnl.")) return true;
124
+ if (kind === "pool") return path === "apy.totalApy" || path.startsWith("apy.rewards");
125
+ if (kind === "strategy") return path === "netApy" || path.startsWith("netApy.") || path === "borrowRate" || path.startsWith("borrowRate.") || path === "timeToLiquidation" || path === "liquidationPrice";
126
+ return false;
127
+ }
128
+ function tagDiff(diff, kind) {
129
+ if (isModeScoped(diff.path, kind)) return withExpected(diff, "mode-scoped");
130
+ if (withinTolerance(diff)) return withExpected(diff, "tolerance");
131
+ return diff;
132
+ }
133
+ function withinTolerance(diff) {
134
+ if (diff.kind === "usd") return isUsdWithinTolerance(diff.onchain, diff.offchain);
135
+ if (diff.kind !== "numeric") return false;
136
+ if (diff.path === "leverage") return withinRelative(asFiniteNumber(diff.onchain), asFiniteNumber(diff.offchain), USD_RELATIVE_EPSILON);
137
+ if (BPS_RATE_PATHS.has(diff.path)) return isBpsWithinTolerance(diff.onchain, diff.offchain);
138
+ if (isLagAmountPath(diff.path)) return isAmountWithinTolerance(diff.onchain, diff.offchain);
139
+ return false;
140
+ }
141
+ function summarize(inputs, wallets, failed) {
142
+ const compared = wallets.filter((wallet) => !wallet.error);
143
+ const allOnchain = inputs.flatMap((input) => input.onchain.data);
144
+ const allOffchain = inputs.flatMap((input) => input.offchain.data);
145
+ const onlyOnchain = compared.flatMap((wallet) => wallet.onlyOnchain);
146
+ const onlyOffchain = compared.flatMap((wallet) => wallet.onlyOffchain);
147
+ const matched = compared.flatMap((wallet) => wallet.matched);
148
+ const byChain = union(allOnchain.map((row) => String(row.chainId)), allOffchain.map((row) => String(row.chainId))).map((chainId) => ({
149
+ chainId: Number(chainId),
150
+ ...toCompareCounts(allOnchain.filter((row) => String(row.chainId) === chainId).length, allOffchain.filter((row) => String(row.chainId) === chainId).length, onlyOnchain.filter((ref) => String(ref.chainId) === chainId).length, onlyOffchain.filter((ref) => String(ref.chainId) === chainId).length, matched.filter((match) => String(match.chainId) === chainId))
151
+ })).sort((a, b) => a.chainId - b.chainId);
152
+ const byWallet = wallets.map((wallet) => ({
153
+ wallet: wallet.wallet,
154
+ ...wallet.error ? { error: wallet.error } : {},
155
+ ...toCompareCounts(wallet.matched.length + wallet.onlyOnchain.length, wallet.matched.length + wallet.onlyOffchain.length, wallet.onlyOnchain.length, wallet.onlyOffchain.length, wallet.matched)
156
+ }));
157
+ const walletsClean = compared.filter((wallet) => wallet.onlyOnchain.length === 0 && wallet.onlyOffchain.length === 0 && wallet.matched.every((match) => match.clean)).length;
158
+ return {
159
+ ...toCompareCounts(allOnchain.length, allOffchain.length, onlyOnchain.length, onlyOffchain.length, matched),
160
+ wallets: wallets.length,
161
+ walletsClean,
162
+ walletsFailed: failed,
163
+ byChain,
164
+ byWallet,
165
+ diffsByPath: countPaths(matched.flatMap((match) => match.diffs))
166
+ };
167
+ }
168
+ /**
169
+ * One metadata entry per chain, preferring a success so the report names the
170
+ * block. Later wallets of the same chain are ignored.
171
+ **/
172
+ function collectChains(wallets, side) {
173
+ const byChain = /* @__PURE__ */ new Map();
174
+ for (const wallet of wallets) for (const chain of wallet[side].meta.chains) {
175
+ const existing = byChain.get(chain.chainId);
176
+ if (!existing || existing.status !== "success" && chain.status === "success") byChain.set(chain.chainId, chain);
177
+ }
178
+ return [...byChain.values()].sort((a, b) => a.chainId - b.chainId);
179
+ }
180
+ //#endregion
181
+ export { comparePositions, diffPosition };
@@ -0,0 +1,224 @@
1
+ //#region src/dev/fieldDiff.ts
2
+ /**
3
+ * Relative drift allowed on {@link Amount.valueUsd} before a USD float is a
4
+ * real disagreement: 0.1%.
5
+ **/
6
+ const USD_RELATIVE_EPSILON = .001;
7
+ /**
8
+ * Relative drift allowed on lag-bounded bigint amounts: 0.05%.
9
+ **/
10
+ const AMOUNT_RELATIVE_EPSILON = 5e-4;
11
+ /**
12
+ * Absolute drift allowed on bps rates before rounding and a one-block lag are
13
+ * no longer enough to explain it.
14
+ **/
15
+ const BPS_ABSOLUTE_EPSILON = 1;
16
+ /**
17
+ * Every field two versions of one value disagree on. Nothing is filtered or
18
+ * tagged: the caller marks expected diffs afterwards.
19
+ **/
20
+ function diffValue(path, onchain, offchain, out, options) {
21
+ if (isAbsent(onchain) && isAbsent(offchain)) return;
22
+ if (isAbsent(onchain) || isAbsent(offchain)) {
23
+ out.push({
24
+ path,
25
+ onchain,
26
+ offchain,
27
+ kind: "presence"
28
+ });
29
+ return;
30
+ }
31
+ if (Array.isArray(onchain) && Array.isArray(offchain)) {
32
+ diffArray(path, onchain, offchain, out, options);
33
+ return;
34
+ }
35
+ if (isRecord(onchain) && isRecord(offchain)) {
36
+ for (const key of union(Object.keys(onchain), Object.keys(offchain))) diffValue(join(path, key), onchain[key], offchain[key], out, options);
37
+ return;
38
+ }
39
+ if (!sameScalar(onchain, offchain)) out.push({
40
+ path,
41
+ onchain,
42
+ offchain,
43
+ kind: scalarKind(path, onchain)
44
+ });
45
+ }
46
+ /**
47
+ * Deep-diff two values and return the disagreements, in path order of
48
+ * discovery.
49
+ **/
50
+ function diffObjects(onchain, offchain, options) {
51
+ const diffs = [];
52
+ diffValue("", onchain, offchain, diffs, options);
53
+ return diffs;
54
+ }
55
+ /**
56
+ * Mark a diff expected, so a later `clean` count can ignore it.
57
+ **/
58
+ function withExpected(diff, reason) {
59
+ return {
60
+ ...diff,
61
+ expected: true,
62
+ reason
63
+ };
64
+ }
65
+ /**
66
+ * How often each field differed, with array keys collapsed so that the same
67
+ * field of a hundred collateral tokens counts as one path. Sorted so the
68
+ * unexpected disagreements come first.
69
+ **/
70
+ function countPaths(diffs) {
71
+ const counts = /* @__PURE__ */ new Map();
72
+ for (const diff of diffs) {
73
+ const path = collapseArrayKeys(diff.path);
74
+ const entry = counts.get(path) ?? {
75
+ path,
76
+ kinds: [],
77
+ count: 0,
78
+ expected: 0,
79
+ unexpected: 0
80
+ };
81
+ entry.count += 1;
82
+ if (diff.expected) entry.expected += 1;
83
+ else entry.unexpected += 1;
84
+ if (!entry.kinds.includes(diff.kind)) entry.kinds.push(diff.kind);
85
+ counts.set(path, entry);
86
+ }
87
+ return [...counts.values()].sort((a, b) => b.unexpected - a.unexpected || b.count - a.count || a.path.localeCompare(b.path));
88
+ }
89
+ /**
90
+ * Collapse `collateralTokens[0xa0b8...].symbol` to `collateralTokens[].symbol`.
91
+ **/
92
+ function collapseArrayKeys(path) {
93
+ return path.replace(/\[[^\]]*\]/g, "[]");
94
+ }
95
+ /**
96
+ * Membership and match totals of one comparison, from already-built lists.
97
+ **/
98
+ function toCompareCounts(onchainRows, offchainRows, onlyOnchain, onlyOffchain, matched) {
99
+ const identical = matched.filter((match) => match.identical).length;
100
+ const clean = matched.filter((match) => match.clean).length;
101
+ return {
102
+ onchainRows,
103
+ offchainRows,
104
+ matched: matched.length,
105
+ identical,
106
+ clean,
107
+ differing: matched.length - identical,
108
+ onlyOnchain,
109
+ onlyOffchain
110
+ };
111
+ }
112
+ /**
113
+ * USD floats within {@link USD_RELATIVE_EPSILON}.
114
+ **/
115
+ function isUsdWithinTolerance(onchain, offchain) {
116
+ return withinRelative(asFiniteNumber(onchain), asFiniteNumber(offchain), USD_RELATIVE_EPSILON);
117
+ }
118
+ /**
119
+ * Bps rates that differ by at most {@link BPS_ABSOLUTE_EPSILON}.
120
+ **/
121
+ function isBpsWithinTolerance(onchain, offchain) {
122
+ const left = asFiniteNumber(onchain);
123
+ const right = asFiniteNumber(offchain);
124
+ return left !== void 0 && right !== void 0 && Math.abs(left - right) <= 1;
125
+ }
126
+ /**
127
+ * Bigint amounts within {@link AMOUNT_RELATIVE_EPSILON}.
128
+ **/
129
+ function isAmountWithinTolerance(onchain, offchain) {
130
+ return typeof onchain === "bigint" && typeof offchain === "bigint" && withinRelativeBigint(onchain, offchain, 5e-4);
131
+ }
132
+ /**
133
+ * Finite numbers within a relative epsilon of each other.
134
+ **/
135
+ function withinRelative(onchain, offchain, epsilon) {
136
+ if (onchain === void 0 || offchain === void 0) return false;
137
+ const scale = Math.max(Math.abs(onchain), Math.abs(offchain));
138
+ return scale === 0 ? true : Math.abs(onchain - offchain) / scale <= epsilon;
139
+ }
140
+ /**
141
+ * `diff / max(|a|, |b|) <= epsilon`, computed in integer arithmetic so a
142
+ * 1e18-scale amount does not round through `Number`.
143
+ **/
144
+ function withinRelativeBigint(onchain, offchain, epsilon) {
145
+ if (onchain === offchain) return true;
146
+ const diff = onchain > offchain ? onchain - offchain : offchain - onchain;
147
+ const scale = abs(onchain) > abs(offchain) ? abs(onchain) : abs(offchain);
148
+ if (scale === 0n) return true;
149
+ return diff * BigInt(Math.round(1 / epsilon)) <= scale;
150
+ }
151
+ function asFiniteNumber(value) {
152
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
153
+ }
154
+ function union(left, right) {
155
+ return [.../* @__PURE__ */ new Set([...left, ...right])];
156
+ }
157
+ function isRecord(value) {
158
+ return typeof value === "object" && value !== null && !Array.isArray(value);
159
+ }
160
+ function diffArray(path, onchain, offchain, out, options) {
161
+ const onchainKeyed = keyElements(path, onchain, options?.keyOf);
162
+ const offchainKeyed = keyElements(path, offchain, options?.keyOf);
163
+ if (!onchainKeyed || !offchainKeyed) {
164
+ if (onchain.length !== offchain.length) {
165
+ out.push({
166
+ path,
167
+ onchain,
168
+ offchain,
169
+ kind: "other"
170
+ });
171
+ return;
172
+ }
173
+ onchain.forEach((element, index) => {
174
+ diffValue(`${path}[${index}]`, element, offchain[index], out, options);
175
+ });
176
+ return;
177
+ }
178
+ for (const key of union([...onchainKeyed.keys()], [...offchainKeyed.keys()])) diffValue(`${path}[${key}]`, onchainKeyed.get(key), offchainKeyed.get(key), out, options);
179
+ }
180
+ /**
181
+ * The array indexed by each element's own identity, or `undefined` when its
182
+ * elements have none and order is all there is to go by.
183
+ **/
184
+ function keyElements(path, values, keyOf) {
185
+ const keyed = /* @__PURE__ */ new Map();
186
+ for (const value of values) {
187
+ const identity = keyOf?.(path, value) ?? defaultIdentity(value);
188
+ if (typeof identity !== "string") return;
189
+ keyed.set(identity.toLowerCase(), value);
190
+ }
191
+ return keyed.size === values.length ? keyed : void 0;
192
+ }
193
+ function defaultIdentity(value) {
194
+ if (!isRecord(value)) return;
195
+ if (typeof value.address === "string") return value.address;
196
+ if (typeof value.id === "string") return value.id;
197
+ if (typeof value.token === "string") return value.token;
198
+ if (isRecord(value.token) && typeof value.token.address === "string") return value.token.address;
199
+ }
200
+ const ADDRESS = /^0x[0-9a-f]{40}$/i;
201
+ /**
202
+ * Only addresses are compared case-insensitively: the backend lowercases them
203
+ * while the chain hands out checksummed ones, which is not a disagreement. A
204
+ * symbol or a name spelled differently is.
205
+ **/
206
+ function sameScalar(onchain, offchain) {
207
+ if (typeof onchain === "string" && typeof offchain === "string" && ADDRESS.test(onchain) && ADDRESS.test(offchain)) return onchain.toLowerCase() === offchain.toLowerCase();
208
+ return onchain === offchain;
209
+ }
210
+ function scalarKind(path, onchain) {
211
+ if (path.endsWith("valueUsd")) return "usd";
212
+ return typeof onchain === "number" || typeof onchain === "bigint" ? "numeric" : "other";
213
+ }
214
+ function isAbsent(value) {
215
+ return value === void 0 || value === null;
216
+ }
217
+ function join(path, key) {
218
+ return path ? `${path}.${key}` : key;
219
+ }
220
+ function abs(value) {
221
+ return value < 0n ? -value : value;
222
+ }
223
+ //#endregion
224
+ export { AMOUNT_RELATIVE_EPSILON, BPS_ABSOLUTE_EPSILON, USD_RELATIVE_EPSILON, asFiniteNumber, collapseArrayKeys, countPaths, diffObjects, diffValue, isAmountWithinTolerance, isBpsWithinTolerance, isRecord, isUsdWithinTolerance, toCompareCounts, union, withExpected, withinRelative, withinRelativeBigint };
@@ -1,6 +1,6 @@
1
- import { iWithdrawalCompressorV313Abi } from "../abi/IWithdrawalCompressorV313.js";
2
1
  import { getNetworkType } from "../sdk/chain/chains.js";
3
2
  import { getWithdrawalCompressorAddress } from "../sdk/accounts/withdrawal-compressor/addresses.js";
3
+ import { iWithdrawalCompressorV313Abi } from "../abi/IWithdrawalCompressorV313.js";
4
4
  import "../sdk/index.js";
5
5
  import { iMidasDataFeedAbi, iMidasRedemptionVaultAbi, midasGatewayAbi, midasRedeemerAbi, midasRedemptionVaultPhantomTokenAbi, securitizeRedeemerAbi, securitizeRedemptionGatewayAbi, securitizeRedemptionPhantomTokenAbi } from "./withdrawalAbi.js";
6
6
  import { erc20Abi, hexToString, parseAbi, parseEther } from "viem";
@@ -1,5 +1,5 @@
1
- import { ierc4626AdapterAbi } from "../../../abi/ierc4626Adapter.js";
2
1
  import { MissingSerializedParamsError } from "../../../sdk/base/errors.js";
2
+ import { ierc4626AdapterAbi } from "../../../abi/ierc4626Adapter.js";
3
3
  import "../../../sdk/index.js";
4
4
  import { fnSigToName, swapFromTransfers } from "../transferHelpers.js";
5
5
  import { AbstractAdapterContract } from "./AbstractAdapter.js";
@@ -1,5 +1,5 @@
1
- import { iZapperAbi } from "../../abi/iZapper.js";
2
1
  import { iPoolV310Abi } from "../../abi/310/generated.js";
2
+ import { iZapperAbi } from "../../abi/iZapper.js";
3
3
  import { asPreviewSimulationError } from "./errors.js";
4
4
  //#region src/preview/simulate/simulatePoolOperation.ts
5
5
  function previewRead(operation) {