@morpho-org/midnight-sdk 2.7.0-next.1 → 2.8.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/api/MidnightApi.js +63 -52
- package/lib/cjs/api/helpers.js +30 -17
- package/lib/cjs/fetch/Position.js +2 -1
- package/lib/cjs/fetch/Ratifier.js +4 -5
- package/lib/cjs/market/Market.js +2 -1
- package/lib/cjs/market/MarketUtils.js +16 -14
- package/lib/cjs/math/TakeAmountsLib.js +8 -4
- package/lib/cjs/math/TickLib.js +12 -6
- package/lib/cjs/offers/OfferChainUtils.js +35 -26
- package/lib/cjs/offers/OfferUtils.js +17 -10
- package/lib/cjs/position/Position.js +2 -1
- package/lib/cjs/signatures/EcrecoverRatifier.js +22 -17
- package/lib/cjs/signatures/Group.js +4 -2
- package/lib/cjs/signatures/Payload.js +18 -9
- package/lib/cjs/signatures/PriceRatifierV1.js +5 -4
- package/lib/cjs/signatures/RateRatifierV1.js +19 -11
- package/lib/cjs/signatures/Ratifier.js +4 -4
- package/lib/cjs/signatures/SetterRatifier.js +2 -1
- package/lib/cjs/signatures/Tree.js +8 -4
- package/lib/cjs/signatures/TreeUtils.js +16 -13
- package/lib/cjs/signatures/ratifierV1Internal.js +34 -24
- package/lib/cjs/signatures/treeMathInternal.d.ts +2 -0
- package/lib/cjs/signatures/treeMathInternal.js +10 -0
- package/lib/cjs/version.d.ts +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/esm/api/MidnightApi.js +63 -52
- package/lib/esm/api/helpers.js +30 -17
- package/lib/esm/fetch/Position.js +2 -1
- package/lib/esm/fetch/Ratifier.js +4 -5
- package/lib/esm/market/Market.js +2 -1
- package/lib/esm/market/MarketUtils.js +16 -14
- package/lib/esm/math/TakeAmountsLib.js +8 -4
- package/lib/esm/math/TickLib.js +12 -6
- package/lib/esm/offers/OfferChainUtils.js +35 -26
- package/lib/esm/offers/OfferUtils.js +17 -10
- package/lib/esm/position/Position.js +2 -1
- package/lib/esm/signatures/EcrecoverRatifier.js +22 -17
- package/lib/esm/signatures/Group.js +4 -2
- package/lib/esm/signatures/Payload.js +18 -9
- package/lib/esm/signatures/PriceRatifierV1.js +5 -4
- package/lib/esm/signatures/RateRatifierV1.js +19 -11
- package/lib/esm/signatures/Ratifier.js +5 -5
- package/lib/esm/signatures/SetterRatifier.js +2 -1
- package/lib/esm/signatures/Tree.js +8 -4
- package/lib/esm/signatures/TreeUtils.js +17 -14
- package/lib/esm/signatures/ratifierV1Internal.js +35 -25
- package/lib/esm/signatures/treeMathInternal.d.ts +2 -0
- package/lib/esm/signatures/treeMathInternal.js +9 -0
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/package.json +13 -13
|
@@ -20,17 +20,20 @@ function assignRatifierV1Groups(leaves, groupId) {
|
|
|
20
20
|
: index_js_1.Offer.from({ ...leaf.offer, group: groupId([leaf]) }));
|
|
21
21
|
const buckets = new Map();
|
|
22
22
|
for (const [index, leaf] of leaves.entries()) {
|
|
23
|
-
if (!leaf.offer.hasExplicitGroup)
|
|
23
|
+
if (!leaf.offer.hasExplicitGroup) {
|
|
24
24
|
continue;
|
|
25
|
+
}
|
|
25
26
|
const label = leaf.offer.group.toLowerCase();
|
|
26
27
|
const bucket = buckets.get(label);
|
|
27
|
-
if (bucket)
|
|
28
|
+
if (bucket) {
|
|
28
29
|
bucket.push(index);
|
|
29
|
-
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
30
32
|
buckets.set(label, [index]);
|
|
33
|
+
}
|
|
31
34
|
}
|
|
32
35
|
for (const [label, indices] of buckets) {
|
|
33
|
-
const bucketLeaves = indices.map((index) => leaves
|
|
36
|
+
const bucketLeaves = indices.map((index) => (0, treeMathInternal_js_1.requireTreeItem)(leaves, index));
|
|
34
37
|
// Called only to throw on incompatible group members.
|
|
35
38
|
index_js_1.OfferUtils.validateOfferGroup({
|
|
36
39
|
offers: bucketLeaves.map((leaf) => leaf.offer),
|
|
@@ -41,13 +44,17 @@ function assignRatifierV1Groups(leaves, groupId) {
|
|
|
41
44
|
}
|
|
42
45
|
const group = groupId(bucketLeaves);
|
|
43
46
|
for (const index of indices) {
|
|
44
|
-
offers[index] = index_js_1.Offer.from({
|
|
47
|
+
offers[index] = index_js_1.Offer.from({
|
|
48
|
+
...(0, treeMathInternal_js_1.requireTreeItem)(leaves, index).offer,
|
|
49
|
+
group,
|
|
50
|
+
});
|
|
45
51
|
}
|
|
46
52
|
}
|
|
47
53
|
const finalGroups = new Map();
|
|
48
54
|
for (const [index, offer] of offers.entries()) {
|
|
49
55
|
const label = offer.group.toLowerCase();
|
|
50
|
-
const hasExplicitGroup = leaves
|
|
56
|
+
const hasExplicitGroup = (0, treeMathInternal_js_1.requireTreeItem)(leaves, index).offer
|
|
57
|
+
.hasExplicitGroup;
|
|
51
58
|
const bucket = finalGroups.get(label);
|
|
52
59
|
if (bucket) {
|
|
53
60
|
bucket.offers.push(offer);
|
|
@@ -58,8 +65,9 @@ function assignRatifierV1Groups(leaves, groupId) {
|
|
|
58
65
|
}
|
|
59
66
|
}
|
|
60
67
|
for (const { offers: groupOffers, hasExplicitGroup, } of finalGroups.values()) {
|
|
61
|
-
if (!hasExplicitGroup)
|
|
68
|
+
if (!hasExplicitGroup) {
|
|
62
69
|
continue;
|
|
70
|
+
}
|
|
63
71
|
// Catches explicit groups that collide with a defaulted or re-derived id.
|
|
64
72
|
index_js_1.OfferUtils.validateOfferGroup({ offers: groupOffers });
|
|
65
73
|
}
|
|
@@ -85,9 +93,9 @@ function buildRatifierV1Descriptor(params) {
|
|
|
85
93
|
throw new errors_js_1.InvalidTreeError(`All offers in a ${label} tree must use one ratifier; expected "${ratifier}", got "${other}". Build separate trees per ratifier.`);
|
|
86
94
|
}
|
|
87
95
|
}
|
|
88
|
-
const
|
|
96
|
+
const leaves = entries.map(hashLeaf);
|
|
89
97
|
const seen = new Set();
|
|
90
|
-
for (const leafHash of
|
|
98
|
+
for (const leafHash of leaves) {
|
|
91
99
|
if (seen.has(leafHash)) {
|
|
92
100
|
throw new errors_js_1.InvalidTreeError(`Duplicate leaf hash "${leafHash}" in tree.`);
|
|
93
101
|
}
|
|
@@ -100,11 +108,12 @@ function buildRatifierV1Descriptor(params) {
|
|
|
100
108
|
...entries,
|
|
101
109
|
...Array.from({ length: paddingCount }, () => padding),
|
|
102
110
|
];
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
111
|
+
if (paddingCount > 0) {
|
|
112
|
+
const paddingHash = hashLeaf(padding);
|
|
113
|
+
for (let index = 0; index < paddingCount; index++) {
|
|
114
|
+
leaves.push(paddingHash);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
108
117
|
const { root, height } = TreeUtils_js_1.TreeUtils.buildRootFromLeaves(leaves);
|
|
109
118
|
return { entries: paddedEntries, leaves, root, height };
|
|
110
119
|
}
|
|
@@ -120,8 +129,9 @@ function buildRatifierV1Descriptor(params) {
|
|
|
120
129
|
*/
|
|
121
130
|
function resolveRatifierV1Tree(tree, helpers) {
|
|
122
131
|
const { buildDescriptor, hashLeaf, isPadding, ratifierOf, label } = helpers;
|
|
123
|
-
if (Array.isArray(tree))
|
|
132
|
+
if (Array.isArray(tree)) {
|
|
124
133
|
return buildDescriptor(tree);
|
|
134
|
+
}
|
|
125
135
|
const descriptor = tree;
|
|
126
136
|
if ("type" in descriptor &&
|
|
127
137
|
descriptor.type != null &&
|
|
@@ -142,8 +152,9 @@ function resolveRatifierV1Tree(tree, helpers) {
|
|
|
142
152
|
expectedLength !== (0, treeMathInternal_js_1.nextPowerOfTwo)(descriptor.offers.length)) {
|
|
143
153
|
throw new errors_js_1.InvalidTreeError("Tree entries, leaves, offers, and height describe different trees.");
|
|
144
154
|
}
|
|
145
|
-
const
|
|
146
|
-
const
|
|
155
|
+
const entries = Array.from({ length: expectedLength }, (_, index) => (0, treeMathInternal_js_1.requireTreeItem)(descriptor.entries, index));
|
|
156
|
+
const visibleEntries = entries.slice(0, descriptor.offers.length);
|
|
157
|
+
const ratifier = ratifierOf((0, treeMathInternal_js_1.requireTreeItem)(visibleEntries, 0));
|
|
147
158
|
for (const entry of visibleEntries.slice(1)) {
|
|
148
159
|
const other = ratifierOf(entry);
|
|
149
160
|
if (!(0, viem_1.isAddressEqual)(other, ratifier)) {
|
|
@@ -157,25 +168,24 @@ function resolveRatifierV1Tree(tree, helpers) {
|
|
|
157
168
|
}
|
|
158
169
|
helpers.validateEntry?.(entry);
|
|
159
170
|
}
|
|
160
|
-
const computedLeaves =
|
|
171
|
+
const computedLeaves = entries.map((entry) => hashLeaf(entry));
|
|
161
172
|
const seen = new Set();
|
|
162
173
|
for (const [index, offer] of descriptor.offers.entries()) {
|
|
163
|
-
const entry =
|
|
174
|
+
const entry = (0, treeMathInternal_js_1.requireTreeItem)(entries, index);
|
|
164
175
|
if (index_js_1.OfferUtils.hashStruct(index_js_1.OfferUtils.toStruct({ offer: index_js_1.Offer.from(offer) })).toLowerCase() !== index_js_1.OfferUtils.hashStruct(entry.offer).toLowerCase()) {
|
|
165
176
|
throw new errors_js_1.InvalidTreeError("Visible offers do not match the tree entries.");
|
|
166
177
|
}
|
|
167
|
-
const leafHash = computedLeaves
|
|
178
|
+
const leafHash = (0, treeMathInternal_js_1.requireTreeItem)(computedLeaves, index).toLowerCase();
|
|
168
179
|
if (seen.has(leafHash)) {
|
|
169
180
|
throw new errors_js_1.InvalidTreeError(`Duplicate leaf hash "${leafHash}" in tree.`);
|
|
170
181
|
}
|
|
171
182
|
seen.add(leafHash);
|
|
172
183
|
}
|
|
173
|
-
if (descriptor.
|
|
174
|
-
.slice(descriptor.offers.length)
|
|
175
|
-
.some((entry) => !isPadding(entry))) {
|
|
184
|
+
if (entries.slice(descriptor.offers.length).some((entry) => !isPadding(entry))) {
|
|
176
185
|
throw new errors_js_1.InvalidTreeError("Tree padding contains entries hidden from the visible offer list.");
|
|
177
186
|
}
|
|
178
|
-
if (computedLeaves.some((leaf, index) => leaf.toLowerCase() !==
|
|
187
|
+
if (computedLeaves.some((leaf, index) => leaf.toLowerCase() !==
|
|
188
|
+
(0, treeMathInternal_js_1.requireTreeItem)(descriptor.leaves, index).toLowerCase())) {
|
|
179
189
|
throw new errors_js_1.InvalidTreeError("Tree leaves do not match its entries.");
|
|
180
190
|
}
|
|
181
191
|
if (TreeUtils_js_1.TreeUtils.buildRootFromLeaves(descriptor.leaves).root.toLowerCase() !==
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** @internal Reads a tree item at a required index, rejecting missing entries. */
|
|
2
|
+
export declare function requireTreeItem<T>(items: readonly T[], index: number): T;
|
|
1
3
|
/** @internal Returns whether `value` is a positive power of two. */
|
|
2
4
|
export declare function isPowerOfTwo(value: number): boolean;
|
|
3
5
|
/** @internal Returns the smallest power of two greater than or equal to `value`. */
|
|
@@ -1,7 +1,17 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.requireTreeItem = requireTreeItem;
|
|
3
4
|
exports.isPowerOfTwo = isPowerOfTwo;
|
|
4
5
|
exports.nextPowerOfTwo = nextPowerOfTwo;
|
|
6
|
+
const errors_js_1 = require("../errors.js");
|
|
7
|
+
/** @internal Reads a tree item at a required index, rejecting missing entries. */
|
|
8
|
+
function requireTreeItem(items, index) {
|
|
9
|
+
const item = items[index];
|
|
10
|
+
if (item == null) {
|
|
11
|
+
throw new errors_js_1.InvalidTreeError(`Tree item at index "${index}" is missing.`);
|
|
12
|
+
}
|
|
13
|
+
return item;
|
|
14
|
+
}
|
|
5
15
|
/** @internal Returns whether `value` is a positive power of two. */
|
|
6
16
|
function isPowerOfTwo(value) {
|
|
7
17
|
return value > 0 && (value & (value - 1)) === 0;
|
package/lib/cjs/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** Installed @morpho-org/midnight-sdk package version. */
|
|
2
|
-
export declare const version = "2.
|
|
2
|
+
export declare const version = "2.8.0-next.0";
|
package/lib/cjs/version.js
CHANGED
|
@@ -3,6 +3,56 @@ import { InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, }
|
|
|
3
3
|
import { TakeAmountsLib } from "../math/index.js";
|
|
4
4
|
import { Payload } from "../signatures/Payload.js";
|
|
5
5
|
import { buildBookPath, mapBoundBookMarket, mapBoundBooks, mapBoundTakeableOffers, mapPriceLevels, parseResponseCursor, parseValidationResponse, requestMidnightApi, requireBigIntString, requireObject, requireResponseEnvelope, } from "./helpers.js";
|
|
6
|
+
function computeQuoteFillByUnits({ side, settlementFee, takeableOffers }, units) {
|
|
7
|
+
let remainingUnits = units;
|
|
8
|
+
let filledUnits = 0n;
|
|
9
|
+
let filledAssets = 0n;
|
|
10
|
+
for (const take of takeableOffers) {
|
|
11
|
+
if (remainingUnits === 0n) {
|
|
12
|
+
break;
|
|
13
|
+
}
|
|
14
|
+
const { buyerPrice, sellerPrice } = TakeAmountsLib.prices({
|
|
15
|
+
offer: take.offer,
|
|
16
|
+
settlementFee,
|
|
17
|
+
});
|
|
18
|
+
const price = side === "asks" ? buyerPrice : sellerPrice;
|
|
19
|
+
const filled = take.units < remainingUnits ? take.units : remainingUnits;
|
|
20
|
+
filledUnits += filled;
|
|
21
|
+
filledAssets += MathLib.mulDiv(filled, price, MathLib.WAD, side === "asks" ? "Up" : "Down");
|
|
22
|
+
remainingUnits -= filled;
|
|
23
|
+
}
|
|
24
|
+
return { filledUnits, filledAssets };
|
|
25
|
+
}
|
|
26
|
+
function computeQuoteFillByAssets({ side, settlementFee, takeableOffers }, assets) {
|
|
27
|
+
let remainingAssets = assets;
|
|
28
|
+
let filledUnits = 0n;
|
|
29
|
+
let filledAssets = 0n;
|
|
30
|
+
for (const take of takeableOffers) {
|
|
31
|
+
if (remainingAssets === 0n) {
|
|
32
|
+
break;
|
|
33
|
+
}
|
|
34
|
+
const { buyerPrice, sellerPrice } = TakeAmountsLib.prices({
|
|
35
|
+
offer: take.offer,
|
|
36
|
+
settlementFee,
|
|
37
|
+
});
|
|
38
|
+
const makerPrice = side === "asks" ? sellerPrice : buyerPrice;
|
|
39
|
+
const settlementPrice = side === "asks" ? buyerPrice : sellerPrice;
|
|
40
|
+
const takeMakerAssets = side === "asks"
|
|
41
|
+
? MathLib.mulDivUp(take.units, makerPrice, MathLib.WAD)
|
|
42
|
+
: MathLib.mulDivDown(take.units, makerPrice, MathLib.WAD);
|
|
43
|
+
const fillsEntireTake = takeMakerAssets <= remainingAssets;
|
|
44
|
+
const filled = fillsEntireTake
|
|
45
|
+
? take.units
|
|
46
|
+
: MathLib.mulDiv(remainingAssets, MathLib.WAD, makerPrice, side === "asks" ? "Down" : "Up");
|
|
47
|
+
if (filled === 0n) {
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
filledUnits += filled;
|
|
51
|
+
filledAssets += MathLib.mulDiv(filled, settlementPrice, MathLib.WAD, side === "asks" ? "Up" : "Down");
|
|
52
|
+
remainingAssets = fillsEntireTake ? remainingAssets - takeMakerAssets : 0n;
|
|
53
|
+
}
|
|
54
|
+
return { filledUnits, filledAssets };
|
|
55
|
+
}
|
|
6
56
|
export { MempoolPayloadValidationRule } from "./types.js";
|
|
7
57
|
/**
|
|
8
58
|
* Midnight API client and stateless helper surface for books and mempool data.
|
|
@@ -279,8 +329,9 @@ export class MidnightApi {
|
|
|
279
329
|
*/
|
|
280
330
|
static async fetchBookQuote(params) {
|
|
281
331
|
const input = params;
|
|
282
|
-
if ((input.units == null) === (input.assets == null))
|
|
332
|
+
if ((input.units == null) === (input.assets == null)) {
|
|
283
333
|
throw new InvalidMidnightApiQuoteTargetError();
|
|
334
|
+
}
|
|
284
335
|
const settlementFee = BigInt(input.settlementFee ?? 0n);
|
|
285
336
|
assertNonNegative("settlementFee", settlementFee);
|
|
286
337
|
const response = await requestMidnightApi({
|
|
@@ -310,58 +361,18 @@ export class MidnightApi {
|
|
|
310
361
|
side: input.side,
|
|
311
362
|
taker: input.taker,
|
|
312
363
|
});
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
364
|
+
let guard;
|
|
365
|
+
if ("averageWorstPrice" in input && input.averageWorstPrice != null) {
|
|
366
|
+
guard = BigInt(input.averageWorstPrice);
|
|
367
|
+
}
|
|
368
|
+
else if ("slippage" in input && input.slippage != null) {
|
|
369
|
+
guard = BigInt(responseAverageWorstPrice);
|
|
370
|
+
}
|
|
319
371
|
if (guard != null) {
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
for (const take of takeableOffers) {
|
|
325
|
-
if (remainingUnits === 0n)
|
|
326
|
-
break;
|
|
327
|
-
const { buyerPrice, sellerPrice } = TakeAmountsLib.prices({
|
|
328
|
-
offer: take.offer,
|
|
329
|
-
settlementFee,
|
|
330
|
-
});
|
|
331
|
-
const price = input.side === "asks" ? buyerPrice : sellerPrice;
|
|
332
|
-
const filled = take.units < remainingUnits ? take.units : remainingUnits;
|
|
333
|
-
filledUnits += filled;
|
|
334
|
-
filledAssets += MathLib.mulDiv(filled, price, MathLib.WAD, input.side === "asks" ? "Up" : "Down");
|
|
335
|
-
remainingUnits -= filled;
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
else {
|
|
339
|
-
let remainingAssets = BigInt(input.assets);
|
|
340
|
-
for (const take of takeableOffers) {
|
|
341
|
-
if (remainingAssets === 0n)
|
|
342
|
-
break;
|
|
343
|
-
const { buyerPrice, sellerPrice } = TakeAmountsLib.prices({
|
|
344
|
-
offer: take.offer,
|
|
345
|
-
settlementFee,
|
|
346
|
-
});
|
|
347
|
-
const makerPrice = input.side === "asks" ? sellerPrice : buyerPrice;
|
|
348
|
-
const settlementPrice = input.side === "asks" ? buyerPrice : sellerPrice;
|
|
349
|
-
const takeMakerAssets = input.side === "asks"
|
|
350
|
-
? MathLib.mulDivUp(take.units, makerPrice, MathLib.WAD)
|
|
351
|
-
: MathLib.mulDivDown(take.units, makerPrice, MathLib.WAD);
|
|
352
|
-
const fillsEntireTake = takeMakerAssets <= remainingAssets;
|
|
353
|
-
const filled = fillsEntireTake
|
|
354
|
-
? take.units
|
|
355
|
-
: MathLib.mulDiv(remainingAssets, MathLib.WAD, makerPrice, input.side === "asks" ? "Down" : "Up");
|
|
356
|
-
if (filled === 0n)
|
|
357
|
-
continue;
|
|
358
|
-
filledUnits += filled;
|
|
359
|
-
filledAssets += MathLib.mulDiv(filled, settlementPrice, MathLib.WAD, input.side === "asks" ? "Up" : "Down");
|
|
360
|
-
remainingAssets = fillsEntireTake
|
|
361
|
-
? remainingAssets - takeMakerAssets
|
|
362
|
-
: 0n;
|
|
363
|
-
}
|
|
364
|
-
}
|
|
372
|
+
const settlement = { side: input.side, settlementFee, takeableOffers };
|
|
373
|
+
const { filledUnits, filledAssets } = "units" in input && input.units != null
|
|
374
|
+
? computeQuoteFillByUnits(settlement, BigInt(input.units))
|
|
375
|
+
: computeQuoteFillByAssets(settlement, BigInt(input.assets));
|
|
365
376
|
if (filledUnits > 0n) {
|
|
366
377
|
const averagePrice = MathLib.mulDiv(filledAssets, MathLib.WAD, filledUnits, input.side === "asks" ? "Up" : "Down");
|
|
367
378
|
const violatesGuard = input.side === "asks" ? averagePrice > guard : averagePrice < guard;
|
package/lib/esm/api/helpers.js
CHANGED
|
@@ -24,20 +24,24 @@ export async function requestMidnightApi(params) {
|
|
|
24
24
|
url.hash = "";
|
|
25
25
|
if (params.query != null) {
|
|
26
26
|
for (const [key, value] of Object.entries(params.query)) {
|
|
27
|
-
if (value === undefined)
|
|
27
|
+
if (value === undefined) {
|
|
28
28
|
continue;
|
|
29
|
-
|
|
29
|
+
}
|
|
30
|
+
if (Array.isArray(value) && value.length === 0) {
|
|
30
31
|
continue;
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
32
|
+
}
|
|
33
|
+
if (Array.isArray(value)) {
|
|
34
|
+
url.searchParams.set(key, value.map(String).join(","));
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
url.searchParams.set(key, value instanceof Date ? value.toISOString() : String(value));
|
|
38
|
+
}
|
|
36
39
|
}
|
|
37
40
|
}
|
|
38
41
|
const headers = new Headers(params.request?.headers);
|
|
39
|
-
if (params.body !== undefined)
|
|
42
|
+
if (params.body !== undefined) {
|
|
40
43
|
headers.set("Content-Type", "application/json");
|
|
44
|
+
}
|
|
41
45
|
headers.set("sdk-version", version);
|
|
42
46
|
const init = {
|
|
43
47
|
...params.request,
|
|
@@ -332,8 +336,9 @@ export function mapBoundTakeableOffers(takeableOffers, context) {
|
|
|
332
336
|
});
|
|
333
337
|
}
|
|
334
338
|
catch (cause) {
|
|
335
|
-
if (!(cause instanceof InvalidOfferParameterError))
|
|
339
|
+
if (!(cause instanceof InvalidOfferParameterError)) {
|
|
336
340
|
throw cause;
|
|
341
|
+
}
|
|
337
342
|
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer for market_id "${take.marketId}" is not executable: ${cause.message}`, { cause });
|
|
338
343
|
}
|
|
339
344
|
if (maxUnits > 0n && take.units > maxUnits) {
|
|
@@ -370,13 +375,16 @@ export function mapBoundTakeableOffers(takeableOffers, context) {
|
|
|
370
375
|
}
|
|
371
376
|
return take;
|
|
372
377
|
});
|
|
373
|
-
if (context.side == null)
|
|
378
|
+
if (context.side == null) {
|
|
374
379
|
return mapped;
|
|
380
|
+
}
|
|
375
381
|
return [...mapped].sort((a, b) => {
|
|
376
|
-
if (a.offer.tick === b.offer.tick)
|
|
382
|
+
if (a.offer.tick === b.offer.tick) {
|
|
377
383
|
return 0;
|
|
378
|
-
|
|
384
|
+
}
|
|
385
|
+
if (context.side === "asks") {
|
|
379
386
|
return a.offer.tick < b.offer.tick ? -1 : 1;
|
|
387
|
+
}
|
|
380
388
|
return a.offer.tick > b.offer.tick ? -1 : 1;
|
|
381
389
|
});
|
|
382
390
|
}
|
|
@@ -394,8 +402,9 @@ export function parseValidationResponse(response) {
|
|
|
394
402
|
throw new InvalidMidnightApiResponseError('Midnight API validation issue is missing "rule".');
|
|
395
403
|
}
|
|
396
404
|
const details = record.details;
|
|
397
|
-
if (details == null)
|
|
405
|
+
if (details == null) {
|
|
398
406
|
return { rule };
|
|
407
|
+
}
|
|
399
408
|
if (rule === MempoolPayloadValidationRule.MinOfferAssetsUsd &&
|
|
400
409
|
isRecord(details)) {
|
|
401
410
|
const loanToken = details.loan_token;
|
|
@@ -449,10 +458,12 @@ export function requireResponseEnvelope(response, context) {
|
|
|
449
458
|
}
|
|
450
459
|
/** @internal Parses a paginated response cursor, treating a missing cursor as the last page. */
|
|
451
460
|
export function parseResponseCursor(cursor, context) {
|
|
452
|
-
if (cursor == null)
|
|
461
|
+
if (cursor == null) {
|
|
453
462
|
return null;
|
|
454
|
-
|
|
463
|
+
}
|
|
464
|
+
if (typeof cursor === "string") {
|
|
455
465
|
return cursor;
|
|
466
|
+
}
|
|
456
467
|
throw new InvalidMidnightApiResponseError(`Midnight API ${context} cursor is malformed.`);
|
|
457
468
|
}
|
|
458
469
|
/** @internal Returns `value` when it is a decimal string of a uint256. */
|
|
@@ -466,14 +477,16 @@ export function requireBigIntString(value, context) {
|
|
|
466
477
|
throw new InvalidMidnightApiResponseError(`Midnight API ${context} (${typeof value}) is not a decimal uint256 string.`);
|
|
467
478
|
}
|
|
468
479
|
function requireArray(value, context) {
|
|
469
|
-
if (Array.isArray(value))
|
|
480
|
+
if (Array.isArray(value)) {
|
|
470
481
|
return value;
|
|
482
|
+
}
|
|
471
483
|
throw new InvalidMidnightApiResponseError(`Midnight API ${context} is malformed.`);
|
|
472
484
|
}
|
|
473
485
|
/** @internal Returns `value` when it is a plain object, else throws `InvalidMidnightApiResponseError`. */
|
|
474
486
|
function requireRecord(value, context) {
|
|
475
|
-
if (isRecord(value))
|
|
487
|
+
if (isRecord(value)) {
|
|
476
488
|
return value;
|
|
489
|
+
}
|
|
477
490
|
throw new InvalidMidnightApiResponseError(`Midnight API ${context} is malformed.`);
|
|
478
491
|
}
|
|
479
492
|
function isRecord(value) {
|
|
@@ -72,8 +72,9 @@ export async function fetchPosition(client, params) {
|
|
|
72
72
|
});
|
|
73
73
|
}
|
|
74
74
|
catch (error) {
|
|
75
|
-
if (params.deployless === "force")
|
|
75
|
+
if (params.deployless === "force") {
|
|
76
76
|
throw error;
|
|
77
|
+
}
|
|
77
78
|
// Fallback to direct reads if deployless execution is unavailable.
|
|
78
79
|
}
|
|
79
80
|
}
|
|
@@ -39,13 +39,12 @@ export async function fetchRatifierInfo(client, params) {
|
|
|
39
39
|
const chainId = await resolveChainId(client);
|
|
40
40
|
const ecrecoverRatifier = getChainAddress(chainId, "ecrecoverRatifier");
|
|
41
41
|
const setterRatifier = getChainAddress(chainId, "setterRatifier");
|
|
42
|
+
const block = params.blockNumber == null
|
|
43
|
+
? { blockTag: params.blockTag ?? undefined }
|
|
44
|
+
: { blockNumber: params.blockNumber };
|
|
42
45
|
// eth_getCode is trusted; the returned ratifier is a suggestion the caller commits to on Offer.create. See THREAT_MODEL.md, RPC.
|
|
43
46
|
const bytecode = await getBytecode(client, {
|
|
44
|
-
...
|
|
45
|
-
? { blockNumber: params.blockNumber }
|
|
46
|
-
: params.blockTag != null
|
|
47
|
-
? { blockTag: params.blockTag }
|
|
48
|
-
: {}),
|
|
47
|
+
...block,
|
|
49
48
|
address: params.maker,
|
|
50
49
|
});
|
|
51
50
|
return Ratifier.getRatifierInfo({
|
package/lib/esm/market/Market.js
CHANGED
|
@@ -171,8 +171,9 @@ export class MarketParams {
|
|
|
171
171
|
* ```
|
|
172
172
|
*/
|
|
173
173
|
static from(market) {
|
|
174
|
-
if ("params" in market)
|
|
174
|
+
if ("params" in market) {
|
|
175
175
|
return MarketParams.from(market.params);
|
|
176
|
+
}
|
|
176
177
|
return market instanceof MarketParams ? market : new MarketParams(market);
|
|
177
178
|
}
|
|
178
179
|
}
|
|
@@ -66,8 +66,9 @@ export var MarketUtils;
|
|
|
66
66
|
function compareCollateralTokens(a, b) {
|
|
67
67
|
const tokenA = a.token.toLowerCase();
|
|
68
68
|
const tokenB = b.token.toLowerCase();
|
|
69
|
-
if (tokenA === tokenB)
|
|
69
|
+
if (tokenA === tokenB) {
|
|
70
70
|
return 0;
|
|
71
|
+
}
|
|
71
72
|
return tokenA < tokenB ? -1 : 1;
|
|
72
73
|
}
|
|
73
74
|
MarketUtils.compareCollateralTokens = compareCollateralTokens;
|
|
@@ -260,20 +261,21 @@ export var MarketUtils;
|
|
|
260
261
|
function getSettlementFee(params) {
|
|
261
262
|
const timeToMaturity = BigInt(params.timeToMaturity);
|
|
262
263
|
assertNonNegative("timeToMaturity", timeToMaturity);
|
|
263
|
-
const
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
264
|
+
const upperBucketIndices = [1, 2, 3, 4, 5, 6];
|
|
265
|
+
let lowerIndex = 0;
|
|
266
|
+
for (const upperIndex of upperBucketIndices) {
|
|
267
|
+
const end = SETTLEMENT_FEE_BREAKPOINTS[upperIndex];
|
|
268
|
+
if (timeToMaturity < end) {
|
|
269
|
+
const start = SETTLEMENT_FEE_BREAKPOINTS[lowerIndex];
|
|
270
|
+
const feeLower = BigInt(params.settlementFeeCbps[lowerIndex]) * CBP;
|
|
271
|
+
const feeUpper = BigInt(params.settlementFeeCbps[upperIndex]) * CBP;
|
|
272
|
+
return ((feeLower * (end - timeToMaturity) +
|
|
273
|
+
feeUpper * (timeToMaturity - start)) /
|
|
274
|
+
(end - start));
|
|
275
|
+
}
|
|
276
|
+
lowerIndex = upperIndex;
|
|
267
277
|
}
|
|
268
|
-
|
|
269
|
-
const lowerIndex = upperIndex - 1;
|
|
270
|
-
const start = SETTLEMENT_FEE_BREAKPOINTS[lowerIndex];
|
|
271
|
-
const end = SETTLEMENT_FEE_BREAKPOINTS[upperIndex];
|
|
272
|
-
const feeLower = BigInt(params.settlementFeeCbps[lowerIndex]) * CBP;
|
|
273
|
-
const feeUpper = BigInt(params.settlementFeeCbps[upperIndex]) * CBP;
|
|
274
|
-
return ((feeLower * (end - timeToMaturity) +
|
|
275
|
-
feeUpper * (timeToMaturity - start)) /
|
|
276
|
-
(end - start));
|
|
278
|
+
return BigInt(params.settlementFeeCbps[lowerIndex]) * CBP;
|
|
277
279
|
}
|
|
278
280
|
MarketUtils.getSettlementFee = getSettlementFee;
|
|
279
281
|
/**
|
|
@@ -87,10 +87,12 @@ export var TakeAmountsLib;
|
|
|
87
87
|
const targetBuyerAssets = BigInt(params.targetBuyerAssets);
|
|
88
88
|
assertNonNegative("targetBuyerAssets", targetBuyerAssets);
|
|
89
89
|
const { buyerPrice } = prices({ offer: params.offer, settlementFee });
|
|
90
|
-
if (buyerPrice === 0n)
|
|
90
|
+
if (buyerPrice === 0n) {
|
|
91
91
|
throw new DivisionByZeroError("buyerPrice");
|
|
92
|
-
|
|
92
|
+
}
|
|
93
|
+
if (buyerPrice > MathLib.WAD) {
|
|
93
94
|
throw new PriceGreaterThanOneError(buyerPrice);
|
|
95
|
+
}
|
|
94
96
|
return MathLib.mulDiv(targetBuyerAssets, MathLib.WAD, buyerPrice, params.offer.buy ? "Up" : "Down");
|
|
95
97
|
}
|
|
96
98
|
TakeAmountsLib.buyerAssetsToUnits = buyerAssetsToUnits;
|
|
@@ -130,8 +132,9 @@ export var TakeAmountsLib;
|
|
|
130
132
|
const targetSellerAssets = BigInt(params.targetSellerAssets);
|
|
131
133
|
assertNonNegative("targetSellerAssets", targetSellerAssets);
|
|
132
134
|
const { sellerPrice } = prices({ offer: params.offer, settlementFee });
|
|
133
|
-
if (sellerPrice === 0n)
|
|
135
|
+
if (sellerPrice === 0n) {
|
|
134
136
|
throw new DivisionByZeroError("sellerPrice");
|
|
137
|
+
}
|
|
135
138
|
return MathLib.mulDiv(targetSellerAssets, MathLib.WAD, sellerPrice, params.offer.buy ? "Up" : "Down");
|
|
136
139
|
}
|
|
137
140
|
TakeAmountsLib.sellerAssetsToUnits = sellerAssetsToUnits;
|
|
@@ -160,8 +163,9 @@ export var TakeAmountsLib;
|
|
|
160
163
|
const price = BigInt(params.price);
|
|
161
164
|
assertNonNegative("assets", assets);
|
|
162
165
|
assertNonNegative("price", price);
|
|
163
|
-
if (price === 0n)
|
|
166
|
+
if (price === 0n) {
|
|
164
167
|
throw new DivisionByZeroError("price");
|
|
168
|
+
}
|
|
165
169
|
return MathLib.mulDiv(assets, MathLib.WAD, price, params.rounding);
|
|
166
170
|
}
|
|
167
171
|
TakeAmountsLib.toUnits = toUnits;
|
package/lib/esm/math/TickLib.js
CHANGED
|
@@ -79,8 +79,9 @@ export var TickLib;
|
|
|
79
79
|
TickLib.assertTickInRange = (tick) => {
|
|
80
80
|
const tickValue = BigInt(tick);
|
|
81
81
|
assertNonNegative("tick", tickValue);
|
|
82
|
-
if (tickValue > MAX_TICK)
|
|
82
|
+
if (tickValue > MAX_TICK) {
|
|
83
83
|
throw new TickOutOfRangeError(tickValue, MAX_TICK);
|
|
84
|
+
}
|
|
84
85
|
return tickValue;
|
|
85
86
|
};
|
|
86
87
|
/**
|
|
@@ -97,8 +98,9 @@ export var TickLib;
|
|
|
97
98
|
* ```
|
|
98
99
|
*/
|
|
99
100
|
TickLib.wExp = (x) => {
|
|
100
|
-
if (x < 0n)
|
|
101
|
+
if (x < 0n) {
|
|
101
102
|
return 1000000000000000000000000000000000000n / TickLib.wExp(-x);
|
|
103
|
+
}
|
|
102
104
|
const q = (x + TickLib.EXP_OFFSET) / TickLib.LN_2;
|
|
103
105
|
const r = x - q * TickLib.LN_2;
|
|
104
106
|
const secondTerm = (r * r) / (2n * MathLib.WAD);
|
|
@@ -149,8 +151,9 @@ export var TickLib;
|
|
|
149
151
|
const priceValue = BigInt(price);
|
|
150
152
|
const spacingValue = BigInt(spacing);
|
|
151
153
|
assertNonNegative("price", priceValue);
|
|
152
|
-
if (priceValue > MathLib.WAD)
|
|
154
|
+
if (priceValue > MathLib.WAD) {
|
|
153
155
|
throw new PriceGreaterThanOneError(priceValue);
|
|
156
|
+
}
|
|
154
157
|
if (spacingValue <= 0n || MAX_TICK % spacingValue !== 0n) {
|
|
155
158
|
throw new InvalidTickSpacingError(spacingValue);
|
|
156
159
|
}
|
|
@@ -158,10 +161,12 @@ export var TickLib;
|
|
|
158
161
|
let high = MAX_TICK;
|
|
159
162
|
while (low !== high) {
|
|
160
163
|
const mid = (low + high) / 2n;
|
|
161
|
-
if (tickToPrice(mid) < priceValue)
|
|
164
|
+
if (tickToPrice(mid) < priceValue) {
|
|
162
165
|
low = mid + 1n;
|
|
163
|
-
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
164
168
|
high = mid;
|
|
169
|
+
}
|
|
165
170
|
}
|
|
166
171
|
return ((low + spacingValue - 1n) / spacingValue) * spacingValue;
|
|
167
172
|
}
|
|
@@ -231,8 +236,9 @@ export var TickLib;
|
|
|
231
236
|
*/
|
|
232
237
|
function tickToRate(tick) {
|
|
233
238
|
const price = tickToPrice(tick);
|
|
234
|
-
if (price === 0n)
|
|
239
|
+
if (price === 0n) {
|
|
235
240
|
throw new DivisionByZeroError("price");
|
|
241
|
+
}
|
|
236
242
|
return MathLib.mulDiv(MathLib.WAD, MathLib.WAD, price, "Up") - MathLib.WAD;
|
|
237
243
|
}
|
|
238
244
|
TickLib.tickToRate = tickToRate;
|