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

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 (42) hide show
  1. package/dist/cjs/dev/mode-parity/compareOpportunities.js +105 -0
  2. package/dist/cjs/dev/mode-parity/comparePositions.js +160 -0
  3. package/dist/cjs/dev/mode-parity/compareRules.js +93 -0
  4. package/dist/cjs/dev/mode-parity/fieldDiff.js +288 -0
  5. package/dist/cjs/dev/mode-parity/scriptUtils.js +131 -0
  6. package/dist/cjs/model/compare.schema.js +33 -0
  7. package/dist/cjs/model/curators.schema.js +2 -1
  8. package/dist/cjs/model/index.js +5 -0
  9. package/dist/cjs/model/opportunities.schema.js +13 -12
  10. package/dist/cjs/model/positions.schema.js +15 -14
  11. package/dist/cjs/model/primitives.schema.js +2 -1
  12. package/dist/cjs/sdk/market/math.js +8 -1
  13. package/dist/cjs/sdk/pools/PoolService.js +1 -1
  14. package/dist/cjs/sdk/positions/PositionsService.js +6 -1
  15. package/dist/esm/common-utils/index.js +3 -3
  16. package/dist/esm/common-utils/utils/index.js +1 -1
  17. package/dist/esm/dev/mode-parity/compareOpportunities.js +103 -0
  18. package/dist/esm/dev/mode-parity/comparePositions.js +158 -0
  19. package/dist/esm/dev/mode-parity/compareRules.js +91 -0
  20. package/dist/esm/dev/mode-parity/fieldDiff.js +270 -0
  21. package/dist/esm/dev/mode-parity/scriptUtils.js +121 -0
  22. package/dist/esm/model/compare.schema.js +29 -0
  23. package/dist/esm/model/curators.schema.js +2 -1
  24. package/dist/esm/model/index.js +2 -1
  25. package/dist/esm/model/opportunities.schema.js +13 -12
  26. package/dist/esm/model/positions.schema.js +15 -14
  27. package/dist/esm/model/primitives.schema.js +2 -1
  28. package/dist/esm/plugins/apy/ApyPlugin.js +2 -2
  29. package/dist/esm/sdk/market/math.js +8 -1
  30. package/dist/esm/sdk/pools/PoolService.js +1 -1
  31. package/dist/esm/sdk/positions/PositionsService.js +6 -1
  32. package/dist/types/dev/{compareOpportunities.d.ts → mode-parity/compareOpportunities.d.ts} +18 -66
  33. package/dist/types/dev/mode-parity/comparePositions.d.ts +149 -0
  34. package/dist/types/dev/mode-parity/compareRules.d.ts +33 -0
  35. package/dist/types/dev/mode-parity/fieldDiff.d.ts +209 -0
  36. package/dist/types/dev/mode-parity/scriptUtils.d.ts +47 -0
  37. package/dist/types/model/compare.schema.d.ts +47 -0
  38. package/dist/types/model/index.d.ts +2 -1
  39. package/dist/types/sdk/market/math.d.ts +2 -0
  40. package/package.json +1 -1
  41. package/dist/cjs/dev/compareOpportunities.js +0 -218
  42. package/dist/esm/dev/compareOpportunities.js +0 -216
