@morpho-org/midnight-sdk 2.7.0 → 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/errors.d.ts +13 -27
- package/lib/cjs/errors.js +8 -39
- 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 +17 -17
- 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/position/PositionUtils.js +11 -35
- 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/errors.d.ts +13 -27
- package/lib/esm/errors.js +8 -36
- 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 +19 -19
- 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/position/PositionUtils.js +12 -36
- 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 +4 -4
|
@@ -76,8 +76,9 @@ class Tree {
|
|
|
76
76
|
this.height = descriptor.height;
|
|
77
77
|
}
|
|
78
78
|
static from(tree) {
|
|
79
|
-
if (tree instanceof Tree)
|
|
79
|
+
if (tree instanceof Tree) {
|
|
80
80
|
return tree;
|
|
81
|
+
}
|
|
81
82
|
// Portable snapshots resume through descriptor validation instead of rebuilding.
|
|
82
83
|
if (!Array.isArray(tree) &&
|
|
83
84
|
"entries" in tree &&
|
|
@@ -87,8 +88,9 @@ class Tree {
|
|
|
87
88
|
? Tree.fromDescriptor(tree)
|
|
88
89
|
: Tree.fromDescriptor(tree);
|
|
89
90
|
}
|
|
90
|
-
if ("type" in tree && tree.type != null)
|
|
91
|
+
if ("type" in tree && tree.type != null) {
|
|
91
92
|
return Tree.create(tree);
|
|
93
|
+
}
|
|
92
94
|
return Tree.create(Array.isArray(tree) ? tree : [tree]);
|
|
93
95
|
}
|
|
94
96
|
static create(params) {
|
|
@@ -175,10 +177,12 @@ class Tree {
|
|
|
175
177
|
? index_js_1.OfferUtils.toStruct({ offer })
|
|
176
178
|
: offer),
|
|
177
179
|
};
|
|
178
|
-
if (descriptor.type === "ecrecover")
|
|
180
|
+
if (descriptor.type === "ecrecover") {
|
|
179
181
|
return new Tree("ecrecover", normalized);
|
|
180
|
-
|
|
182
|
+
}
|
|
183
|
+
if (descriptor.type === "setter") {
|
|
181
184
|
return new Tree("setter", normalized);
|
|
185
|
+
}
|
|
182
186
|
return new Tree(undefined, normalized);
|
|
183
187
|
}
|
|
184
188
|
default:
|
|
@@ -19,8 +19,9 @@ const SetterRatifier_js_1 = require("./SetterRatifier.js");
|
|
|
19
19
|
const Tree_js_1 = require("./Tree.js");
|
|
20
20
|
const treeMathInternal_js_1 = require("./treeMathInternal.js");
|
|
21
21
|
function padOfferStructs(offers) {
|
|
22
|
-
if ((0, treeMathInternal_js_1.isPowerOfTwo)(offers.length))
|
|
22
|
+
if ((0, treeMathInternal_js_1.isPowerOfTwo)(offers.length)) {
|
|
23
23
|
return [...offers];
|
|
24
|
+
}
|
|
24
25
|
const paddedLength = (0, treeMathInternal_js_1.nextPowerOfTwo)(offers.length);
|
|
25
26
|
return [
|
|
26
27
|
...offers,
|
|
@@ -30,9 +31,10 @@ function padOfferStructs(offers) {
|
|
|
30
31
|
function assertLeafOffers(offers, leafHashes) {
|
|
31
32
|
const seen = new Set();
|
|
32
33
|
for (const [index, offer] of offers.entries()) {
|
|
33
|
-
if ((0, offerStructInternal_js_1.isEmptyOfferStruct)(offer, { allowDefaultGroup: true }))
|
|
34
|
+
if ((0, offerStructInternal_js_1.isEmptyOfferStruct)(offer, { allowDefaultGroup: true })) {
|
|
34
35
|
continue;
|
|
35
|
-
|
|
36
|
+
}
|
|
37
|
+
const leafHash = (0, treeMathInternal_js_1.requireTreeItem)(leafHashes, index);
|
|
36
38
|
if (seen.has(leafHash)) {
|
|
37
39
|
throw new errors_js_1.InvalidTreeError(`Duplicate offer hash "${leafHash}" in tree.`);
|
|
38
40
|
}
|
|
@@ -44,12 +46,12 @@ function assertLeafOffers(offers, leafHashes) {
|
|
|
44
46
|
}
|
|
45
47
|
}
|
|
46
48
|
function buildLayers(leaves) {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
+
let level = [...leaves];
|
|
50
|
+
const layers = [level];
|
|
49
51
|
while (level.length > 1) {
|
|
50
52
|
const next = [];
|
|
51
53
|
for (let i = 0; i < level.length; i += 2) {
|
|
52
|
-
next.push(TreeUtils.hashNode(level
|
|
54
|
+
next.push(TreeUtils.hashNode((0, treeMathInternal_js_1.requireTreeItem)(level, i), (0, treeMathInternal_js_1.requireTreeItem)(level, i + 1)));
|
|
53
55
|
}
|
|
54
56
|
layers.push(next);
|
|
55
57
|
level = next;
|
|
@@ -61,14 +63,15 @@ function assertProvableLeaves(leaves) {
|
|
|
61
63
|
throw new errors_js_1.InvalidTreeError(`Tree leaf count "${leaves.length}" is not a power of two.`);
|
|
62
64
|
}
|
|
63
65
|
const height = Math.log2(leaves.length);
|
|
64
|
-
if (height > constants_js_1.MAX_TREE_HEIGHT)
|
|
66
|
+
if (height > constants_js_1.MAX_TREE_HEIGHT) {
|
|
65
67
|
throw new errors_js_1.InvalidTreeHeightError(height);
|
|
68
|
+
}
|
|
66
69
|
return height;
|
|
67
70
|
}
|
|
68
71
|
function computeRootFromLeaves(leaves) {
|
|
69
72
|
const height = assertProvableLeaves(leaves);
|
|
70
73
|
const layers = buildLayers(leaves);
|
|
71
|
-
return { root: layers
|
|
74
|
+
return { root: (0, treeMathInternal_js_1.requireTreeItem)((0, treeMathInternal_js_1.requireTreeItem)(layers, height), 0), height };
|
|
72
75
|
}
|
|
73
76
|
/**
|
|
74
77
|
* Object-compatible tree hashing, root, proof, and verification helpers.
|
|
@@ -226,17 +229,17 @@ var TreeUtils;
|
|
|
226
229
|
}
|
|
227
230
|
}
|
|
228
231
|
else if (params.ratification.type === "ecrecover") {
|
|
229
|
-
if (params.ratification.signature
|
|
232
|
+
if (params.ratification.signature == null) {
|
|
230
233
|
items = await EcrecoverRatifier_js_1.EcrecoverRatifierUtils.ratify({
|
|
231
234
|
tree,
|
|
232
|
-
|
|
235
|
+
client: params.ratification.client,
|
|
233
236
|
account: params.ratification.account,
|
|
234
237
|
});
|
|
235
238
|
}
|
|
236
239
|
else {
|
|
237
240
|
items = await EcrecoverRatifier_js_1.EcrecoverRatifierUtils.ratify({
|
|
238
241
|
tree,
|
|
239
|
-
|
|
242
|
+
signature: params.ratification.signature,
|
|
240
243
|
account: params.ratification.account,
|
|
241
244
|
});
|
|
242
245
|
}
|
|
@@ -482,7 +485,7 @@ var TreeUtils;
|
|
|
482
485
|
const layers = buildLayers(params.tree.leaves);
|
|
483
486
|
const proof = layers
|
|
484
487
|
.slice(0, -1)
|
|
485
|
-
.map((level, layerIndex) => level
|
|
488
|
+
.map((level, layerIndex) => (0, treeMathInternal_js_1.requireTreeItem)(level, (index >> layerIndex) ^ 1));
|
|
486
489
|
return (0, morpho_ts_1.deepFreeze)({ root: params.tree.root, leafIndex, proof });
|
|
487
490
|
}
|
|
488
491
|
TreeUtils.buildProof = buildProof;
|
|
@@ -550,7 +553,7 @@ var TreeUtils;
|
|
|
550
553
|
return (0, morpho_ts_1.deepFreeze)(Array.from({ length: count }, (_, index) => ({
|
|
551
554
|
root: params.tree.root,
|
|
552
555
|
leafIndex: BigInt(index),
|
|
553
|
-
proof: siblingLayers.map((level, layerIndex) => level
|
|
556
|
+
proof: siblingLayers.map((level, layerIndex) => (0, treeMathInternal_js_1.requireTreeItem)(level, (index >> layerIndex) ^ 1)),
|
|
554
557
|
})));
|
|
555
558
|
}
|
|
556
559
|
TreeUtils.buildProofs = buildProofs;
|
|
@@ -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) {
|
package/lib/esm/errors.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { InvalidPositionAccrualStateError as SharedInvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError as SharedInvalidPositionAccrualTimestampError, InvalidPositionLossFactorError as SharedInvalidPositionLossFactorError } from "@morpho-org/morpho-ts";
|
|
1
2
|
import type { Address } from "viem";
|
|
2
3
|
import type { MempoolPayloadValidationIssue } from "./api/types.js";
|
|
3
4
|
/**
|
|
@@ -70,42 +71,27 @@ export declare class SettlementFeeExceedsPriceError extends Error {
|
|
|
70
71
|
/**
|
|
71
72
|
* Thrown when a local position accrual is requested for an impossible timestamp.
|
|
72
73
|
*
|
|
73
|
-
* @
|
|
74
|
-
* ```ts
|
|
75
|
-
* import { InvalidPositionAccrualTimestampError } from "@morpho-org/midnight-sdk";
|
|
76
|
-
*
|
|
77
|
-
* throw new InvalidPositionAccrualTimestampError(1n, 2n);
|
|
78
|
-
* ```
|
|
74
|
+
* @deprecated Import `InvalidPositionAccrualTimestampError` from `@morpho-org/morpho-ts`. Removed in the next major.
|
|
79
75
|
*/
|
|
80
|
-
export declare
|
|
81
|
-
|
|
82
|
-
|
|
76
|
+
export declare const InvalidPositionAccrualTimestampError: typeof SharedInvalidPositionAccrualTimestampError;
|
|
77
|
+
/** @deprecated Import `InvalidPositionAccrualTimestampError` from `@morpho-org/morpho-ts`. Removed in the next major. */
|
|
78
|
+
export type InvalidPositionAccrualTimestampError = SharedInvalidPositionAccrualTimestampError;
|
|
83
79
|
/**
|
|
84
80
|
* Thrown when a local position accrual sees a market loss factor older than the position.
|
|
85
81
|
*
|
|
86
|
-
* @
|
|
87
|
-
* ```ts
|
|
88
|
-
* import { InvalidPositionLossFactorError } from "@morpho-org/midnight-sdk";
|
|
89
|
-
*
|
|
90
|
-
* throw new InvalidPositionLossFactorError(1n, 2n);
|
|
91
|
-
* ```
|
|
82
|
+
* @deprecated Import `InvalidPositionLossFactorError` from `@morpho-org/morpho-ts`. Removed in the next major.
|
|
92
83
|
*/
|
|
93
|
-
export declare
|
|
94
|
-
|
|
95
|
-
|
|
84
|
+
export declare const InvalidPositionLossFactorError: typeof SharedInvalidPositionLossFactorError;
|
|
85
|
+
/** @deprecated Import `InvalidPositionLossFactorError` from `@morpho-org/morpho-ts`. Removed in the next major. */
|
|
86
|
+
export type InvalidPositionLossFactorError = SharedInvalidPositionLossFactorError;
|
|
96
87
|
/**
|
|
97
88
|
* Thrown when local position accrual inputs violate Midnight accounting invariants.
|
|
98
89
|
*
|
|
99
|
-
* @
|
|
100
|
-
* ```ts
|
|
101
|
-
* import { InvalidPositionAccrualStateError } from "@morpho-org/midnight-sdk";
|
|
102
|
-
*
|
|
103
|
-
* throw new InvalidPositionAccrualStateError("Pending fee exceeds credit.");
|
|
104
|
-
* ```
|
|
90
|
+
* @deprecated Import `InvalidPositionAccrualStateError` from `@morpho-org/morpho-ts`. Removed in the next major.
|
|
105
91
|
*/
|
|
106
|
-
export declare
|
|
107
|
-
|
|
108
|
-
|
|
92
|
+
export declare const InvalidPositionAccrualStateError: typeof SharedInvalidPositionAccrualStateError;
|
|
93
|
+
/** @deprecated Import `InvalidPositionAccrualStateError` from `@morpho-org/morpho-ts`. Removed in the next major. */
|
|
94
|
+
export type InvalidPositionAccrualStateError = SharedInvalidPositionAccrualStateError;
|
|
109
95
|
/**
|
|
110
96
|
* Thrown when a market parameter cannot satisfy Midnight protocol rules.
|
|
111
97
|
*
|