@totalis/hip4-client 0.124.0 → 0.126.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/CHANGELOG.md +389 -0
- package/README.md +9 -5
- package/dist/api-keys.d.ts +21 -2
- package/dist/api-keys.js +12 -10
- package/dist/audience-contract.d.ts +1 -2
- package/dist/client.d.ts +1 -1
- package/dist/client.js +1 -1
- package/dist/flow-errors.d.ts +1 -1
- package/dist/flow-errors.js +1 -1
- package/dist/generated/account-read.d.ts +150 -126
- package/dist/generated/api-keys.d.ts +19 -10
- package/dist/generated/browse.d.ts +12 -12
- package/dist/generated/client.d.ts +5 -2
- package/dist/generated/errors.d.ts +15 -8
- package/dist/generated/errors.js +47 -35
- package/dist/generated/maker.d.ts +3 -4
- package/dist/generated/openapi.d.ts +833 -893
- package/dist/generated/realtime.d.ts +66 -93
- package/dist/generated/vault-abi.d.ts +57 -0
- package/dist/generated/vault-abi.js +77 -0
- package/dist/generated/version.d.ts +16 -16
- package/dist/generated/version.js +20 -18
- package/dist/maker.d.ts +134 -54
- package/dist/maker.js +257 -147
- package/dist/money.d.ts +8 -6
- package/dist/money.js +7 -7
- package/dist/partner.d.ts +2 -0
- package/dist/partner.js +2 -1
- package/dist/request.d.ts +11 -2
- package/dist/request.js +7 -2
- package/dist/totalis.d.ts +147 -232
- package/dist/totalis.js +290 -269
- package/dist/typed-data.d.ts +6 -0
- package/dist/typed-data.js +8 -0
- package/dist/ui.d.ts +6 -10
- package/dist/ui.js +15 -13
- package/dist/vault-reads.d.ts +46 -0
- package/dist/vault-reads.js +72 -0
- package/examples/browser-wallet.mjs +1 -1
- package/examples/node-bot.mjs +15 -12
- package/package.json +1 -1
package/dist/maker.js
CHANGED
|
@@ -1,36 +1,26 @@
|
|
|
1
1
|
import { audienceClient, headerRecord } from "./base.js";
|
|
2
|
-
import { ApiError,
|
|
2
|
+
import { ApiError, resendable, sendOnce, singleFetch, sleep, unwrap, uuidv7 } from "./request.js";
|
|
3
3
|
import { toTotalisSigner } from "./signer.js";
|
|
4
4
|
import { items } from "./pagination.js";
|
|
5
5
|
import { TotalisStream } from "./stream.js";
|
|
6
6
|
import { follow, terminalOperationStatuses } from "./totalis.js";
|
|
7
7
|
import { address, hashTypedData, quoteTypedData, sellBackTypedData } from "./typed-data.js";
|
|
8
8
|
import { calldata, controllerTransactions } from "./controller.js";
|
|
9
|
+
import { readCashoutPosition as readPosition } from "./vault-reads.js";
|
|
9
10
|
export { controllerTransactions, encodeCall, openMakerVaultTransaction } from "./controller.js";
|
|
11
|
+
export { legsHash } from "./typed-data.js";
|
|
12
|
+
export { legStateOfCall, legStateReadGas, readCashoutPosition, readLegState, readTicket, ticketsCall, } from "./vault-reads.js";
|
|
10
13
|
export function createMakerClient(environment, options) {
|
|
11
14
|
return audienceClient(environment, options);
|
|
12
15
|
}
|
|
13
|
-
/**
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
* refuses with 409 `STATE_CONFLICT`. Nothing was published: answer the
|
|
17
|
-
* acceptance (`confirm`, or `onAcceptance`) first, or let its deadline pass.
|
|
18
|
-
*/
|
|
19
|
-
export class AcceptancePendingError extends Error {
|
|
20
|
-
rfqId;
|
|
21
|
-
quoteId;
|
|
22
|
-
deadline;
|
|
23
|
-
name = "AcceptancePendingError";
|
|
24
|
-
code = "ACCEPTANCE_PENDING";
|
|
25
|
-
constructor(rfqId, quoteId, deadline) {
|
|
26
|
-
super(`an acceptance of quote ${quoteId} on RFQ ${rfqId} awaits this maker's answer until ${deadline}`);
|
|
27
|
-
this.rfqId = rfqId;
|
|
28
|
-
this.quoteId = quoteId;
|
|
29
|
-
this.deadline = deadline;
|
|
30
|
-
}
|
|
16
|
+
/** Acceptance terms that are not a live quote this maker published, as opposed to a failure reading them. */
|
|
17
|
+
class UnpublishedTermsError extends Error {
|
|
18
|
+
name = "UnpublishedTermsError";
|
|
31
19
|
}
|
|
32
20
|
// An opening event older than this arrived by replay, not live fanout.
|
|
33
21
|
const REPLAYED_AFTER_MS = 2_000;
|
|
22
|
+
// An accept's deadline is 2 seconds after it, so its QUOTE_ACCEPTED arrives well within this.
|
|
23
|
+
const ACCEPTED_ARRIVES_MS = 2_500;
|
|
34
24
|
/** An in-memory store that drops entries a minute after they expire. */
|
|
35
25
|
export function memoryPublished() {
|
|
36
26
|
const entries = new Map();
|
|
@@ -46,21 +36,33 @@ export function memoryPublished() {
|
|
|
46
36
|
expiry: (digest) => entries.get(digest),
|
|
47
37
|
};
|
|
48
38
|
}
|
|
49
|
-
|
|
50
|
-
const
|
|
39
|
+
/** How long a priced entry quote stays signable: it stands until its RFQ closes or this maker replaces or cancels it. */
|
|
40
|
+
const PRICED_LIFE_SECONDS = 3 * 60 * 60;
|
|
41
|
+
/** The venue gives entry terms at most this much life on its clock. */
|
|
42
|
+
const MAX_ENTRY_LIFE_MS = 30_000;
|
|
43
|
+
/** An entry quote's key in the published store: its terms but the expiry and salt the venue renews. */
|
|
44
|
+
const pricedKey = (rfqId, terms) => `entry:${rfqId}:${terms.payout}:${terms.stake}:${terms.taker.toLowerCase()}:${[...terms.legs].sort((a, b) => Number(a.outcome_id) - Number(b.outcome_id)).map((leg) => `${leg.outcome_id}${leg.side}`).join(",")}`;
|
|
45
|
+
/** The venue gives a cash-out bid at most this much life on its clock, and its RFQ closes sooner. */
|
|
46
|
+
const MAX_BID_LIFE_MS = 60_000;
|
|
47
|
+
/**
|
|
48
|
+
* A cash-out bid's key in the published store: its price, position and owner,
|
|
49
|
+
* and the leg state it was priced at when the maker pinned one. The venue fills
|
|
50
|
+
* in the expiry and salt.
|
|
51
|
+
*/
|
|
52
|
+
const bidKey = (rfqId, terms) => `cashout:${rfqId}:${terms.price}:${terms.position_id.toLowerCase()}:${terms.owner.toLowerCase()}${terms.leg_state === undefined ? "" : `:${terms.leg_state.toLowerCase()}`}`;
|
|
51
53
|
/**
|
|
52
54
|
* The maker SDK over the public maker surface (the one Totalis MM uses):
|
|
53
|
-
* publish
|
|
54
|
-
*
|
|
55
|
+
* publish a price on entry and cash-out RFQs, and the SDK confirms the exact
|
|
56
|
+
* terms a taker accepts when QUOTE_ACCEPTED arrives.
|
|
55
57
|
*/
|
|
56
58
|
export function createMaker(options) {
|
|
57
|
-
const { environment, apiKey, makerId, signer: signerInput, stream: streamOptions, streamBaseUrl, ...clientOptions } = options;
|
|
59
|
+
const { environment, apiKey, makerId, chain, signer: signerInput, stream: streamOptions, streamBaseUrl, lastLook, autoConfirm = true, onConfirmError, ...clientOptions } = options;
|
|
58
60
|
const client = createMakerClient(environment, { ...clientOptions, accessToken: apiKey });
|
|
59
61
|
const recoveryFetch = singleFetch(clientOptions.fetch);
|
|
60
62
|
const signer = toTotalisSigner(signerInput);
|
|
61
63
|
const stream = new TotalisStream({
|
|
62
64
|
environment, accessToken: apiKey, headers: headerRecord(clientOptions.headers), ...streamOptions,
|
|
63
|
-
subscription: { ...streamOptions?.subscription,
|
|
65
|
+
subscription: { ...streamOptions?.subscription, kind: "maker", maker_id: makerId },
|
|
64
66
|
...(clientOptions.baseUrl === undefined ? {} : { baseUrl: clientOptions.baseUrl }),
|
|
65
67
|
...(streamBaseUrl === undefined ? {} : { streamBaseUrl }),
|
|
66
68
|
});
|
|
@@ -80,10 +82,27 @@ export function createMaker(options) {
|
|
|
80
82
|
}
|
|
81
83
|
return undefined;
|
|
82
84
|
};
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
85
|
+
// Waiters on the pending acceptances, checked whenever one arrives or is answered.
|
|
86
|
+
const watchers = new Set();
|
|
87
|
+
const changed = () => watchers.forEach((check) => check());
|
|
88
|
+
/** Whether `ready` holds within `ms`, checked as acceptances arrive and are answered. */
|
|
89
|
+
const within = (ready, ms) => new Promise((resolve) => {
|
|
90
|
+
if (ready())
|
|
91
|
+
return resolve(true);
|
|
92
|
+
const finish = (result) => {
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
watchers.delete(check);
|
|
95
|
+
resolve(result);
|
|
96
|
+
};
|
|
97
|
+
const check = () => void (ready() && finish(true));
|
|
98
|
+
const timer = setTimeout(() => finish(ready()), Math.max(ms, 0));
|
|
99
|
+
watchers.add(check);
|
|
100
|
+
});
|
|
101
|
+
/** Wait until no acceptance of this maker's quote on the RFQ awaits an answer: it is answered, or its deadline passes. */
|
|
102
|
+
const answeredOn = async (rfqId) => {
|
|
103
|
+
for (let acceptance = awaiting(rfqId); acceptance !== undefined; acceptance = awaiting(rfqId)) {
|
|
104
|
+
await within(() => awaiting(rfqId) === undefined, Date.parse(acceptance.deadline) - stream.serverNow() + 50);
|
|
105
|
+
}
|
|
87
106
|
};
|
|
88
107
|
// Resolves once the acceptances a truncated snapshot left out have been paged
|
|
89
108
|
// in, and rejects while that read has failed: until then they are not known.
|
|
@@ -96,7 +115,7 @@ export function createMaker(options) {
|
|
|
96
115
|
paging.catch((error) => {
|
|
97
116
|
if (acceptancesPaged === paging)
|
|
98
117
|
pagingFailed = true;
|
|
99
|
-
|
|
118
|
+
answerers().forEach(({ failed }) => failed(error));
|
|
100
119
|
});
|
|
101
120
|
return paging;
|
|
102
121
|
};
|
|
@@ -120,78 +139,134 @@ export function createMaker(options) {
|
|
|
120
139
|
answeredUntil.set(acceptance.quote_id, Date.parse(acceptance.deadline));
|
|
121
140
|
if (pending.delete(acceptance.quote_id))
|
|
122
141
|
released.forEach((release) => release(acceptance.rfq_id, filled));
|
|
142
|
+
changed();
|
|
123
143
|
};
|
|
144
|
+
// Each RFQ's live priced key, and the RFQ of each quote ID the venue
|
|
145
|
+
// returned, so a replacement or cancel makes the old price unsignable.
|
|
146
|
+
const pricedOn = new Map();
|
|
147
|
+
const rfqOfQuote = new Map();
|
|
148
|
+
async function forgetPriced(rfqId) {
|
|
149
|
+
const key = pricedOn.get(rfqId);
|
|
150
|
+
pricedOn.delete(rfqId);
|
|
151
|
+
if (key !== undefined)
|
|
152
|
+
await published.forget(key);
|
|
153
|
+
}
|
|
154
|
+
// Publications on one RFQ run one at a time: a same-price publication shares
|
|
155
|
+
// its key with one in flight, and a refusal must restore only what it found.
|
|
156
|
+
const publishing = new Map();
|
|
124
157
|
/**
|
|
125
|
-
*
|
|
126
|
-
*
|
|
158
|
+
* Publish a price under its key, replacing this maker's price on the RFQ.
|
|
159
|
+
* Replacing a quote while a taker's acceptance of it awaits an answer would
|
|
160
|
+
* withdraw that acceptance, so the venue refuses it: the publication waits
|
|
161
|
+
* until the acceptance is answered or its deadline passes. The key is
|
|
162
|
+
* recorded as signable before publishing (a lost response may still have
|
|
163
|
+
* published it) and restored when the venue definitely rejects it.
|
|
127
164
|
*/
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
165
|
+
function publishPriced(rfqId, key, lifeSeconds, post) {
|
|
166
|
+
const run = (publishing.get(rfqId) ?? Promise.resolve()).catch(() => undefined).then(async () => {
|
|
167
|
+
await answeredOn(rfqId);
|
|
168
|
+
const before = await published.expiry(key);
|
|
169
|
+
await published.record(key, Math.max(Math.floor(Date.now() / 1000) + lifeSeconds, before ?? 0));
|
|
170
|
+
let created;
|
|
171
|
+
try {
|
|
172
|
+
for (;;) {
|
|
173
|
+
try {
|
|
174
|
+
created = await post();
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
// The venue may hold an acceptance the stream has not delivered yet: once it arrives and is answered, publish again.
|
|
179
|
+
if (!(error instanceof ApiError && error.status === 409 && error.code === "STATE_CONFLICT"))
|
|
180
|
+
throw error;
|
|
181
|
+
if (!(await within(() => awaiting(rfqId) !== undefined, ACCEPTED_ARRIVES_MS)))
|
|
182
|
+
throw error;
|
|
183
|
+
await answeredOn(rfqId);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
if (!resendable(error))
|
|
189
|
+
await (before === undefined ? published.forget(key) : published.record(key, before));
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
192
|
+
const previous = pricedOn.get(rfqId);
|
|
193
|
+
if (previous !== undefined && previous !== key)
|
|
194
|
+
await published.forget(previous);
|
|
195
|
+
pricedOn.set(rfqId, key);
|
|
196
|
+
rfqOfQuote.set(created.quote_id, rfqId);
|
|
197
|
+
return created;
|
|
198
|
+
});
|
|
199
|
+
publishing.set(rfqId, run);
|
|
200
|
+
void run.catch(() => undefined).then(() => {
|
|
201
|
+
if (publishing.get(rfqId) === run)
|
|
202
|
+
publishing.delete(rfqId);
|
|
203
|
+
});
|
|
204
|
+
return run;
|
|
140
205
|
}
|
|
141
206
|
const published = options.published ?? memoryPublished();
|
|
142
207
|
const deployment = () => (deploymentRead ??= client.GET("/v1/deployment").then(unwrap).catch((error) => {
|
|
143
208
|
deploymentRead = undefined;
|
|
144
209
|
throw error;
|
|
145
210
|
}));
|
|
146
|
-
// Fees can change by governance and accepts require the current ones, so
|
|
147
|
-
// every quote reads them; only the deployment identity is cached.
|
|
148
|
-
async function vaultFees() {
|
|
149
|
-
const { fee_bps, taker_fee_bps } = unwrap(await client.GET("/v1/deployment"));
|
|
150
|
-
if (fee_bps === null || taker_fee_bps === null)
|
|
151
|
-
throw new Error("the venue has not published the vault's fees yet");
|
|
152
|
-
return { fee_bps, taker_fee_bps };
|
|
153
|
-
}
|
|
154
211
|
/**
|
|
155
|
-
* Publish
|
|
156
|
-
* previous quote there.
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
*
|
|
212
|
+
* Publish this maker's price on an entry RFQ; it replaces this maker's
|
|
213
|
+
* previous quote there. The venue fills in every other term (the RFQ's legs,
|
|
214
|
+
* stake and taker, the vault's current fees, an expiry and salt) and keeps
|
|
215
|
+
* the quote takeable, renewing its expiry and salt, until the RFQ closes or
|
|
216
|
+
* this maker replaces or cancels it. Each renewal gives the quote a new ID;
|
|
217
|
+
* any of them cancels it. Nothing is signed until a taker accepts it, and
|
|
218
|
+
* the SDK then signs only terms at a price this maker published. While a
|
|
219
|
+
* taker's acceptance of this maker's quote on the RFQ awaits its answer,
|
|
220
|
+
* the new price waits and is published once the acceptance is answered.
|
|
221
|
+
* It starts the maker stream if needed and waits until it is live, so the
|
|
222
|
+
* pending acceptances are known.
|
|
162
223
|
*/
|
|
163
224
|
async function quote(rfq, terms) {
|
|
164
225
|
await acceptancesKnown();
|
|
165
|
-
|
|
166
|
-
const
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
fee_bps: fees.fee_bps, taker_fee_bps: fees.taker_fee_bps, taker: rfq.taker.toLowerCase(),
|
|
170
|
-
expiry: expiryIn(terms.lifetimeSeconds ?? 20), salt: terms.salt ?? randomSalt(),
|
|
171
|
-
};
|
|
172
|
-
const quote_id = hashTypedData(quoteTypedData(chain, entry));
|
|
173
|
-
await publish(rfq.rfq_id, quote_id, Number(entry.expiry), async () => unwrap(await client.POST("/v1/rfqs/{rfq_id}/quotes", {
|
|
174
|
-
params: { path: { rfq_id: rfq.rfq_id }, header: { "Idempotency-Key": uuidv7() } }, body: { quote_id, entry },
|
|
226
|
+
const payout = String(terms.payout);
|
|
227
|
+
const key = pricedKey(rfq.rfq_id, { payout, stake: rfq.stake, taker: rfq.taker, legs: rfq.legs });
|
|
228
|
+
const created = await publishPriced(rfq.rfq_id, key, PRICED_LIFE_SECONDS, async () => unwrap(await client.POST("/v1/rfqs/{rfq_id}/quotes", {
|
|
229
|
+
params: { path: { rfq_id: rfq.rfq_id }, header: { "Idempotency-Key": uuidv7() } }, body: { payout },
|
|
175
230
|
})));
|
|
176
|
-
return { quoteId: quote_id
|
|
231
|
+
return { quoteId: created.quote_id };
|
|
177
232
|
}
|
|
178
233
|
/**
|
|
179
|
-
* Publish
|
|
180
|
-
* quotes
|
|
181
|
-
* and may bid; the maker vault
|
|
182
|
-
*
|
|
183
|
-
*
|
|
234
|
+
* Publish this maker's price on a cash-out RFQ, on the same route as entry
|
|
235
|
+
* quotes; it replaces this maker's previous bid there. Only the maker that
|
|
236
|
+
* backs the position receives its cash-out RFQ and may bid; the maker vault
|
|
237
|
+
* pays the owner `price` and the position closes. The venue fills in every
|
|
238
|
+
* other sell-back term (the RFQ's position, owner and leg_state, an expiry
|
|
239
|
+
* and salt), and the bid stays takeable until the RFQ closes or this maker
|
|
240
|
+
* replaces or cancels it. The owner signs the terms to accept, and the
|
|
241
|
+
* SDK then signs only terms at a price this maker bid. Pass `legState`
|
|
242
|
+
* from `readCashoutPosition(rfq)`, the leg state you priced from, to sign
|
|
243
|
+
* only a sell-back at that leg state; without it the SDK signs at the leg
|
|
244
|
+
* state the venue records. A new price waits for a pending acceptance like
|
|
245
|
+
* `quote`.
|
|
184
246
|
*/
|
|
185
247
|
async function bid(rfq, terms) {
|
|
186
248
|
await acceptancesKnown();
|
|
187
|
-
|
|
188
|
-
const
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
await publish(rfq.rfq_id, command.quote_id, Number(sell_back.expiry), async () => unwrap(await client.POST("/v1/rfqs/{rfq_id}/quotes", {
|
|
192
|
-
params: { path: { rfq_id: rfq.rfq_id }, header: { "Idempotency-Key": uuidv7() } }, body: command,
|
|
249
|
+
const price = String(terms.price);
|
|
250
|
+
const key = bidKey(rfq.rfq_id, { price, position_id: rfq.position_id, owner: rfq.taker, leg_state: terms.legState });
|
|
251
|
+
const created = await publishPriced(rfq.rfq_id, key, MAX_BID_LIFE_MS / 1000, async () => unwrap(await client.POST("/v1/rfqs/{rfq_id}/quotes", {
|
|
252
|
+
params: { path: { rfq_id: rfq.rfq_id }, header: { "Idempotency-Key": uuidv7() } }, body: { price },
|
|
193
253
|
})));
|
|
194
|
-
return { quoteId:
|
|
254
|
+
return { quoteId: created.quote_id };
|
|
255
|
+
}
|
|
256
|
+
/** Every market `GET /v1/markets` lists under `filters`, as `createTotalis`'s `listMarkets` reads them. */
|
|
257
|
+
function listMarkets(filters = {}, limit = 200) {
|
|
258
|
+
return items((query) => client.GET("/v1/markets", { params: { query: { ...filters, ...query, limit } } }).then(unwrap), (page) => page.items);
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Read a cash-out RFQ's position on chain (the `chain` option): its ticket,
|
|
262
|
+
* legs hash and leg state, after checking the RFQ's `legs` against the
|
|
263
|
+
* ticket's `legsHash`. Price from it, then
|
|
264
|
+
* `bid(rfq, { price, legState: position.legState })`.
|
|
265
|
+
*/
|
|
266
|
+
async function readCashoutPosition(rfq) {
|
|
267
|
+
if (chain === undefined)
|
|
268
|
+
throw new TypeError("pass chain to createMaker to read positions on chain");
|
|
269
|
+
return readPosition(chain, await deployment(), rfq);
|
|
195
270
|
}
|
|
196
271
|
/**
|
|
197
272
|
* Cancel a published quote. `ACCEPTED` means this maker already confirmed it:
|
|
@@ -210,6 +285,11 @@ export function createMaker(options) {
|
|
|
210
285
|
// Cancelled or replaced can no longer be accepted, so it must no longer be signable.
|
|
211
286
|
if (result.status !== "ACCEPTED") {
|
|
212
287
|
await published.forget(quoteId);
|
|
288
|
+
// A cancelled quote takes its price with it; a replaced one's price is the replacement's.
|
|
289
|
+
const rfqId = rfqOfQuote.get(quoteId);
|
|
290
|
+
rfqOfQuote.delete(quoteId);
|
|
291
|
+
if (rfqId !== undefined && result.status === "CANCELLED")
|
|
292
|
+
await forgetPriced(rfqId);
|
|
213
293
|
const acceptance = pending.get(quoteId);
|
|
214
294
|
if (acceptance !== undefined)
|
|
215
295
|
answered(acceptance);
|
|
@@ -217,59 +297,65 @@ export function createMaker(options) {
|
|
|
217
297
|
return result;
|
|
218
298
|
}
|
|
219
299
|
/**
|
|
220
|
-
*
|
|
221
|
-
*
|
|
222
|
-
*
|
|
223
|
-
*
|
|
224
|
-
* QUOTE_REMOVED with status CANCELLED. Without a lease nothing changes.
|
|
225
|
-
*/
|
|
226
|
-
async function renewQuoteLease(leaseMs) {
|
|
227
|
-
return unwrap(await client.PUT("/v1/makers/{maker_id}/quote-lease", { params: { path: { maker_id: makerId } }, body: { lease_ms: leaseMs } }));
|
|
228
|
-
}
|
|
229
|
-
/** Disarm the quote lease: open quotes then stand until their own expiry. `released` is false if none was armed. */
|
|
230
|
-
async function releaseQuoteLease() {
|
|
231
|
-
return unwrap(await client.DELETE("/v1/makers/{maker_id}/quote-lease", { params: { path: { maker_id: makerId } } }));
|
|
232
|
-
}
|
|
233
|
-
let stopLease;
|
|
234
|
-
/**
|
|
235
|
-
* Renew the quote lease now and every third of `leaseMs` until the returned
|
|
236
|
-
* stop, `close()` or another `keepQuoteLease` call. If this process dies or
|
|
237
|
-
* loses the venue, the lease lapses and its quotes are withdrawn. Stopping
|
|
238
|
-
* leaves the lease to lapse; `releaseQuoteLease()` keeps quotes standing
|
|
239
|
-
* without one. `onError` gets each failed renewal; renewals continue.
|
|
300
|
+
* Cancel all of this maker's open quotes, as `cancelQuote` would one at a
|
|
301
|
+
* time; takers see QUOTE_REMOVED with status CANCELLED. A quote whose
|
|
302
|
+
* acceptance awaits this maker's answer stays, counted in `pending`: answer
|
|
303
|
+
* it or let it time out. Publish again to come back.
|
|
240
304
|
*/
|
|
241
|
-
function
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
const stop = () => {
|
|
250
|
-
stopped = true;
|
|
251
|
-
clearTimeout(timer);
|
|
252
|
-
if (stopLease === stop)
|
|
253
|
-
stopLease = undefined;
|
|
254
|
-
};
|
|
255
|
-
stopLease = stop;
|
|
256
|
-
renew();
|
|
257
|
-
return stop;
|
|
305
|
+
async function cancelAllQuotes() {
|
|
306
|
+
const result = unwrap(await client.DELETE("/v1/makers/{maker_id}/quotes", { params: { path: { maker_id: makerId } } }));
|
|
307
|
+
// A quote under acceptance stays up to be answered, and its acceptance may not
|
|
308
|
+
// have arrived yet: forget the prices only when the venue kept none.
|
|
309
|
+
if (result.pending === 0)
|
|
310
|
+
for (const rfqId of [...pricedOn.keys()])
|
|
311
|
+
await forgetPriced(rfqId);
|
|
312
|
+
return result;
|
|
258
313
|
}
|
|
259
314
|
/** The exact terms an acceptance asks this maker to sign, checked against the quote ID. */
|
|
260
315
|
async function termsFor(acceptance) {
|
|
261
316
|
const chain = await deployment();
|
|
262
|
-
|
|
317
|
+
let typedData;
|
|
318
|
+
try {
|
|
319
|
+
typedData = acceptance.kind === "ENTRY" ? quoteTypedData(chain, acceptance.entry) : sellBackTypedData(chain, acceptance.sell_back);
|
|
320
|
+
}
|
|
321
|
+
catch (error) {
|
|
322
|
+
throw new UnpublishedTermsError("acceptance terms are malformed", { cause: error });
|
|
323
|
+
}
|
|
263
324
|
if (hashTypedData(typedData) !== acceptance.quote_id)
|
|
264
|
-
throw new
|
|
325
|
+
throw new UnpublishedTermsError("acceptance terms do not match their quote ID");
|
|
326
|
+
// The venue fills in the expiry and salt: the terms must be this maker's, at a price it set, and no longer-lived than the venue allows.
|
|
327
|
+
const venueTerms = acceptance.kind === "ENTRY"
|
|
328
|
+
? acceptance.entry.maker_id === makerId && Number(acceptance.entry.expiry) * 1000 <= stream.serverNow() + MAX_ENTRY_LIFE_MS + 1_000
|
|
329
|
+
: Number(acceptance.sell_back.expiry) * 1000 <= stream.serverNow() + MAX_BID_LIFE_MS + 1_000;
|
|
330
|
+
if (!venueTerms)
|
|
331
|
+
throw new UnpublishedTermsError("acceptance is not for a live quote this maker published");
|
|
265
332
|
// The quote signer signs only terms this maker published and that are still live.
|
|
266
|
-
|
|
333
|
+
// A bid pinned to a leg state signs only at that state; an unpinned one at the state the venue recorded.
|
|
334
|
+
const expiry = acceptance.kind === "ENTRY"
|
|
335
|
+
? await published.expiry(pricedKey(acceptance.rfq_id, acceptance.entry))
|
|
336
|
+
: await published.expiry(bidKey(acceptance.rfq_id, acceptance.sell_back))
|
|
337
|
+
?? await published.expiry(bidKey(acceptance.rfq_id, { ...acceptance.sell_back, leg_state: undefined }));
|
|
267
338
|
if (expiry === undefined || expiry * 1000 <= Date.now())
|
|
268
|
-
throw new
|
|
339
|
+
throw new UnpublishedTermsError("acceptance is not for a live quote this maker published");
|
|
269
340
|
return typedData;
|
|
270
341
|
}
|
|
271
|
-
//
|
|
342
|
+
// Acceptances being answered and answered, by whichever answerer took them first.
|
|
343
|
+
const busy = new Set();
|
|
344
|
+
const done = new Set();
|
|
345
|
+
// Each delivery goes to every onAcceptance handler, or to the SDK's own answerer while none is attached.
|
|
272
346
|
const handlers = new Set();
|
|
347
|
+
const reportAutomatic = onConfirmError ?? (() => undefined);
|
|
348
|
+
const confirming = answerer((acceptance) => (lastLook === undefined ? "CONFIRM" : lastLook(acceptance)), reportAutomatic);
|
|
349
|
+
const automatic = {
|
|
350
|
+
failed: confirming.failed,
|
|
351
|
+
// The maker stream carries every acceptance of the maker: one whose terms this instance did not publish is left to the process that did.
|
|
352
|
+
// A failure to read the deployment or the store is reported, never taken as unpublished.
|
|
353
|
+
dispatch: (acceptance) => void termsFor(acceptance).then(() => confirming.dispatch(acceptance), (error) => {
|
|
354
|
+
if (!(error instanceof UnpublishedTermsError))
|
|
355
|
+
reportAutomatic(error, acceptance);
|
|
356
|
+
}),
|
|
357
|
+
};
|
|
358
|
+
const answerers = () => (handlers.size > 0 ? handlers : autoConfirm ? [automatic] : []);
|
|
273
359
|
const deliver = (acceptance) => {
|
|
274
360
|
for (const [id, { deadline }] of pending)
|
|
275
361
|
if (Date.parse(deadline) <= stream.serverNow())
|
|
@@ -279,7 +365,8 @@ export function createMaker(options) {
|
|
|
279
365
|
answeredUntil.delete(id);
|
|
280
366
|
if (Date.parse(acceptance.deadline) > stream.serverNow() && !answeredUntil.has(acceptance.quote_id))
|
|
281
367
|
pending.set(acceptance.quote_id, acceptance);
|
|
282
|
-
|
|
368
|
+
changed();
|
|
369
|
+
answerers().forEach(({ dispatch }) => dispatch(acceptance));
|
|
283
370
|
};
|
|
284
371
|
const continueAcceptances = async () => {
|
|
285
372
|
const read = (query) => client.GET("/v1/makers/{maker_id}/acceptances", { params: { path: { maker_id: makerId }, query: { ...query, limit: 200 } } }).then(unwrap);
|
|
@@ -337,7 +424,9 @@ export function createMaker(options) {
|
|
|
337
424
|
return entry.built.then((send) => send());
|
|
338
425
|
}
|
|
339
426
|
/**
|
|
340
|
-
* Answer an acceptance before its deadline.
|
|
427
|
+
* Answer an acceptance before its deadline. The SDK already answers every
|
|
428
|
+
* acceptance it receives, unless an `onAcceptance` handler is attached:
|
|
429
|
+
* this is for an acceptance read another way. CONFIRM signs the exact accepted
|
|
341
430
|
* terms with the quote signer. The first answer for a quote is final:
|
|
342
431
|
* calling again, or `NetworkError.resend()`, resends the identical request,
|
|
343
432
|
* which the venue answers with the stored result.
|
|
@@ -346,35 +435,49 @@ export function createMaker(options) {
|
|
|
346
435
|
return answer(acceptance, () => decision);
|
|
347
436
|
}
|
|
348
437
|
/**
|
|
349
|
-
*
|
|
438
|
+
* Answer acceptances yourself, in place of the SDK's own answer (confirm
|
|
439
|
+
* what this maker published, after `lastLook`), until the returned function
|
|
440
|
+
* detaches the handler. A handler that returns CONFIRM for terms this maker
|
|
441
|
+
* did not publish gets an error, and nothing is sent. It handles every
|
|
442
|
+
* pending acceptance: from QUOTE_ACCEPTED, live or replayed by
|
|
350
443
|
* the stream after a reconnect with a cursor, and the snapshot's
|
|
351
444
|
* `acceptances` (paging GET /v1/makers/{maker_id}/acceptances when the
|
|
352
445
|
* snapshot truncated them), including acceptances the stream delivered
|
|
353
446
|
* before it was attached. The handler decides once per quote; if every send
|
|
354
447
|
* of the answer is lost, a redelivery before the deadline resends that same
|
|
355
448
|
* answer. `onError` receives the acceptance, or none when paging the
|
|
356
|
-
* truncated acceptances failed.
|
|
449
|
+
* truncated acceptances failed. A handler must not await `quote` or `bid`
|
|
450
|
+
* on the acceptance's RFQ: those wait for this answer.
|
|
357
451
|
*/
|
|
358
452
|
function onAcceptance(handler, onError = () => undefined) {
|
|
359
|
-
const
|
|
360
|
-
|
|
453
|
+
const entry = answerer(handler, onError);
|
|
454
|
+
handlers.add(entry);
|
|
455
|
+
stream.start();
|
|
456
|
+
[...pending.values()].forEach(entry.dispatch);
|
|
457
|
+
return () => {
|
|
458
|
+
if (!handlers.delete(entry) || handlers.size > 0)
|
|
459
|
+
return;
|
|
460
|
+
// The SDK answers again: what this handler left unanswered too.
|
|
461
|
+
answerers().forEach(({ dispatch }) => [...pending.values()].forEach(dispatch));
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
/** Each acceptance is answered once, by the first answerer it reaches; a lost or backed-off answer is resent unchanged by the next delivery. */
|
|
465
|
+
function answerer(decide, onError) {
|
|
361
466
|
const dispatch = (request) => {
|
|
362
467
|
const id = request.quote_id;
|
|
363
|
-
if (busy.has(id) ||
|
|
468
|
+
if (busy.has(id) || done.has(id) || Date.parse(request.deadline) <= stream.serverNow())
|
|
364
469
|
return;
|
|
365
470
|
busy.add(id);
|
|
366
|
-
|
|
471
|
+
if (done.size > 10_000)
|
|
472
|
+
done.delete(done.values().next().value);
|
|
473
|
+
void answer(request, () => decide(request)).then(() => done.add(id), (error) => {
|
|
367
474
|
// A lost or backed-off answer is resent unchanged by the next delivery.
|
|
368
475
|
if (!resendable(error))
|
|
369
|
-
|
|
476
|
+
done.add(id);
|
|
370
477
|
onError(error, request);
|
|
371
478
|
}).finally(() => busy.delete(id));
|
|
372
479
|
};
|
|
373
|
-
|
|
374
|
-
handlers.add(entry);
|
|
375
|
-
stream.start();
|
|
376
|
-
[...pending.values()].forEach(dispatch);
|
|
377
|
-
return () => void handlers.delete(entry);
|
|
480
|
+
return { dispatch, failed: (error) => onError(error) };
|
|
378
481
|
}
|
|
379
482
|
/**
|
|
380
483
|
* Every open RFQ once per subscription: from RFQ_CREATED, the snapshot's
|
|
@@ -500,8 +603,8 @@ export function createMaker(options) {
|
|
|
500
603
|
}
|
|
501
604
|
/** Vault transactions for this maker, for its controller wallet to sign and send. */
|
|
502
605
|
const controller = async () => {
|
|
503
|
-
const {
|
|
504
|
-
return controllerTransactions(await deployment(), makerId,
|
|
606
|
+
const { controller: wallet } = unwrap(await client.GET("/v1/makers/{maker_id}/capital", { params: { path: { maker_id: makerId } } }));
|
|
607
|
+
return controllerTransactions(await deployment(), makerId, wallet);
|
|
505
608
|
};
|
|
506
609
|
/**
|
|
507
610
|
* The pending vault withdrawal, if any, and what would block executing it
|
|
@@ -543,10 +646,17 @@ export function createMaker(options) {
|
|
|
543
646
|
return { job, idempotencyKey, submitted };
|
|
544
647
|
}
|
|
545
648
|
return {
|
|
546
|
-
client, stream, deployment, quote, bid,
|
|
649
|
+
client, stream, deployment, listMarkets, quote, bid, readCashoutPosition, cancelQuote, cancelAllQuotes, confirm, onAcceptance, onRfq, controller, withdrawal, reduceCollateral,
|
|
650
|
+
/**
|
|
651
|
+
* Stop quoting: cancel all open quotes and close the stream. Await it
|
|
652
|
+
* before exiting. It never rejects: it resolves to `cancelAllQuotes()`'s
|
|
653
|
+
* result, or undefined if that failed, and then a missed confirm
|
|
654
|
+
* withdraws what is left.
|
|
655
|
+
*/
|
|
547
656
|
close: () => {
|
|
548
|
-
|
|
657
|
+
const cancelled = cancelAllQuotes().catch(() => undefined);
|
|
549
658
|
stream.close();
|
|
659
|
+
return cancelled;
|
|
550
660
|
},
|
|
551
661
|
};
|
|
552
662
|
}
|
|
@@ -560,7 +670,7 @@ export async function makerReadiness(client, options = {}) {
|
|
|
560
670
|
const init = options.signal === undefined ? {} : { signal: options.signal };
|
|
561
671
|
let { ownership } = unwrap(await client.GET("/v1/me/maker", init));
|
|
562
672
|
// A self-service PENDING profile is activated by the same POST; an operator decision keeps it as it is.
|
|
563
|
-
if ((ownership.
|
|
673
|
+
if ((ownership.status === "SETUP_REQUIRED" || ownership.status === "PENDING") && options.admit !== false) {
|
|
564
674
|
try {
|
|
565
675
|
({ ownership } = unwrap(await client.POST("/v1/me/maker", init)));
|
|
566
676
|
}
|
|
@@ -569,18 +679,18 @@ export async function makerReadiness(client, options = {}) {
|
|
|
569
679
|
return { state: "NOT_INDEXED", ownership };
|
|
570
680
|
throw error;
|
|
571
681
|
}
|
|
572
|
-
if (ownership.
|
|
682
|
+
if (ownership.status === "SETUP_REQUIRED")
|
|
573
683
|
return { state: "NOT_INDEXED", ownership };
|
|
574
684
|
}
|
|
575
|
-
switch (ownership.
|
|
685
|
+
switch (ownership.status) {
|
|
576
686
|
case "READY":
|
|
577
687
|
case "PENDING":
|
|
578
688
|
case "RESTRICTED":
|
|
579
|
-
return { state: ownership.
|
|
689
|
+
return { state: ownership.status, makerId: ownership.maker.maker_id, ownership };
|
|
580
690
|
case "NOT_CREATED":
|
|
581
691
|
return { state: "NOT_INDEXED", ownership };
|
|
582
692
|
default:
|
|
583
|
-
return { state: ownership.
|
|
693
|
+
return { state: ownership.status, ownership };
|
|
584
694
|
}
|
|
585
695
|
}
|
|
586
696
|
/** `makerReadiness` again every `intervalMs` (default 3000) while `NOT_INDEXED`; resolves with the first other state. */
|
package/dist/money.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ type Balance = Schemas["Balance"];
|
|
|
4
4
|
type EntryTerms = Pick<Schemas["schemas-QuoteTerms"], "stake" | "payout" | "fee_bps" | "taker_fee_bps">;
|
|
5
5
|
type CashoutTerms = {
|
|
6
6
|
readonly kind: "SELL_BACK";
|
|
7
|
-
readonly
|
|
7
|
+
readonly price: string;
|
|
8
8
|
};
|
|
9
9
|
/**
|
|
10
10
|
* Spendable Totalis cash from `GET /v1/me/balances`, in USDC base units, as
|
|
@@ -18,7 +18,7 @@ type CashoutTerms = {
|
|
|
18
18
|
* stake fundings but not a pending wallet deposit, which moves into the
|
|
19
19
|
* vault, so it can exceed `vault + wallet` while a deposit is pending.
|
|
20
20
|
*/
|
|
21
|
-
export declare function spendableCash(balance: Pick<Balance, "amount" | "
|
|
21
|
+
export declare function spendableCash(balance: Pick<Balance, "amount" | "freshness" | "components" | "pending">): {
|
|
22
22
|
readonly vault: bigint | null;
|
|
23
23
|
readonly wallet: bigint | null;
|
|
24
24
|
readonly total: bigint | null;
|
|
@@ -59,13 +59,15 @@ export declare function netStake(terms: Pick<EntryTerms, "stake" | "taker_fee_bp
|
|
|
59
59
|
* 9.18 USDC at 100 bps profit fee nets 9.118140 USDC.
|
|
60
60
|
*/
|
|
61
61
|
export declare function netPayout(quote: {
|
|
62
|
-
readonly
|
|
62
|
+
readonly signing: {
|
|
63
|
+
readonly entry: EntryTerms;
|
|
64
|
+
};
|
|
63
65
|
} | EntryTerms): bigint;
|
|
64
66
|
/**
|
|
65
67
|
* What the owner receives from a sell-back: its price less the position's
|
|
66
|
-
* profit fee on the price above its net stake. `position` is the position
|
|
67
|
-
* (`GET /v1/me/positions/{position_id}`
|
|
68
|
-
* unknown.
|
|
68
|
+
* profit fee on the price above its net stake. `position` is the `position`
|
|
69
|
+
* of Get position's read (`GET /v1/me/positions/{position_id}` returns
|
|
70
|
+
* `{ context, position }`); `null` when its `net_stake` is unknown.
|
|
69
71
|
*/
|
|
70
72
|
export declare function netCashout(bid: CashoutTerms, position: {
|
|
71
73
|
readonly net_stake: string | null;
|