@@ -0,0 +1,209 @@
1
+ import { ChainId } from "../../model/primitives.js";
2
+ import "../../model/index.js";
3
+ //#region src/dev/mode-parity/fieldDiff.d.ts
4
+ /**
5
+ * What kind of disagreement a {@link FieldDiff} describes, so that a reader can
6
+ * bucket the report without re-deriving it from the values.
7
+ *
8
+ * - `"presence"` — one side has no value at all (`undefined` or `null`).
9
+ * - `"usd"` — an {@link Amount.valueUsd}, i.e. a price-derived float.
10
+ * - `"numeric"` — any other number or bigint.
11
+ * - `"other"` — everything else: strings, booleans, array shapes.
12
+ **/
13
+ type DiffKind = "presence" | "usd" | "numeric" | "other";
14
+ /**
15
+ * Why a {@link FieldDiff} is expected rather than a real disagreement.
16
+ *
17
+ * - `"mode-scoped"` — a field documented `@mode offchain` or `@mode onchain`,
18
+ * so the other source has nothing to put there.
19
+ * - `"tolerance"` — snapshot lag or float-path noise within the thresholds
20
+ * below, not a formula or membership mismatch.
21
+ **/
22
+ type ExpectedDiffReason = "mode-scoped" | "tolerance";
23
+ /**
24
+ * One field of one row where the two sources disagree.
25
+ **/
26
+ interface FieldDiff {
27
+ /**
28
+ * Dotted path into the row, with array elements keyed by their own identity
29
+ * rather than by index, e.g. `collateralTokens[0xa0b8...].symbol`.
30
+ **/
31
+ path: string;
32
+ /**
33
+ * Value the chain reported, `undefined` when it has no such field.
34
+ **/
35
+ onchain: unknown;
36
+ /**
37
+ * Value the backend reported, see {@link onchain}.
38
+ **/
39
+ offchain: unknown;
40
+ kind: DiffKind;
41
+ /**
42
+ * Present when this disagreement is documented or within snapshot-lag noise,
43
+ * so it does not keep the row from being counted as clean.
44
+ **/
45
+ expected?: true;
46
+ reason?: ExpectedDiffReason;
47
+ }
48
+ /**
49
+ * The largest numeric disagreement seen for one collapsed field path, on
50
+ * either the unexpected or the expected side.
51
+ **/
52
+ interface WorstDiff {
53
+ /**
54
+ * Entity id (position/opportunity id) with the biggest relative difference.
55
+ **/
56
+ id: string;
57
+ /**
58
+ * Uncollapsed path, so the exact array element is named.
59
+ **/
60
+ path: string;
61
+ /**
62
+ * Relative difference in bps.
63
+ **/
64
+ bps: number;
65
+ onchain: unknown;
66
+ offchain: unknown;
67
+ }
68
+ /**
69
+ * One field disagreement together with the matched row it belongs to.
70
+ **/
71
+ interface EntityFieldDiff {
72
+ id: string;
73
+ diff: FieldDiff;
74
+ }
75
+ /**
76
+ * How often one field disagreed across all matched rows, with array keys
77
+ * collapsed, e.g. `collateralTokens[].symbol`.
78
+ **/
79
+ interface DiffPathCount {
80
+ path: string;
81
+ kinds: DiffKind[];
82
+ count: number;
83
+ expected: number;
84
+ unexpected: number;
85
+ /**
86
+ * Largest unexpected numeric disagreement, when any unexpected diff of this
87
+ * path yields a relative bps value.
88
+ **/
89
+ worstUnexpected?: WorstDiff;
90
+ /**
91
+ * Largest expected numeric disagreement, see {@link worstUnexpected}.
92
+ **/
93
+ worstExpected?: WorstDiff;
94
+ }
95
+ /**
96
+ * Counts of one chain, one wallet, or of the whole report when those ids are
97
+ * absent.
98
+ **/
99
+ interface CompareCounts {
100
+ onchainRows: number;
101
+ offchainRows: number;
102
+ matched: number;
103
+ identical: number;
104
+ /**
105
+ * Matched rows with no unexpected diffs, including the identical ones.
106
+ **/
107
+ clean: number;
108
+ differing: number;
109
+ onlyOnchain: number;
110
+ onlyOffchain: number;
111
+ }
112
+ /**
113
+ * Counts of one chain.
114
+ **/
115
+ interface ChainCompareCounts extends CompareCounts {
116
+ chainId: ChainId;
117
+ }
118
+ /**
119
+ * Identity of an array element, used so a token present on one side only is
120
+ * reported as such rather than shifting every later element into a diff.
121
+ *
122
+ * Return a string to key the element; `undefined` falls back to the default
123
+ * (`address`, `id`, `token`, or nested `token.address`).
124
+ **/
125
+ type ArrayElementKey = (path: string, value: unknown) => string | undefined;
126
+ /**
127
+ * How to walk two values. Callers that need identity-bearing arrays whose
128
+ * key is not one of the defaults pass {@link DiffOptions.keyOf}.
129
+ **/
130
+ interface DiffOptions {
131
+ keyOf?: ArrayElementKey;
132
+ }
133
+ /**
134
+ * Relative drift allowed on {@link Amount.valueUsd} before a USD float is a
135
+ * real disagreement: 0.1%.
136
+ **/
137
+ declare const USD_RELATIVE_EPSILON = 0.001;
138
+ /**
139
+ * Relative drift allowed on lag-bounded bigint amounts: 0.05%.
140
+ **/
141
+ declare const AMOUNT_RELATIVE_EPSILON = 0.0005;
142
+ /**
143
+ * Absolute drift allowed on bps rates before rounding and a one-block lag are
144
+ * no longer enough to explain it.
145
+ **/
146
+ declare const BPS_ABSOLUTE_EPSILON = 1;
147
+ /**
148
+ * Every field two versions of one value disagree on. Nothing is filtered or
149
+ * tagged: the caller marks expected diffs afterwards.
150
+ **/
151
+ declare function diffValue(path: string, onchain: unknown, offchain: unknown, out: FieldDiff[], options?: DiffOptions): void;
152
+ /**
153
+ * Deep-diff two values and return the disagreements, in path order of
154
+ * discovery.
155
+ **/
156
+ declare function diffObjects(onchain: unknown, offchain: unknown, options?: DiffOptions): FieldDiff[];
157
+ /**
158
+ * Mark a diff expected, so a later `clean` count can ignore it.
159
+ **/
160
+ declare function withExpected(diff: FieldDiff, reason: ExpectedDiffReason): FieldDiff;
161
+ /**
162
+ * How often each field differed, with array keys collapsed so that the same
163
+ * field of a hundred collateral tokens counts as one path. Sorted so the
164
+ * unexpected disagreements come first.
165
+ **/
166
+ declare function countPaths(diffs: Iterable<EntityFieldDiff>): DiffPathCount[];
167
+ /**
168
+ * Collapse `collateralTokens[0xa0b8...].symbol` to `collateralTokens[].symbol`.
169
+ **/
170
+ declare function collapseArrayKeys(path: string): string;
171
+ /**
172
+ * Membership and match totals of one comparison, from already-built lists.
173
+ **/
174
+ declare function toCompareCounts(onchainRows: number, offchainRows: number, onlyOnchain: number, onlyOffchain: number, matched: ReadonlyArray<{
175
+ identical: boolean;
176
+ clean: boolean;
177
+ }>): CompareCounts;
178
+ /**
179
+ * USD floats within {@link USD_RELATIVE_EPSILON}.
180
+ **/
181
+ declare function isUsdWithinTolerance(onchain: unknown, offchain: unknown): boolean;
182
+ /**
183
+ * Bps rates that differ by at most {@link BPS_ABSOLUTE_EPSILON}.
184
+ **/
185
+ declare function isBpsWithinTolerance(onchain: unknown, offchain: unknown): boolean;
186
+ /**
187
+ * Bigint amounts within {@link AMOUNT_RELATIVE_EPSILON}.
188
+ **/
189
+ declare function isAmountWithinTolerance(onchain: unknown, offchain: unknown): boolean;
190
+ /**
191
+ * Finite numbers within a relative epsilon of each other.
192
+ **/
193
+ declare function withinRelative(onchain: number | undefined, offchain: number | undefined, epsilon: number): boolean;
194
+ /**
195
+ * `diff / max(|a|, |b|) <= epsilon`, computed in integer arithmetic so a
196
+ * 1e18-scale amount does not round through `Number`.
197
+ **/
198
+ declare function withinRelativeBigint(onchain: bigint, offchain: bigint, epsilon: number): boolean;
199
+ declare function asFiniteNumber(value: unknown): number | undefined;
200
+ /**
201
+ * Relative difference of two numbers or bigints, in bps:
202
+ * `|a − b| / max(|a|, |b|) * 10_000`. `undefined` when the values are not
203
+ * a comparable pair of finite numbers or of bigints.
204
+ **/
205
+ declare function relativeDiffBps(onchain: unknown, offchain: unknown): number | undefined;
206
+ declare function union(left: string[], right: string[]): string[];
207
+ declare function isRecord(value: unknown): value is Record<string, unknown>;
208
+ //#endregion
209
+ export { AMOUNT_RELATIVE_EPSILON, ArrayElementKey, BPS_ABSOLUTE_EPSILON, ChainCompareCounts, CompareCounts, DiffKind, DiffOptions, DiffPathCount, EntityFieldDiff, ExpectedDiffReason, FieldDiff, USD_RELATIVE_EPSILON, WorstDiff, asFiniteNumber, collapseArrayKeys, countPaths, diffObjects, diffValue, isAmountWithinTolerance, isBpsWithinTolerance, isRecord, isUsdWithinTolerance, relativeDiffBps, toCompareCounts, union, withExpected, withinRelative, withinRelativeBigint };
@@ -0,0 +1,47 @@
1
+ import { ChainMetadata } from "../../model/response.js";
2
+ import "../../model/index.js";
3
+ import { ChainCompareCounts, CompareCounts, DiffPathCount } from "./fieldDiff.js";
4
+ import { Logger } from "pino";
5
+ //#region src/dev/mode-parity/scriptUtils.d.ts
6
+ /**
7
+ * Chains the compare scripts attach to.
8
+ **/
9
+ type ComparedNetwork = "Mainnet" | "Monad" | "Plasma" | "Somnia" | "Etherlink";
10
+ declare const NETWORKS: ComparedNetwork[];
11
+ declare const BACKEND_URL: string;
12
+ declare const TIMEOUT = 480000;
13
+ /**
14
+ * Totals both compare reports print.
15
+ **/
16
+ interface PrintableCompareSummary extends CompareCounts {
17
+ byChain: ChainCompareCounts[];
18
+ diffsByPath: DiffPathCount[];
19
+ }
20
+ /**
21
+ * Per-source chain metadata both compare reports carry.
22
+ **/
23
+ interface PrintableCompareReport {
24
+ backendUrl: string;
25
+ summary: PrintableCompareSummary;
26
+ onchainChains: ChainMetadata[];
27
+ offchainChains: ChainMetadata[];
28
+ }
29
+ declare function requireEnv(name: string): string;
30
+ declare function rpcUrls(): Record<ComparedNetwork, string>;
31
+ declare function createLogger(): Logger;
32
+ declare function errorMessage(error: unknown): string;
33
+ /**
34
+ * Runs `fn` over `items` with at most `concurrency` in flight.
35
+ **/
36
+ declare function mapPool<T>(items: readonly T[], concurrency: number, fn: (item: T) => Promise<void>): Promise<void>;
37
+ /**
38
+ * Formats a relative difference in bps as a percent, e.g. 12.5 → `"0.125%"`.
39
+ **/
40
+ declare function formatBpsAsPercent(bps: number): string;
41
+ /**
42
+ * Prints the shared membership table, the fields that differed most often,
43
+ * and any chain that failed to answer.
44
+ **/
45
+ declare function printCompareSummary(noun: string, report: PrintableCompareReport, extraLines?: string[]): void;
46
+ //#endregion
47
+ export { BACKEND_URL, ComparedNetwork, NETWORKS, PrintableCompareReport, PrintableCompareSummary, TIMEOUT, createLogger, errorMessage, formatBpsAsPercent, mapPool, printCompareSummary, requireEnv, rpcUrls };
@@ -0,0 +1,47 @@
1
+ import { z } from "zod/v4";
2
+ //#region src/model/compare.schema.d.ts
3
+ /**
4
+ * How close two numeric values may be before a disagreement counts as real.
5
+ *
6
+ * The compare scripts pick a formula from this union; the schemas only name
7
+ * which formula a field uses.
8
+ *
9
+ * - `"amount"` — accrual lag on an {@link Amount.value} / {@link TokenAmount.value}.
10
+ * - `"bps"` — truncation vs rounding on a basis-point rate, ±1.
11
+ * - `"float"` — relative float drift within 0.1% (leverage).
12
+ * - `"usd"` — price-derived {@link Amount.valueUsd} / {@link TokenAmount.valueUsd}.
13
+ **/
14
+ type CompareTolerance = "amount" | "bps" | "float" | "usd";
15
+ /**
16
+ * A numeric field whose two sources may drift within {@link tolerance}.
17
+ **/
18
+ interface ToleranceCompareTag {
19
+ tolerance: CompareTolerance;
20
+ }
21
+ /**
22
+ * Compare metadata a schema field may carry.
23
+ *
24
+ * - `"offchainOnly"` / `"onchainOnly"` — the other source typically leaves
25
+ * the field empty, so a disagreement is expected.
26
+ * - {@link ToleranceCompareTag} — a numeric disagreement within the named
27
+ * formula is expected snapshot noise.
28
+ **/
29
+ type CompareTag = "offchainOnly" | "onchainOnly" | ToleranceCompareTag;
30
+ /**
31
+ * Marks a field that only the backend fills.
32
+ **/
33
+ declare function offchainOnly<S extends z.ZodType>(schema: S): S;
34
+ /**
35
+ * Marks a field that only the chain fills.
36
+ **/
37
+ declare function onchainOnly<S extends z.ZodType>(schema: S): S;
38
+ /**
39
+ * Marks a numeric field whose two sources may drift within {@link kind}.
40
+ **/
41
+ declare function tolerance<S extends z.ZodType>(schema: S, kind: CompareTolerance): S;
42
+ /**
43
+ * The compare tag registered on a schema, if any.
44
+ **/
45
+ declare function compareTagOf(schema: z.ZodType): CompareTag | undefined;
46
+ //#endregion
47
+ export { CompareTag, CompareTolerance, ToleranceCompareTag, compareTagOf, offchainOnly, onchainOnly, tolerance };
@@ -2,6 +2,7 @@ import { Amount, AssetType, Bps, ChainId, Leverage, Timestamp, Token, TokenAmoun
2
2
  import { Curator, CuratorName } from "./curators.js";
3
3
  import { CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ChartBundle, ChartDenomination, ChartMetric, ChartQuery, ChartRange, ChartSeries, ChartSeriesOk, ChartSeriesUnavailable, ChartUnavailableCode, ChartUnit, ChartValue, ChartWindow, GridSampling, OpportunityChartMetric, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PoolOpportunityChartMetric, PoolPositionChartMetric, PositionChartMetric, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, StrategyOpportunityChartMetric, StrategyPositionChartMetric } from "./charts.js";
4
4
  import { chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, poolOpportunityChartMetricSchema, poolPositionChartMetricSchema, strategyOpportunityChartMetricSchema, strategyPositionChartMetricSchema } from "./charts.schema.js";
5
+ import { CompareTag, CompareTolerance, ToleranceCompareTag, compareTagOf, offchainOnly, onchainOnly, tolerance } from "./compare.schema.js";
5
6
  import { curatorNameSchema, curatorSchema } from "./curators.schema.js";
6
7
  import { ChainScopedFilter, FILTER_ALL, FilterAll, Filterable, isFilterSet } from "./filters.js";
7
8
  import { booleanParamSchema, encodeFlag, filterAllSchema, filterable } from "./filters.schema.js";
@@ -16,4 +17,4 @@ import { borrowRateBreakdownSchema, pnlBreakdownSchema, pointsProgramPnLSchema,
16
17
  import { amountSchema, assetTypeSchema, bpsSchema, chainIdSchema, leverageSchema, timestampSchema, tokenAmountSchema, tokenSchema, txCallSchema } from "./primitives.schema.js";
17
18
  import { ChainFailed, ChainMetadata, ChainScoped, ChainSucceeded, DataResponse, DataSource, ResponseMetadata } from "./response.js";
18
19
  import { chainFailedSchema, chainMetadataSchema, chainSucceededSchema, dataSourceSchema, responseMetadataSchema, responseSchema } from "./response.schema.js";
19
- export { Amount, ApyBreakdown, AssetType, BorrowRateBreakdown, Bps, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ChainFailed, ChainId, ChainMetadata, ChainScoped, ChainScopedFilter, ChainSucceeded, ChartBundle, ChartDenomination, ChartMetric, ChartQuery, ChartRange, ChartSeries, ChartSeriesOk, ChartSeriesUnavailable, ChartUnavailableCode, ChartUnit, ChartValue, ChartWindow, Curator, CuratorName, DataResponse, DataSource, DelayedReceivedAsset, FILTER_ALL, FilterAll, Filterable, GridSampling, InstantReceivedAsset, Leverage, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, Notice, NoticeKind, NoticeSubject, Opportunity, OpportunityBase, OpportunityChartMetric, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PnlBreakdown, PointRewards, PointsProgram, PointsProgramPnL, PointsRewardsPnL, PoolOpportunity, PoolOpportunityChartMetric, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PoolPosition, PoolPositionChartMetric, PoolPositionKey, PoolPositionRef, Position, PositionChartMetric, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionMetrics, PositionTransaction, PositionTransactionKind, PositionsTotals, PriceFeedData, PriceFeedSummary, QuotaAsset, RateCurve, RateCurvePoint, ReceivedAsset, ResponseMetadata, Rewards, RewardsPnL, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, StrategyOpportunity, StrategyOpportunityChartMetric, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, StrategyPosition, StrategyPositionChartMetric, StrategyPositionKey, StrategyPositionRef, Timestamp, Token, TokenAmount, TokenRewards, TokenRewardsPnL, TxCall, amountSchema, apyBreakdownSchema, assetTypeSchema, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, curatorNameSchema, curatorSchema, dataSourceSchema, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, instantReceivedAssetSchema, isFilterSet, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, noticeKindSchema, noticeSchema, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, txCallSchema };
20
+ export { Amount, ApyBreakdown, AssetType, BorrowRateBreakdown, Bps, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ChainFailed, ChainId, ChainMetadata, ChainScoped, ChainScopedFilter, ChainSucceeded, ChartBundle, ChartDenomination, ChartMetric, ChartQuery, ChartRange, ChartSeries, ChartSeriesOk, ChartSeriesUnavailable, ChartUnavailableCode, ChartUnit, ChartValue, ChartWindow, CompareTag, CompareTolerance, Curator, CuratorName, DataResponse, DataSource, DelayedReceivedAsset, FILTER_ALL, FilterAll, Filterable, GridSampling, InstantReceivedAsset, Leverage, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, Notice, NoticeKind, NoticeSubject, Opportunity, OpportunityBase, OpportunityChartMetric, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PnlBreakdown, PointRewards, PointsProgram, PointsProgramPnL, PointsRewardsPnL, PoolOpportunity, PoolOpportunityChartMetric, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PoolPosition, PoolPositionChartMetric, PoolPositionKey, PoolPositionRef, Position, PositionChartMetric, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionMetrics, PositionTransaction, PositionTransactionKind, PositionsTotals, PriceFeedData, PriceFeedSummary, QuotaAsset, RateCurve, RateCurvePoint, ReceivedAsset, ResponseMetadata, Rewards, RewardsPnL, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, StrategyOpportunity, StrategyOpportunityChartMetric, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, StrategyPosition, StrategyPositionChartMetric, StrategyPositionKey, StrategyPositionRef, Timestamp, Token, TokenAmount, TokenRewards, TokenRewardsPnL, ToleranceCompareTag, TxCall, amountSchema, apyBreakdownSchema, assetTypeSchema, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, curatorNameSchema, curatorSchema, dataSourceSchema, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, instantReceivedAssetSchema, isFilterSet, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema };
@@ -15,6 +15,8 @@ declare function rayToBps(ray: bigint): Bps;
15
15
  /**
16
16
  * Converts a USD value in the oracle's 8-decimal fixed point to a float.
17
17
  *
18
+ * Values below {@link USD_DUST_THRESHOLD} report as `0`.
19
+ *
18
20
  * @example
19
21
  * ```ts
20
22
  * // usd: $1500.50 in 8-decimal fixed point
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gearbox-protocol/sdk",
3
- "version": "15.1.0-next.10",
3
+ "version": "15.1.0-next.12",
4
4
  "description": "Gearbox SDK",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,218 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_model_opportunities = require("../model/opportunities.js");
3
- require("../model/index.js");
4
- //#region src/dev/compareOpportunities.ts
5
- /**
6
- * Matches two opportunity listings by {@link opportunityId} and reports every
7
- * field the two sources disagree on.
8
- *
9
- * Nothing is filtered out: a diff that is expected — a field only the backend
10
- * can fill, a formula the two sides define differently, a USD value smoothed on
11
- * one side — is reported like any other, tagged by {@link DiffKind} so that a
12
- * reader can bucket it afterwards.
13
- **/
14
- function compareOpportunities(input) {
15
- const onchainRows = indexById(input.onchain.data);
16
- const offchainRows = indexById(input.offchain.data);
17
- const onlyOnchain = [];
18
- const onlyOffchain = [];
19
- const matched = [];
20
- for (const [id, row] of onchainRows) {
21
- const counterpart = offchainRows.get(id);
22
- if (!counterpart) {
23
- onlyOnchain.push(toRef(row));
24
- continue;
25
- }
26
- const diffs = diffOpportunity(row, counterpart);
27
- matched.push({
28
- id,
29
- kind: row.kind,
30
- chainId: row.chainId,
31
- onchainName: row.name,
32
- offchainName: counterpart.name,
33
- identical: diffs.length === 0,
34
- diffs
35
- });
36
- }
37
- for (const [id, row] of offchainRows) if (!onchainRows.has(id)) onlyOffchain.push(toRef(row));
38
- byId(onlyOnchain);
39
- byId(onlyOffchain);
40
- matched.sort((a, b) => a.id.localeCompare(b.id));
41
- return {
42
- generatedAt: input.generatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
43
- backendUrl: input.backendUrl,
44
- networks: [...input.networks],
45
- onchainChains: input.onchain.meta.chains,
46
- offchainChains: input.offchain.meta.chains,
47
- summary: summarize(input.onchain.data, input.offchain.data, onlyOnchain, onlyOffchain, matched),
48
- onlyOnchain,
49
- onlyOffchain,
50
- matched
51
- };
52
- }
53
- function indexById(rows) {
54
- return new Map(rows.map((row) => [require_model_opportunities.opportunityId(row), row]));
55
- }
56
- function byId(refs) {
57
- refs.sort((a, b) => a.id.localeCompare(b.id));
58
- }
59
- function toRef(row) {
60
- const base = {
61
- id: require_model_opportunities.opportunityId(row),
62
- kind: row.kind,
63
- chainId: row.chainId,
64
- name: row.name
65
- };
66
- return row.kind === "pool" ? {
67
- ...base,
68
- pool: row.pool
69
- } : {
70
- ...base,
71
- creditManager: row.creditManager,
72
- targetCollateral: row.targetCollateral.address
73
- };
74
- }
75
- /**
76
- * Every field two versions of one opportunity disagree on.
77
- **/
78
- function diffOpportunity(onchain, offchain) {
79
- const diffs = [];
80
- diffValue("", onchain, offchain, diffs);
81
- return diffs;
82
- }
83
- function diffValue(path, onchain, offchain, out) {
84
- if (isAbsent(onchain) && isAbsent(offchain)) return;
85
- if (isAbsent(onchain) || isAbsent(offchain)) {
86
- out.push({
87
- path,
88
- onchain,
89
- offchain,
90
- kind: "presence"
91
- });
92
- return;
93
- }
94
- if (Array.isArray(onchain) && Array.isArray(offchain)) {
95
- diffArray(path, onchain, offchain, out);
96
- return;
97
- }
98
- if (isRecord(onchain) && isRecord(offchain)) {
99
- for (const key of union(Object.keys(onchain), Object.keys(offchain))) diffValue(join(path, key), onchain[key], offchain[key], out);
100
- return;
101
- }
102
- if (!sameScalar(onchain, offchain)) out.push({
103
- path,
104
- onchain,
105
- offchain,
106
- kind: scalarKind(path, onchain)
107
- });
108
- }
109
- /**
110
- * Arrays whose elements identify themselves — collateral tokens, points
111
- * programs — are matched by that identity, so a token present on one side only
112
- * is reported as such rather than shifting every later element into a diff.
113
- **/
114
- function diffArray(path, onchain, offchain, out) {
115
- const onchainKeyed = keyElements(onchain);
116
- const offchainKeyed = keyElements(offchain);
117
- if (!onchainKeyed || !offchainKeyed) {
118
- if (onchain.length !== offchain.length) {
119
- out.push({
120
- path,
121
- onchain,
122
- offchain,
123
- kind: "other"
124
- });
125
- return;
126
- }
127
- onchain.forEach((element, index) => {
128
- diffValue(`${path}[${index}]`, element, offchain[index], out);
129
- });
130
- return;
131
- }
132
- for (const key of union([...onchainKeyed.keys()], [...offchainKeyed.keys()])) diffValue(`${path}[${key}]`, onchainKeyed.get(key), offchainKeyed.get(key), out);
133
- }
134
- /**
135
- * The array indexed by each element's own identity, or `undefined` when its
136
- * elements have none and order is all there is to go by.
137
- **/
138
- function keyElements(values) {
139
- const keyed = /* @__PURE__ */ new Map();
140
- for (const value of values) {
141
- if (!isRecord(value)) return;
142
- const identity = value.address ?? value.id ?? value.token;
143
- if (typeof identity !== "string") return;
144
- keyed.set(identity.toLowerCase(), value);
145
- }
146
- return keyed.size === values.length ? keyed : void 0;
147
- }
148
- const ADDRESS = /^0x[0-9a-f]{40}$/i;
149
- /**
150
- * Only addresses are compared case-insensitively: the backend lowercases them
151
- * while the chain hands out checksummed ones, which is not a disagreement. A
152
- * symbol or a name spelled differently is.
153
- **/
154
- function sameScalar(onchain, offchain) {
155
- if (typeof onchain === "string" && typeof offchain === "string" && ADDRESS.test(onchain) && ADDRESS.test(offchain)) return onchain.toLowerCase() === offchain.toLowerCase();
156
- return onchain === offchain;
157
- }
158
- function scalarKind(path, onchain) {
159
- if (path.endsWith("valueUsd")) return "usd";
160
- return typeof onchain === "number" || typeof onchain === "bigint" ? "numeric" : "other";
161
- }
162
- function summarize(onchain, offchain, onlyOnchain, onlyOffchain, matched) {
163
- const byChain = union(onchain.map((row) => String(row.chainId)), offchain.map((row) => String(row.chainId))).map((chainId) => ({
164
- chainId: Number(chainId),
165
- ...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))
166
- })).sort((a, b) => a.chainId - b.chainId);
167
- return {
168
- ...count(onchain, offchain, onlyOnchain, onlyOffchain, matched),
169
- byChain,
170
- diffsByPath: countPaths(matched)
171
- };
172
- }
173
- function count(onchain, offchain, onlyOnchain, onlyOffchain, matched) {
174
- const identical = matched.filter((match) => match.identical).length;
175
- return {
176
- onchainRows: onchain.length,
177
- offchainRows: offchain.length,
178
- matched: matched.length,
179
- identical,
180
- differing: matched.length - identical,
181
- onlyOnchain: onlyOnchain.length,
182
- onlyOffchain: onlyOffchain.length
183
- };
184
- }
185
- /**
186
- * How often each field differed, with array keys collapsed so that the same
187
- * field of a hundred collateral tokens counts as one path.
188
- **/
189
- function countPaths(matched) {
190
- const counts = /* @__PURE__ */ new Map();
191
- for (const match of matched) for (const diff of match.diffs) {
192
- const path = diff.path.replace(/\[[^\]]*\]/g, "[]");
193
- const entry = counts.get(path) ?? {
194
- path,
195
- kinds: [],
196
- count: 0
197
- };
198
- entry.count += 1;
199
- if (!entry.kinds.includes(diff.kind)) entry.kinds.push(diff.kind);
200
- counts.set(path, entry);
201
- }
202
- return [...counts.values()].sort((a, b) => b.count - a.count || a.path.localeCompare(b.path));
203
- }
204
- function isAbsent(value) {
205
- return value === void 0 || value === null;
206
- }
207
- function isRecord(value) {
208
- return typeof value === "object" && value !== null && !Array.isArray(value);
209
- }
210
- function union(left, right) {
211
- return [.../* @__PURE__ */ new Set([...left, ...right])];
212
- }
213
- function join(path, key) {
214
- return path ? `${path}.${key}` : key;
215
- }
216
- //#endregion
217
- exports.compareOpportunities = compareOpportunities;
218
- exports.diffOpportunity = diffOpportunity;