@gearbox-protocol/sdk 16.0.0-next.54 → 16.0.0-next.55

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/dev/mode-parity/compareOpportunities.js +3 -4
  2. package/dist/cjs/dev/mode-parity/comparePositions.js +5 -6
  3. package/dist/cjs/dev/mode-parity/fieldDiff.js +4 -6
  4. package/dist/cjs/dev/mode-parity/scriptUtils.js +145 -5
  5. package/dist/cjs/rewards/errors.js +27 -0
  6. package/dist/cjs/rewards/index.js +6 -7
  7. package/dist/cjs/rewards/merkl-api.js +45 -0
  8. package/dist/cjs/rewards/multichain.js +40 -0
  9. package/dist/cjs/rewards/{rewards/api.js → toMerklRewards.js} +26 -28
  10. package/dist/esm/dev/mode-parity/compareOpportunities.js +3 -4
  11. package/dist/esm/dev/mode-parity/comparePositions.js +5 -6
  12. package/dist/esm/dev/mode-parity/fieldDiff.js +4 -6
  13. package/dist/esm/dev/mode-parity/scriptUtils.js +142 -6
  14. package/dist/esm/rewards/errors.js +26 -0
  15. package/dist/esm/rewards/index.js +4 -5
  16. package/dist/esm/rewards/merkl-api.js +42 -0
  17. package/dist/esm/rewards/multichain.js +39 -0
  18. package/dist/esm/rewards/{rewards/api.js → toMerklRewards.js} +26 -28
  19. package/dist/types/dev/mode-parity/compareOpportunities.d.ts +3 -7
  20. package/dist/types/dev/mode-parity/comparePositions.d.ts +4 -8
  21. package/dist/types/dev/mode-parity/fieldDiff.d.ts +9 -8
  22. package/dist/types/dev/mode-parity/scriptUtils.d.ts +26 -1
  23. package/dist/types/rewards/errors.d.ts +18 -0
  24. package/dist/types/rewards/index.d.ts +4 -7
  25. package/dist/types/rewards/merkl-api.d.ts +64 -0
  26. package/dist/types/rewards/multichain.d.ts +33 -0
  27. package/dist/types/rewards/toMerklRewards.d.ts +42 -0
  28. package/package.json +1 -3
  29. package/dist/cjs/_virtual/_rolldown/runtime.js +0 -23
  30. package/dist/cjs/rewards/apy/index.js +0 -3
  31. package/dist/cjs/rewards/apy/output-details.js +0 -1
  32. package/dist/cjs/rewards/apy/output.js +0 -1
  33. package/dist/cjs/rewards/rewards/common.js +0 -1
  34. package/dist/cjs/rewards/rewards/extra-apy.js +0 -71
  35. package/dist/cjs/rewards/rewards/index.js +0 -6
  36. package/dist/cjs/rewards/rewards/merkl-api.js +0 -22
  37. package/dist/esm/rewards/apy/index.js +0 -3
  38. package/dist/esm/rewards/apy/output-details.js +0 -1
  39. package/dist/esm/rewards/apy/output.js +0 -1
  40. package/dist/esm/rewards/rewards/common.js +0 -1
  41. package/dist/esm/rewards/rewards/extra-apy.js +0 -67
  42. package/dist/esm/rewards/rewards/index.js +0 -3
  43. package/dist/esm/rewards/rewards/merkl-api.js +0 -19
  44. package/dist/types/rewards/apy/index.d.ts +0 -3
  45. package/dist/types/rewards/apy/output-details.d.ts +0 -99
  46. package/dist/types/rewards/apy/output.d.ts +0 -25
  47. package/dist/types/rewards/rewards/api.d.ts +0 -60
  48. package/dist/types/rewards/rewards/common.d.ts +0 -9
  49. package/dist/types/rewards/rewards/extra-apy.d.ts +0 -37
  50. package/dist/types/rewards/rewards/index.d.ts +0 -3
  51. package/dist/types/rewards/rewards/merkl-api.d.ts +0 -54
@@ -15,8 +15,8 @@ const tagDiff = require_dev_mode_parity_compareRules.makeTagDiff({
15
15
  *
16
16
  * Nothing is filtered out. A field only the backend can fill, or a USD value
17
17
  * that drifted within snapshot-lag noise, is still reported — tagged
18
- * {@link FieldDiff.expected} so that {@link CompareCounts.clean} can ignore it
19
- * while {@link CompareCounts.identical} stays strict.
18
+ * {@link FieldDiff.expected} so that {@link CompareCounts.similar} can ignore
19
+ * it.
20
20
  **/
21
21
  function compareOpportunities(input) {
22
22
  const onchainRows = indexById(input.onchain.data);
@@ -37,8 +37,7 @@ function compareOpportunities(input) {
37
37
  chainId: row.chainId,
38
38
  onchainName: row.name,
39
39
  offchainName: counterpart.name,
40
- identical: diffs.length === 0,
41
- clean: diffs.every((diff) => diff.expected),
40
+ similar: diffs.every((diff) => diff.expected),
42
41
  diffs
43
42
  });
44
43
  }
@@ -18,8 +18,8 @@ const tagDiff = require_dev_mode_parity_compareRules.makeTagDiff({
18
18
  * Nothing is filtered out. A field only one mode can fill, a strategy field
19
19
  * both-mode merge overlays from the backend, or a USD value that drifted
20
20
  * within snapshot-lag noise, is still reported — tagged
21
- * {@link FieldDiff.expected} so that {@link CompareCounts.clean} can ignore it
22
- * while {@link CompareCounts.identical} stays strict.
21
+ * {@link FieldDiff.expected} so that {@link CompareCounts.similar} can ignore
22
+ * it.
23
23
  **/
24
24
  function comparePositions(input) {
25
25
  const failures = input.failures ?? [];
@@ -66,8 +66,7 @@ function compareWallet(input) {
66
66
  chainId: row.chainId,
67
67
  onchainName: row.name,
68
68
  offchainName: counterpart.name,
69
- identical: diffs.length === 0,
70
- clean: diffs.every((diff) => diff.expected),
69
+ similar: diffs.every((diff) => diff.expected),
71
70
  diffs
72
71
  });
73
72
  }
@@ -130,11 +129,11 @@ function summarize(inputs, wallets, failed) {
130
129
  ...wallet.error ? { error: wallet.error } : {},
131
130
  ...require_dev_mode_parity_fieldDiff.toCompareCounts(wallet.matched.length + wallet.onlyOnchain.length, wallet.matched.length + wallet.onlyOffchain.length, wallet.onlyOnchain.length, wallet.onlyOffchain.length, wallet.matched)
132
131
  }));
133
- const walletsClean = compared.filter((wallet) => wallet.onlyOnchain.length === 0 && wallet.onlyOffchain.length === 0 && wallet.matched.every((match) => match.clean)).length;
132
+ const walletsSimilar = compared.filter((wallet) => wallet.onlyOnchain.length === 0 && wallet.onlyOffchain.length === 0 && wallet.matched.every((match) => match.similar)).length;
134
133
  return {
135
134
  ...require_dev_mode_parity_fieldDiff.toCompareCounts(allOnchain.length, allOffchain.length, onlyOnchain.length, onlyOffchain.length, matched),
136
135
  wallets: wallets.length,
137
- walletsClean,
136
+ walletsSimilar,
138
137
  walletsFailed: failed,
139
138
  byChain,
140
139
  byWallet,
@@ -54,7 +54,7 @@ function diffObjects(onchain, offchain, options) {
54
54
  return diffs;
55
55
  }
56
56
  /**
57
- * Mark a diff expected, so a later `clean` count can ignore it.
57
+ * Mark a diff expected, so a later `similar` count can ignore it.
58
58
  **/
59
59
  function withExpected(diff, reason) {
60
60
  return {
@@ -118,15 +118,13 @@ function collapseArrayKeys(path) {
118
118
  * Membership and match totals of one comparison, from already-built lists.
119
119
  **/
120
120
  function toCompareCounts(onchainRows, offchainRows, onlyOnchain, onlyOffchain, matched) {
121
- const identical = matched.filter((match) => match.identical).length;
122
- const clean = matched.filter((match) => match.clean).length;
121
+ const similar = matched.filter((match) => match.similar).length;
123
122
  return {
124
123
  onchainRows,
125
124
  offchainRows,
126
125
  matched: matched.length,
127
- identical,
128
- clean,
129
- differing: matched.length - identical,
126
+ similar,
127
+ different: matched.length - similar,
130
128
  onlyOnchain,
131
129
  onlyOffchain
132
130
  };
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_dev_providers = require("../providers.js");
3
+ let node_fs = require("node:fs");
3
4
  let pino = require("pino");
4
5
  //#region src/dev/mode-parity/scriptUtils.ts
5
6
  const NETWORKS = [
@@ -77,6 +78,40 @@ function worstColumns(worst) {
77
78
  };
78
79
  }
79
80
  /**
81
+ * Reasons a compare run should fail CI: unexpected membership or field diffs,
82
+ * both sources empty, a chain that could not be read, or wallets that failed
83
+ * to list. Expected diffs (mode-scoped, backend-preferred, tolerance) do not
84
+ * fail the run.
85
+ **/
86
+ function evaluateCompareFailure(report) {
87
+ const { summary } = report;
88
+ const reasons = [];
89
+ if (summary.onchainRows === 0 && summary.offchainRows === 0) reasons.push("both sources produced no data");
90
+ if (summary.different > 0) reasons.push(`${summary.different} matched rows are different`);
91
+ if (summary.onlyOnchain > 0) reasons.push(`${summary.onlyOnchain} rows only onchain`);
92
+ if (summary.onlyOffchain > 0) reasons.push(`${summary.onlyOffchain} rows only offchain`);
93
+ if ((summary.walletsFailed ?? 0) > 0) reasons.push(`${summary.walletsFailed} wallets failed to list`);
94
+ for (const chain of [...report.onchainChains, ...report.offchainChains]) if (chain.status === "error") reasons.push(`chain ${chain.chainId} failed on ${chain.source ?? "unknown"}: ${errorMessage(chain.error)}`);
95
+ return reasons;
96
+ }
97
+ function splitDiffs(summary) {
98
+ return {
99
+ unexpected: summary.diffsByPath.filter((entry) => entry.unexpected > 0),
100
+ expected: summary.diffsByPath.filter((entry) => entry.unexpected === 0 && entry.expected > 0)
101
+ };
102
+ }
103
+ function markdownCell(value) {
104
+ return String(value).replaceAll("|", "\\|").replaceAll("\n", " ");
105
+ }
106
+ function markdownTable(headers, rows) {
107
+ const line = (cells) => `| ${cells.map(markdownCell).join(" | ")} |`;
108
+ return [
109
+ line(headers),
110
+ line(headers.map(() => "---")),
111
+ ...rows.map(line)
112
+ ].join("\n");
113
+ }
114
+ /**
80
115
  * Prints the shared membership table, the fields that differed most often,
81
116
  * and any chain that failed to answer.
82
117
  **/
@@ -88,15 +123,13 @@ function printCompareSummary(noun, report, extraLines = []) {
88
123
  onchain: chain.onchainRows,
89
124
  offchain: chain.offchainRows,
90
125
  matched: chain.matched,
91
- identical: chain.identical,
92
- clean: chain.clean,
93
- differing: chain.differing,
126
+ similar: chain.similar,
127
+ different: chain.different,
94
128
  "only onchain": chain.onlyOnchain,
95
129
  "only offchain": chain.onlyOffchain
96
130
  })));
97
131
  for (const line of extraLines) console.log(line);
98
- const unexpected = summary.diffsByPath.filter((entry) => entry.unexpected > 0);
99
- const expected = summary.diffsByPath.filter((entry) => entry.unexpected === 0 && entry.expected > 0);
132
+ const { unexpected, expected } = splitDiffs(summary);
100
133
  if (unexpected.length) {
101
134
  console.log("\nunexpected fields that differed most often:");
102
135
  console.table(unexpected.slice(0, 25).map((entry) => ({
@@ -118,14 +151,121 @@ function printCompareSummary(noun, report, extraLines = []) {
118
151
  }
119
152
  for (const chain of [...report.onchainChains, ...report.offchainChains]) if (chain.status === "error") console.log(`chain ${chain.chainId} failed on ${chain.source}:`, chain.error);
120
153
  }
154
+ /**
155
+ * Markdown of the same summary printed to the console, for GitHub job summaries.
156
+ **/
157
+ function formatCompareMarkdown(noun, report, extraLines = [], reasons = []) {
158
+ const { summary } = report;
159
+ const { unexpected, expected } = splitDiffs(summary);
160
+ const parts = [
161
+ `# ${noun} compare`,
162
+ "",
163
+ reasons.length ? "**Failed**" : "**Passed**",
164
+ "",
165
+ `${noun} from \`${report.backendUrl}\` vs the chain`,
166
+ ""
167
+ ];
168
+ if (reasons.length) {
169
+ parts.push("## Failures", "");
170
+ for (const reason of reasons) parts.push(`- ${reason}`);
171
+ parts.push("");
172
+ }
173
+ if (extraLines.length) {
174
+ for (const line of extraLines) parts.push(line);
175
+ parts.push("");
176
+ }
177
+ if (summary.byChain.length) parts.push(markdownTable([
178
+ "chain",
179
+ "onchain",
180
+ "offchain",
181
+ "matched",
182
+ "similar",
183
+ "different",
184
+ "only onchain",
185
+ "only offchain"
186
+ ], summary.byChain.map((chain) => [
187
+ chain.chainId,
188
+ chain.onchainRows,
189
+ chain.offchainRows,
190
+ chain.matched,
191
+ chain.similar,
192
+ chain.different,
193
+ chain.onlyOnchain,
194
+ chain.onlyOffchain
195
+ ])), "");
196
+ if (unexpected.length) parts.push("## Unexpected fields that differed most often", "", markdownTable([
197
+ "field",
198
+ "unexpected",
199
+ "expected",
200
+ "kinds",
201
+ "max diff",
202
+ "worst entity"
203
+ ], unexpected.slice(0, 25).map((entry) => {
204
+ const worst = worstColumns(entry.worstUnexpected);
205
+ return [
206
+ entry.path,
207
+ entry.unexpected,
208
+ entry.expected,
209
+ entry.kinds.join(", "),
210
+ worst["max diff"],
211
+ worst["worst entity"]
212
+ ];
213
+ })), "");
214
+ if (expected.length) parts.push("## Expected fields (mode-scoped, backend-preferred, or within tolerance)", "", markdownTable([
215
+ "field",
216
+ "rows",
217
+ "kinds",
218
+ "max diff",
219
+ "worst entity"
220
+ ], expected.slice(0, 25).map((entry) => {
221
+ const worst = worstColumns(entry.worstExpected);
222
+ return [
223
+ entry.path,
224
+ entry.expected,
225
+ entry.kinds.join(", "),
226
+ worst["max diff"],
227
+ worst["worst entity"]
228
+ ];
229
+ })), "");
230
+ const failedChains = [...report.onchainChains, ...report.offchainChains].filter((chain) => chain.status === "error");
231
+ if (failedChains.length) {
232
+ parts.push("## Chain errors", "");
233
+ for (const chain of failedChains) parts.push(`- chain ${chain.chainId} failed on ${chain.source ?? "unknown"}: ${errorMessage(chain.error)}`);
234
+ parts.push("");
235
+ }
236
+ return parts.join("\n");
237
+ }
238
+ /**
239
+ * Appends {@link formatCompareMarkdown} to `GITHUB_STEP_SUMMARY` when running
240
+ * in GitHub Actions. No-op locally.
241
+ **/
242
+ function writeGithubJobSummary(noun, report, extraLines = [], reasons = []) {
243
+ const path = process.env.GITHUB_STEP_SUMMARY;
244
+ if (!path) return;
245
+ (0, node_fs.appendFileSync)(path, `${formatCompareMarkdown(noun, report, extraLines, reasons)}\n`);
246
+ }
247
+ /**
248
+ * Console + job-summary output for a compare run. Returns the failure reasons
249
+ * so the caller can exit 1 when the report is not similar.
250
+ **/
251
+ function reportCompare(noun, report, extraLines = []) {
252
+ printCompareSummary(noun, report, extraLines);
253
+ const reasons = evaluateCompareFailure(report);
254
+ writeGithubJobSummary(noun, report, extraLines, reasons);
255
+ return reasons;
256
+ }
121
257
  //#endregion
122
258
  exports.BACKEND_URL = BACKEND_URL;
123
259
  exports.NETWORKS = NETWORKS;
124
260
  exports.TIMEOUT = TIMEOUT;
125
261
  exports.createLogger = createLogger;
126
262
  exports.errorMessage = errorMessage;
263
+ exports.evaluateCompareFailure = evaluateCompareFailure;
127
264
  exports.formatBpsAsPercent = formatBpsAsPercent;
265
+ exports.formatCompareMarkdown = formatCompareMarkdown;
128
266
  exports.mapPool = mapPool;
129
267
  exports.printCompareSummary = printCompareSummary;
268
+ exports.reportCompare = reportCompare;
130
269
  exports.requireEnv = requireEnv;
131
270
  exports.rpcUrls = rpcUrls;
271
+ exports.writeGithubJobSummary = writeGithubJobSummary;
@@ -0,0 +1,27 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let viem = require("viem");
3
+ //#region src/rewards/errors.ts
4
+ /**
5
+ * Thrown when none of Merkl's domains answered for a chain.
6
+ *
7
+ * Everything a reader needs is in the message: this error travels to consumers
8
+ * inside a chain's {@link ChainFailed} metadata, where it is typed `unknown`
9
+ * and may be serialised by something that turns an arbitrary object into `{}`.
10
+ */
11
+ var MerklRequestFailedError = class extends viem.BaseError {
12
+ name = "MerklRequestFailedError";
13
+ chainId;
14
+ constructor(chainId, path, attempts) {
15
+ super(`Merkl could not be reached for chain ${chainId}.`, {
16
+ cause: attempts.find(([, c]) => c instanceof Error)?.[1],
17
+ metaMessages: attempts.map(([domain, cause]) => `${domain}${path} — ${describe(cause)}`)
18
+ });
19
+ this.chainId = chainId;
20
+ }
21
+ };
22
+ function describe(cause) {
23
+ if (cause instanceof Error) return cause.name === "TimeoutError" ? "timed out" : cause.message;
24
+ return String(cause);
25
+ }
26
+ //#endregion
27
+ exports.MerklRequestFailedError = MerklRequestFailedError;
@@ -1,8 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- require("./apy/index.js");
3
- const require_rewards_rewards_api = require("./rewards/api.js");
4
- const require_rewards_rewards_extra_apy = require("./rewards/extra-apy.js");
5
- require("./rewards/index.js");
6
- exports.PoolPointsAPI = require_rewards_rewards_extra_apy.PoolPointsAPI;
7
- exports.getKeyForPoolPointsInfo = require_rewards_rewards_extra_apy.getKeyForPoolPointsInfo;
8
- exports.getMerklRewards = require_rewards_rewards_api.getMerklRewards;
2
+ const require_rewards_errors = require("./errors.js");
3
+ const require_rewards_toMerklRewards = require("./toMerklRewards.js");
4
+ const require_rewards_multichain = require("./multichain.js");
5
+ exports.MerklRequestFailedError = require_rewards_errors.MerklRequestFailedError;
6
+ exports.getMerklRewardsMultichain = require_rewards_multichain.getMerklRewardsMultichain;
7
+ exports.toMerklRewards = require_rewards_toMerklRewards.toMerklRewards;
@@ -0,0 +1,45 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_rewards_errors = require("./errors.js");
3
+ //#region src/rewards/merkl-api.ts
4
+ /**
5
+ * Merkl's own host and the Angle mirror, tried in this order.
6
+ */
7
+ const MERKL_DOMAINS = ["https://api.merkl.xyz", "https://api-merkl.angle.money"];
8
+ const MERKL_API_KEY_HEADER = "X-API-Key";
9
+ /**
10
+ * Per-attempt budget. Merkl has no timeout of its own, and a hung connection
11
+ * would otherwise stall its leg of a fan-out for as long as the socket lives.
12
+ */
13
+ const ATTEMPT_TIMEOUT = 1e4;
14
+ /**
15
+ * The wallet's raw Merkl rewards on one chain.
16
+ *
17
+ * Rejects with {@link MerklRequestFailedError} when neither domain answers, so
18
+ * a caller can tell an unreachable Merkl from a wallet with nothing to claim.
19
+ * A non-2xx counts as no answer and moves to the next domain: it carries no
20
+ * rewards either way, and treating it as success would report emptiness that
21
+ * was never established.
22
+ */
23
+ async function fetchMerklUserRewards({ chainId, user, apiKey }) {
24
+ const path = `/v4/users/${user}/rewards?chainId=${chainId}`;
25
+ const headers = apiKey ? { [MERKL_API_KEY_HEADER]: apiKey } : void 0;
26
+ const attempts = [];
27
+ for (const domain of MERKL_DOMAINS) try {
28
+ const response = await fetch(`${domain}${path}`, {
29
+ headers,
30
+ signal: AbortSignal.timeout(ATTEMPT_TIMEOUT)
31
+ });
32
+ if (!response.ok) {
33
+ attempts.push([domain, /* @__PURE__ */ new Error(`answered ${response.status}`)]);
34
+ continue;
35
+ }
36
+ return await response.json();
37
+ } catch (error) {
38
+ attempts.push([domain, error]);
39
+ }
40
+ throw new require_rewards_errors.MerklRequestFailedError(chainId, path, attempts);
41
+ }
42
+ //#endregion
43
+ exports.MERKL_API_KEY_HEADER = MERKL_API_KEY_HEADER;
44
+ exports.MERKL_DOMAINS = MERKL_DOMAINS;
45
+ exports.fetchMerklUserRewards = fetchMerklUserRewards;
@@ -0,0 +1,40 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_onchain_base_MultichainConstruct = require("../onchain/base/MultichainConstruct.js");
3
+ require("../onchain/index.js");
4
+ const require_rewards_merkl_api = require("./merkl-api.js");
5
+ const require_rewards_toMerklRewards = require("./toMerklRewards.js");
6
+ let viem = require("viem");
7
+ //#region src/rewards/multichain.ts
8
+ /**
9
+ * The fan-out itself. Private because rewards are not an SDK namespace yet:
10
+ * the read is a free function, and this is only how it reaches `queryChains`.
11
+ **/
12
+ var MerklRewardsFanOut = class extends require_onchain_base_MultichainConstruct.MultichainConstruct {
13
+ async list(wallet, chainIds, apiKey) {
14
+ const user = (0, viem.getAddress)(wallet);
15
+ return this.queryChains({
16
+ chainIds,
17
+ label: "list rewards",
18
+ block: "state",
19
+ run: async (sdk) => require_rewards_toMerklRewards.toMerklRewards(sdk, await require_rewards_merkl_api.fetchMerklUserRewards({
20
+ chainId: sdk.chainId,
21
+ user,
22
+ apiKey
23
+ }))
24
+ });
25
+ }
26
+ };
27
+ /**
28
+ * Every claimable Merkl reward a wallet holds, across the chains the handle
29
+ * carries.
30
+ *
31
+ * Answers the read model's own envelope, so a chain that could not be reached
32
+ * is `status: "error"` in `meta.chains` while a chain with nothing to claim is
33
+ * a `"success"` that contributed no rows. That distinction is the point: the
34
+ * single-chain read this replaces resolved empty either way.
35
+ **/
36
+ async function getMerklRewardsMultichain({ sdk, wallet, chainIds, apiKey }) {
37
+ return new MerklRewardsFanOut(sdk).list(wallet, chainIds, apiKey);
38
+ }
39
+ //#endregion
40
+ exports.getMerklRewardsMultichain = getMerklRewardsMultichain;
@@ -1,28 +1,17 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_onchain_utils_AddressMap = require("../../onchain/utils/AddressMap.js");
3
- const require_onchain_utils_bigint_math = require("../../onchain/utils/bigint-math.js");
4
- const require_onchain_utils_formatter = require("../../onchain/utils/formatter.js");
5
- require("../../onchain/index.js");
6
- const require_rewards_rewards_merkl_api = require("./merkl-api.js");
2
+ const require_onchain_utils_AddressMap = require("../onchain/utils/AddressMap.js");
3
+ const require_onchain_utils_bigint_math = require("../onchain/utils/bigint-math.js");
4
+ const require_onchain_utils_formatter = require("../onchain/utils/formatter.js");
5
+ require("../onchain/index.js");
7
6
  let viem = require("viem");
8
- //#region src/rewards/rewards/api.ts
7
+ //#region src/rewards/toMerklRewards.ts
9
8
  /**
10
- * The wallet's claimable Merkl rewards on one chain.
11
- *
12
- * Never rejects on a transport failure: the fetch is settled rather than
13
- * awaited, and a failure goes to `reportError` and yields an empty list. A
14
- * caller that must tell "this chain is down" from "this chain has no rewards"
15
- * has to watch that callback.
9
+ * Merkl's answer for one chain, turned into rows of the read model.
16
10
  */
17
- async function getMerklRewards({ sdk, account, reportError, apiKey }) {
18
- const [merkleXYZLMResponse] = await Promise.allSettled([require_rewards_rewards_merkl_api.MerkleXYZApi.fetchWithFallback(require_rewards_rewards_merkl_api.MerkleXYZApi.getUserRewardsUrl({ params: {
19
- chainId: sdk.chainId,
20
- user: (0, viem.getAddress)(account)
21
- } }), apiKey)]);
22
- const merkleXYZLm = extractFulfilled(merkleXYZLMResponse, reportError, "merkleXYZLm")?.data;
11
+ function toMerklRewards(sdk, response) {
23
12
  const poolByItsToken = require_onchain_utils_AddressMap.AddressMap.fromMappedArray(sdk.marketRegister.pools.map(({ pool }) => pool.address), (address) => address);
24
13
  const claimable = /* @__PURE__ */ new Map();
25
- for (const chainRewards of merkleXYZLm || []) for (const reward of chainRewards.rewards) {
14
+ for (const chainRewards of response) for (const reward of chainRewards.rewards) {
26
15
  if (!(0, viem.isAddress)(reward.token.address, { strict: false })) continue;
27
16
  const rewardTokenAddress = (0, viem.getAddress)(reward.token.address);
28
17
  for (const reason of reward.breakdowns) {
@@ -30,9 +19,9 @@ async function getMerklRewards({ sdk, account, reportError, apiKey }) {
30
19
  if (!(0, viem.isAddress)(poolTokenAddress, { strict: false })) continue;
31
20
  const pool = poolByItsToken.get(poolTokenAddress);
32
21
  if (!pool) continue;
33
- const total = require_onchain_utils_formatter.toBigInt(reason.amount || 0);
34
- const claimed = require_onchain_utils_formatter.toBigInt(reason.claimed || 0);
35
- const amount = require_onchain_utils_bigint_math.BigIntMath.max(total - claimed, 0n);
22
+ const amounts = toAmounts(reason);
23
+ if (!amounts) continue;
24
+ const amount = require_onchain_utils_bigint_math.BigIntMath.max(amounts.total - amounts.claimed, 0n);
36
25
  if (amount === 0n) continue;
37
26
  const key = `${pool}_${rewardTokenAddress}`;
38
27
  const seen = claimable.get(key);
@@ -54,6 +43,20 @@ async function getMerklRewards({ sdk, account, reportError, apiKey }) {
54
43
  }
55
44
  return [...claimable.values()].map(toReward);
56
45
  }
46
+ /**
47
+ * `toBigInt` throws on anything `BigInt()` cannot parse, and Merkl's amounts
48
+ * are free-form strings.
49
+ */
50
+ function toAmounts(reason) {
51
+ try {
52
+ return {
53
+ total: require_onchain_utils_formatter.toBigInt(reason.amount || 0),
54
+ claimed: require_onchain_utils_formatter.toBigInt(reason.claimed || 0)
55
+ };
56
+ } catch {
57
+ return;
58
+ }
59
+ }
57
60
  function toReward({ price, token, value, ...rest }) {
58
61
  return {
59
62
  ...rest,
@@ -78,10 +81,5 @@ function toRewardToken(sdk, address, merkl) {
78
81
  decimals: merkl.decimals || 18
79
82
  };
80
83
  }
81
- function extractFulfilled(r, reportError, description) {
82
- if (r.status === "fulfilled") return r.value;
83
- if (reportError) reportError(r.reason, description);
84
- else console.error(r.reason);
85
- }
86
84
  //#endregion
87
- exports.getMerklRewards = getMerklRewards;
85
+ exports.toMerklRewards = toMerklRewards;
@@ -14,8 +14,8 @@ const tagDiff = makeTagDiff({
14
14
  *
15
15
  * Nothing is filtered out. A field only the backend can fill, or a USD value
16
16
  * that drifted within snapshot-lag noise, is still reported — tagged
17
- * {@link FieldDiff.expected} so that {@link CompareCounts.clean} can ignore it
18
- * while {@link CompareCounts.identical} stays strict.
17
+ * {@link FieldDiff.expected} so that {@link CompareCounts.similar} can ignore
18
+ * it.
19
19
  **/
20
20
  function compareOpportunities(input) {
21
21
  const onchainRows = indexById(input.onchain.data);
@@ -36,8 +36,7 @@ function compareOpportunities(input) {
36
36
  chainId: row.chainId,
37
37
  onchainName: row.name,
38
38
  offchainName: counterpart.name,
39
- identical: diffs.length === 0,
40
- clean: diffs.every((diff) => diff.expected),
39
+ similar: diffs.every((diff) => diff.expected),
41
40
  diffs
42
41
  });
43
42
  }
@@ -17,8 +17,8 @@ const tagDiff = makeTagDiff({
17
17
  * Nothing is filtered out. A field only one mode can fill, a strategy field
18
18
  * both-mode merge overlays from the backend, or a USD value that drifted
19
19
  * within snapshot-lag noise, is still reported — tagged
20
- * {@link FieldDiff.expected} so that {@link CompareCounts.clean} can ignore it
21
- * while {@link CompareCounts.identical} stays strict.
20
+ * {@link FieldDiff.expected} so that {@link CompareCounts.similar} can ignore
21
+ * it.
22
22
  **/
23
23
  function comparePositions(input) {
24
24
  const failures = input.failures ?? [];
@@ -65,8 +65,7 @@ function compareWallet(input) {
65
65
  chainId: row.chainId,
66
66
  onchainName: row.name,
67
67
  offchainName: counterpart.name,
68
- identical: diffs.length === 0,
69
- clean: diffs.every((diff) => diff.expected),
68
+ similar: diffs.every((diff) => diff.expected),
70
69
  diffs
71
70
  });
72
71
  }
@@ -129,11 +128,11 @@ function summarize(inputs, wallets, failed) {
129
128
  ...wallet.error ? { error: wallet.error } : {},
130
129
  ...toCompareCounts(wallet.matched.length + wallet.onlyOnchain.length, wallet.matched.length + wallet.onlyOffchain.length, wallet.onlyOnchain.length, wallet.onlyOffchain.length, wallet.matched)
131
130
  }));
132
- const walletsClean = compared.filter((wallet) => wallet.onlyOnchain.length === 0 && wallet.onlyOffchain.length === 0 && wallet.matched.every((match) => match.clean)).length;
131
+ const walletsSimilar = compared.filter((wallet) => wallet.onlyOnchain.length === 0 && wallet.onlyOffchain.length === 0 && wallet.matched.every((match) => match.similar)).length;
133
132
  return {
134
133
  ...toCompareCounts(allOnchain.length, allOffchain.length, onlyOnchain.length, onlyOffchain.length, matched),
135
134
  wallets: wallets.length,
136
- walletsClean,
135
+ walletsSimilar,
137
136
  walletsFailed: failed,
138
137
  byChain,
139
138
  byWallet,
@@ -53,7 +53,7 @@ function diffObjects(onchain, offchain, options) {
53
53
  return diffs;
54
54
  }
55
55
  /**
56
- * Mark a diff expected, so a later `clean` count can ignore it.
56
+ * Mark a diff expected, so a later `similar` count can ignore it.
57
57
  **/
58
58
  function withExpected(diff, reason) {
59
59
  return {
@@ -117,15 +117,13 @@ function collapseArrayKeys(path) {
117
117
  * Membership and match totals of one comparison, from already-built lists.
118
118
  **/
119
119
  function toCompareCounts(onchainRows, offchainRows, onlyOnchain, onlyOffchain, matched) {
120
- const identical = matched.filter((match) => match.identical).length;
121
- const clean = matched.filter((match) => match.clean).length;
120
+ const similar = matched.filter((match) => match.similar).length;
122
121
  return {
123
122
  onchainRows,
124
123
  offchainRows,
125
124
  matched: matched.length,
126
- identical,
127
- clean,
128
- differing: matched.length - identical,
125
+ similar,
126
+ different: matched.length - similar,
129
127
  onlyOnchain,
130
128
  onlyOffchain
131
129
  };