hypercall-rfq-example 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,5 @@
1
+ """Demo helpers for the Hypercall "Build an RFQ v2 maker" tutorial."""
2
+
3
+ from .client import Execution, Hypercall, HypercallError, Leg, Quote, Rfq, exact_prices, to_micros
4
+
5
+ __all__ = ["Execution", "Hypercall", "HypercallError", "Leg", "Quote", "Rfq", "exact_prices", "to_micros"]
@@ -0,0 +1,569 @@
1
+ """A small RFQ v2 maker client for the "Build an RFQ v2 maker" tutorial.
2
+
3
+ This is demo code: correct and readable rather than complete. Each method is
4
+ one REST call or one loop, so you can read it next to the API docs.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import base64
11
+ import json
12
+ import math
13
+ import time
14
+ import uuid
15
+ from dataclasses import dataclass, field
16
+ from decimal import ROUND_HALF_UP, Decimal
17
+ from email.utils import parsedate_to_datetime
18
+ from pathlib import Path
19
+ from typing import Any, AsyncIterator
20
+
21
+ import httpx
22
+ import websockets
23
+ from eth_account import Account
24
+
25
+ from . import signing
26
+
27
+ GRANT_LIFETIME_MS = 270_000 # the server refuses grants longer than 5 minutes
28
+ GRANT_RENEW_MS = 60_000 # re-sign this long before expiry
29
+ ACTION_TTL_MS = 30_000 # signature lifetime for decline/withdraw/schedule
30
+ POLL_S = 10.0 # change-feed backstop while the socket is quiet
31
+ MICROS = Decimal(1_000_000)
32
+
33
+
34
+ class HypercallError(Exception):
35
+ def __init__(self, status: int, code: str, message: str):
36
+ super().__init__(f"{status} {code}: {message}")
37
+ self.status, self.code, self.message = status, code, message
38
+
39
+
40
+ def uuid7() -> str:
41
+ """Operation and quote IDs must be UUIDv7 (time-ordered)."""
42
+ ms = int(time.time() * 1000)
43
+ rand = uuid.uuid4().int
44
+ value = (ms << 80) | (0x7 << 76) | ((rand >> 64) & 0x0FFF) << 64 | (0b10 << 62) | (rand & ((1 << 62) - 1))
45
+ return str(uuid.UUID(int=value))
46
+
47
+
48
+ def to_micros(usd: float | Decimal) -> int:
49
+ return int((Decimal(str(usd)) * MICROS).quantize(Decimal(1), ROUND_HALF_UP))
50
+
51
+
52
+ @dataclass
53
+ class Leg:
54
+ instrument: str
55
+ taker_side: str # "buy" or "sell"; the maker takes the other side
56
+ quantity_micros_per_unit: int
57
+
58
+ @property
59
+ def contracts_per_package(self) -> Decimal:
60
+ return Decimal(self.quantity_micros_per_unit) / MICROS
61
+
62
+
63
+ @dataclass
64
+ class Rfq:
65
+ """The maker view of one RFQ, as returned by GET /private/rfqs/{id}."""
66
+
67
+ id: str
68
+ sequence: int
69
+ status: str
70
+ terms_commitment: str
71
+ legs: list[Leg]
72
+ target: int # package units, in micros
73
+ remaining_target: int
74
+ fill_policy: dict
75
+ quote_deadline_ms: int
76
+ expires_at_ms: int
77
+ maker_generation: int | None
78
+ rfq_generation: int | None
79
+ raw: dict = field(repr=False)
80
+
81
+ @classmethod
82
+ def from_view(cls, view: dict, sequence: int) -> Rfq | None:
83
+ parent = view["parent"]
84
+ if parent["view"] != "maker":
85
+ return None # our own RFQ as taker; not ours to quote
86
+ terms, gen = parent["terms"], view.get("maker_quote_generation") or {}
87
+ return cls(
88
+ id=view["rfq_id"],
89
+ sequence=sequence,
90
+ status=view["status"],
91
+ terms_commitment=view["terms_commitment"],
92
+ legs=[Leg(l["instrument"], l["taker_side"], int(l["quantity_micros_per_unit"])) for l in terms["legs"]],
93
+ target=int(view["target"]),
94
+ remaining_target=int(view["remaining_target"]),
95
+ fill_policy=terms["fill_policy"],
96
+ quote_deadline_ms=terms["quote_deadline_ms"],
97
+ expires_at_ms=terms["expires_at_ms"],
98
+ maker_generation=gen.get("maker_generation"),
99
+ rfq_generation=gen.get("rfq_generation"),
100
+ raw=view,
101
+ )
102
+
103
+
104
+ @dataclass
105
+ class Quote:
106
+ id: str
107
+ rfq_id: str
108
+ capacity: int
109
+ legs: list[Leg]
110
+ prices_micros: list[int]
111
+ expires_at_ms: int
112
+ executable: bool
113
+ response: dict = field(repr=False)
114
+
115
+
116
+ @dataclass
117
+ class ExecutionLeg:
118
+ instrument: str
119
+ side: str # our side
120
+ contracts: Decimal
121
+ price_usd: Decimal
122
+
123
+
124
+ @dataclass
125
+ class Execution:
126
+ sequence: int
127
+ execution_id: str
128
+ rfq_id: str
129
+ quote_id: str
130
+ role: str
131
+ package_units: int
132
+ executed_at_ms: int
133
+ legs: list[ExecutionLeg]
134
+
135
+ @classmethod
136
+ def from_json(cls, e: dict) -> Execution:
137
+ return cls(
138
+ sequence=e["sequence"],
139
+ execution_id=e["execution_id"],
140
+ rfq_id=e["rfq_id"],
141
+ quote_id=e["quote_id"],
142
+ role=e["role"],
143
+ package_units=int(e["package_units"]),
144
+ executed_at_ms=e["executed_at_ms"],
145
+ legs=[
146
+ ExecutionLeg(
147
+ l["instrument"], l["side"], Decimal(l["quantity_micros"]) / MICROS, Decimal(l["price_micros"]) / MICROS
148
+ )
149
+ for l in e["legs"]
150
+ ],
151
+ )
152
+
153
+
154
+ class Cursor:
155
+ """A sequence number saved to a file, so restarts resume where they left off."""
156
+
157
+ def __init__(self, path: str | None):
158
+ self.path = Path(path) if path else None
159
+ self.value = int(self.path.read_text()) if self.path and self.path.exists() else 0
160
+
161
+ def save(self, value: int) -> None:
162
+ if value > self.value:
163
+ self.value = value
164
+ if self.path:
165
+ self.path.write_text(str(value))
166
+
167
+
168
+ class Acks:
169
+ """A cursor that only advances past RFQs the caller has acknowledged.
170
+
171
+ For handling RFQs concurrently: `value` is the highest sequence seen (so
172
+ nothing is yielded twice), but the saved cursor stops just below the
173
+ oldest RFQ still being handled. After a crash, every unacknowledged RFQ
174
+ is replayed; ones acknowledged after it may be replayed too.
175
+ """
176
+
177
+ def __init__(self, cursor: Cursor):
178
+ self.cursor = cursor
179
+ self.value = cursor.value
180
+ self._pending: set[int] = set()
181
+
182
+ def hold(self, sequence: int) -> None:
183
+ self.value = max(self.value, sequence)
184
+ self._pending.add(sequence)
185
+
186
+ def save(self, sequence: int) -> None:
187
+ """A sequence passed over without being handed to the caller."""
188
+ self.value = max(self.value, sequence)
189
+ self._flush()
190
+
191
+ def ack(self, sequence: int) -> None:
192
+ self._pending.discard(sequence)
193
+ self._flush()
194
+
195
+ def _flush(self) -> None:
196
+ self.cursor.save(min(self._pending) - 1 if self._pending else self.value)
197
+
198
+
199
+ class Hypercall:
200
+ def __init__(self, host: str, account: str, signer_key: str, chain_id: int = 999, http: httpx.AsyncClient | None = None):
201
+ self.host = host.rstrip("/")
202
+ self.account = account.lower()
203
+ self.key = signer_key
204
+ self.signer = Account.from_key(signer_key).address.lower()
205
+ self.chain_id = chain_id
206
+ self.http = http or httpx.AsyncClient(base_url=self.host, timeout=10)
207
+ self._clock_offset_ms: int | None = None
208
+ self._last_nonce = 0
209
+ self.rfq_v2 = RfqV2(self)
210
+ self.perps = Perps(self)
211
+
212
+ async def now_ms(self) -> int:
213
+ """Server time, from the Date header of /health (signatures use the server clock)."""
214
+ if self._clock_offset_ms is None:
215
+ r = await self.http.get("/health")
216
+ server = int(parsedate_to_datetime(r.headers["date"]).timestamp() * 1000)
217
+ self._clock_offset_ms = server - int(time.time() * 1000)
218
+ return int(time.time() * 1000) + self._clock_offset_ms
219
+
220
+ async def nonce(self) -> int:
221
+ """A millisecond timestamp, strictly increasing within this process."""
222
+ self._last_nonce = max(await self.now_ms(), self._last_nonce + 1)
223
+ return self._last_nonce
224
+
225
+ def sign(self, primary: str, message: dict, domain: str = "Hypercall") -> str:
226
+ return signing.sign(primary, message, self.key, self.chain_id, domain)
227
+
228
+ async def request(self, method: str, path: str, *, token: str | None = None, **kwargs) -> Any:
229
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
230
+ r = await self.http.request(method, path, headers=headers, **kwargs)
231
+ if r.status_code >= 400:
232
+ try:
233
+ body = r.json()
234
+ except ValueError:
235
+ body = {}
236
+ raise HypercallError(r.status_code, body.get("code", "http_error"), body.get("message", r.text))
237
+ return r.json()
238
+
239
+
240
+ class RfqV2:
241
+ def __init__(self, hc: Hypercall):
242
+ self.hc = hc
243
+ self._token: str | None = None
244
+ self._token_expires_ms = 0
245
+ self._acks: Acks | None = None
246
+
247
+ # ---- read grants -------------------------------------------------------
248
+
249
+ async def token(self) -> str:
250
+ """A signed AuthorizeRfqReadV2 bearer token, renewed a minute before it lapses."""
251
+ now = await self.hc.now_ms()
252
+ if self._token is None or now > self._token_expires_ms - GRANT_RENEW_MS:
253
+ expires = now + GRANT_LIFETIME_MS
254
+ nonce = await self.hc.nonce()
255
+ grant = {
256
+ "account": self.hc.account,
257
+ "issued_at_ms": now,
258
+ "expires_at_ms": expires,
259
+ "nonce": nonce,
260
+ "signature": self.hc.sign("AuthorizeRfqReadV2", signing.read_grant_message(self.hc.account, now, expires, nonce)),
261
+ }
262
+ raw = json.dumps(grant, separators=(",", ":")).encode()
263
+ self._token, self._token_expires_ms = base64.urlsafe_b64encode(raw).rstrip(b"=").decode(), expires
264
+ return self._token
265
+
266
+ # ---- reads ---------------------------------------------------------------
267
+
268
+ async def provider(self) -> dict:
269
+ """This account's quote-provider enrollment and status."""
270
+ return await self.hc.request("GET", "/private/rfq-provider", token=await self.token())
271
+
272
+ async def get(self, rfq_id: str, sequence: int = 0) -> Rfq | None:
273
+ view = await self.hc.request("GET", f"/private/rfqs/{rfq_id}", token=await self.token())
274
+ return Rfq.from_view(view, sequence)
275
+
276
+ async def changes(self, after: int) -> dict:
277
+ params = {"after_sequence": after, "limit": 100}
278
+ return await self.hc.request("GET", "/private/rfqs/changes", params=params, token=await self.token())
279
+
280
+ # ---- intake --------------------------------------------------------------
281
+
282
+ async def stream(self, cursor_file: str | None = None, manual_ack: bool = False) -> AsyncIterator[Rfq]:
283
+ """Yield each RFQ change routed to us, in sequence order, forever.
284
+
285
+ Subscribes to `rfq_v2` with `view: full`, so most RFQs arrive complete.
286
+ On every (re)connect, and whenever the socket is quiet, the change feed
287
+ replays anything missed since the saved cursor. By default the cursor
288
+ is saved when your loop body returns, so a crash never skips an RFQ.
289
+ If you hand each RFQ to a task instead of handling it in the loop
290
+ body, pass `manual_ack=True` and call `ack(rfq)` when the task is
291
+ done: the cursor then never moves past an RFQ still being handled.
292
+ """
293
+ cursor: Cursor | Acks = Cursor(cursor_file)
294
+ if manual_ack:
295
+ cursor = self._acks = Acks(cursor)
296
+
297
+ def handed(rfq: Rfq) -> None:
298
+ if manual_ack:
299
+ cursor.hold(rfq.sequence)
300
+
301
+ def done(rfq: Rfq) -> None:
302
+ if not manual_ack:
303
+ cursor.save(rfq.sequence)
304
+ ws_url = "ws" + self.hc.host.removeprefix("http") + "/ws"
305
+ while True:
306
+ try:
307
+ async with websockets.connect(ws_url, max_size=2**22) as ws:
308
+ await self._authenticate(ws)
309
+ await ws.send(json.dumps({"type": "Subscribe", "channel": "rfq_v2", "view": "full"}))
310
+ async for rfq in self._replay(cursor):
311
+ handed(rfq)
312
+ yield rfq
313
+ done(rfq)
314
+ while True:
315
+ if self._token_expires_ms - await self.hc.now_ms() < GRANT_RENEW_MS:
316
+ await self._authenticate(ws) # keeps the subscription
317
+ try:
318
+ frame = json.loads(await asyncio.wait_for(ws.recv(), POLL_S))
319
+ except asyncio.TimeoutError:
320
+ async for rfq in self._replay(cursor):
321
+ handed(rfq)
322
+ yield rfq
323
+ done(rfq)
324
+ continue
325
+ rfq = await self._from_frame(ws, frame, cursor)
326
+ if rfq is not None:
327
+ handed(rfq)
328
+ yield rfq
329
+ done(rfq)
330
+ except (OSError, websockets.ConnectionClosed) as error:
331
+ print(f"rfq_v2 socket dropped ({error}); reconnecting")
332
+ await asyncio.sleep(1)
333
+
334
+ def ack(self, rfq: Rfq) -> None:
335
+ """Mark an RFQ from `stream(manual_ack=True)` as handled."""
336
+ if self._acks is None:
337
+ raise RuntimeError("ack() needs stream(manual_ack=True)")
338
+ self._acks.ack(rfq.sequence)
339
+
340
+ async def _authenticate(self, ws) -> None:
341
+ await ws.send(json.dumps({"type": "AuthenticateRfqV2", "token": await self.token()}))
342
+
343
+ async def _from_frame(self, ws, frame: dict, cursor: Cursor | Acks) -> Rfq | None:
344
+ kind = frame.get("type")
345
+ if kind == "Error" and frame.get("code") == "rfq_v2_grant_expired":
346
+ self._token = None # the server says our grant lapsed: sign a new one
347
+ await self._authenticate(ws)
348
+ return None
349
+ if kind == "Error":
350
+ raise HypercallError(0, frame.get("code") or "ws_error", frame.get("message", ""))
351
+ if kind not in ("RfqV2Rfq", "RfqV2Changed") or frame["sequence"] <= cursor.value:
352
+ return None
353
+ if kind == "RfqV2Rfq":
354
+ return Rfq.from_view(frame["rfq"], frame["sequence"])
355
+ return await self.get(frame["rfq_id"], frame["sequence"]) # hint only: read it
356
+
357
+ async def _replay(self, cursor: Cursor | Acks) -> AsyncIterator[Rfq]:
358
+ after = cursor.value
359
+ while True:
360
+ page = await self.changes(after)
361
+ for change in page["changes"]:
362
+ rfq = await self.get(change["rfq_id"], change["sequence"])
363
+ if rfq is not None:
364
+ yield rfq
365
+ cursor.save(change["sequence"])
366
+ if page["next_after_sequence"] == after or not page["has_more"]:
367
+ cursor.save(page["next_after_sequence"])
368
+ return
369
+ after = page["next_after_sequence"]
370
+
371
+ # ---- quoting -------------------------------------------------------------
372
+
373
+ async def quote(self, rfq: Rfq, prices: list[float], capacity: int | None = None, expires_in_s: float = 20) -> Quote:
374
+ """Sign and post a firm quote. `prices` are USD per contract, one per leg."""
375
+ policy = rfq.fill_policy
376
+ if policy["mode"] == "full_size_once":
377
+ capacity, reference, step = rfq.target, rfq.target, None
378
+ else:
379
+ step = int(policy["step"])
380
+ capacity, reference = capacity or rfq.remaining_target, step
381
+ micros = exact_prices(rfq.legs, [to_micros(p) for p in prices], reference, step)
382
+ receives, premium = signing.reference_premium(
383
+ [l.__dict__ for l in rfq.legs], micros, reference, step
384
+ )
385
+ now = await self.hc.now_ms()
386
+ terms = {
387
+ "id": uuid7(),
388
+ "rfq_id": rfq.id,
389
+ "rfq_terms_commitment": rfq.terms_commitment,
390
+ "maker_account": self.hc.account,
391
+ # Copied from the read, never computed: a withdrawal bumps them.
392
+ "maker_generation": rfq.maker_generation,
393
+ "rfq_generation": rfq.rfq_generation,
394
+ "priced_legs": [{"instrument": l.instrument, "price_micros": str(p)} for l, p in zip(rfq.legs, micros)],
395
+ "reference_quantity": str(reference),
396
+ "maker_receives_reference_premium": receives,
397
+ "reference_premium_micros": str(premium),
398
+ "capacity": str(capacity),
399
+ "fill_policy": policy,
400
+ "withdrawal_policy": "permitted",
401
+ "fee_limits": {"per_execution": "0", "cumulative": "0"},
402
+ "expires_at_ms": min(rfq.expires_at_ms, now + int(expires_in_s * 1000)),
403
+ "protection_scope": None,
404
+ "source_indicative_quote_id": None,
405
+ }
406
+ nonce = await self.hc.nonce()
407
+ body = {"terms": terms, "nonce": nonce, "signature": self.hc.sign("AuthorizeRfqQuoteV2", signing.firm_quote_message(terms, nonce))}
408
+ r = await self.hc.request("POST", f"/private/rfqs/{rfq.id}/quotes/firm", json=body)
409
+ return Quote(terms["id"], rfq.id, capacity, rfq.legs, micros, terms["expires_at_ms"], r["executable"], r)
410
+
411
+ async def _action(self) -> dict:
412
+ now = await self.hc.now_ms()
413
+ return {"operation_id": uuid7(), "expires_at_ms": now + ACTION_TTL_MS, "nonce": await self.hc.nonce()}
414
+
415
+ async def decline(self, rfq: Rfq) -> dict:
416
+ body = {**await self._action(), "maker_account": self.hc.account}
417
+ body["signature"] = self.hc.sign("DeclineRfqV2", signing.decline_message(rfq.id, body))
418
+ return await self.hc.request("POST", f"/private/rfqs/{rfq.id}/declines", json=body)
419
+
420
+ async def withdraw(self, quote: Quote) -> dict:
421
+ body = await self._action()
422
+ body["signature"] = self.hc.sign("InvalidateRfqV2", signing.withdraw_quote_message(quote.rfq_id, quote.id, body))
423
+ return await self.hc.request("POST", f"/private/rfqs/{quote.rfq_id}/quotes/{quote.id}/withdrawals", json=body)
424
+
425
+ async def _bulk(self, scope: dict) -> dict:
426
+ body = {**await self._action(), "maker_account": self.hc.account, "scope": scope}
427
+ body["signature"] = self.hc.sign("BulkWithdrawRfqV2", signing.bulk_withdrawal_message(body))
428
+ return await self.hc.request("POST", "/private/rfq-quote-withdrawals", json=body)
429
+
430
+ async def withdraw_rfq(self, rfq_id: str) -> dict:
431
+ """Withdraw every quote we have on one RFQ (bumps that RFQ's generation)."""
432
+ return await self._bulk({"mode": "rfq", "rfq_id": rfq_id})
433
+
434
+ async def withdraw_all(self) -> dict:
435
+ """Withdraw every open quote (bumps our maker generation)."""
436
+ return await self._bulk({"mode": "all_open"})
437
+
438
+ async def cancel_after(self, seconds: float | None) -> dict:
439
+ """Dead-man switch: withdraw everything unless renewed within `seconds`. None disarms it."""
440
+ body = {**await self._action(), "maker_account": self.hc.account}
441
+ if seconds is not None:
442
+ body["cancel_at_ms"] = await self.hc.now_ms() + int(seconds * 1000)
443
+ body["signature"] = self.hc.sign("ScheduleRfqQuoteCancelV2", signing.cancel_schedule_message(body))
444
+ return await self.hc.request("POST", "/private/rfq-quote-cancel-schedule", json=body)
445
+
446
+ # ---- fills ---------------------------------------------------------------
447
+
448
+ async def executions(self, cursor_file: str | None = None, poll_s: float = 1.0) -> AsyncIterator[Execution]:
449
+ """Yield every execution against our quotes exactly once, in order.
450
+
451
+ Resumes from the saved cursor after a restart; the cursor is saved only
452
+ after your loop body returns. Deduplicate on `execution_id` if your
453
+ handler is not idempotent across a crash mid-body.
454
+ """
455
+ cursor = Cursor(cursor_file)
456
+ while True:
457
+ params = {"after_sequence": cursor.value, "limit": 100}
458
+ page = await self.hc.request("GET", "/private/rfqs/executions", params=params, token=await self.token())
459
+ for e in page["executions"]:
460
+ yield Execution.from_json(e)
461
+ cursor.save(e["sequence"])
462
+ if not page["has_more"]:
463
+ await asyncio.sleep(poll_s)
464
+
465
+
466
+ def price_granule(leg: Leg, reference: int, step: int | None) -> int:
467
+ """Smallest price step, in micros, that keeps this leg's premium whole.
468
+
469
+ A leg contributes price * quantity_micros_per_unit * units / 10^12 micros
470
+ of premium, so its price must be a multiple of
471
+ 10^12 / gcd(quantity_micros_per_unit * units, 10^12) for the reference
472
+ quantity and, for partial-fill policies, for one step. At 0.01 contracts
473
+ per package that is 100 micros; at whole contracts it is 1.
474
+ """
475
+ granule = 1
476
+ for units in (reference, step):
477
+ if units:
478
+ g = signing._SCALE // math.gcd(leg.quantity_micros_per_unit * units, signing._SCALE)
479
+ granule = granule * g // math.gcd(granule, g)
480
+ return granule
481
+
482
+
483
+ def exact_prices(
484
+ legs: list[Leg], micros: list[int], reference: int, step: int | None, max_move: float = 0.01
485
+ ) -> list[int]:
486
+ """Prices the signed premium can carry exactly, moved in the maker's favour.
487
+
488
+ The reference premium is sum(+/- price * contracts) and must be a whole
489
+ number of micros (and so must one step's, for partial fills). Unchanged
490
+ prices are kept when they are already exact. Otherwise every leg is
491
+ rounded to a multiple of its `price_granule`, up on a leg the taker buys
492
+ and down on a leg the taker sells, which makes each leg's premium, and so
493
+ the sum, exact. A sub-contract package can need a coarse step (100 micros
494
+ at 0.01 contracts); a price that would move by more than `max_move`
495
+ (relative) or reach zero is refused rather than quoted.
496
+ """
497
+ raw = [leg.__dict__ for leg in legs]
498
+ if all(m > 0 for m in micros) and signing.reference_premium(raw, micros, reference, step):
499
+ return list(micros)
500
+ fixed = []
501
+ for leg, price in zip(legs, micros, strict=True):
502
+ granule = price_granule(leg, reference, step)
503
+ if leg.taker_side == "buy":
504
+ rounded = -(-price // granule) * granule
505
+ else:
506
+ rounded = price // granule * granule
507
+ if rounded <= 0 or abs(rounded - price) > max_move * price:
508
+ raise ValueError(
509
+ f"{leg.instrument}: at this size the price must be a multiple of {granule} micros, "
510
+ f"which moves {price} too far; adjust the price or the size"
511
+ )
512
+ fixed.append(rounded)
513
+ if not signing.reference_premium(raw, fixed, reference, step):
514
+ raise ValueError("leg prices do not make the premium exact; adjust leg prices")
515
+ return fixed
516
+
517
+
518
+ class Perps:
519
+ """Hyperliquid perp orders placed through Hypercall from the same account."""
520
+
521
+ def __init__(self, hc: Hypercall, info_url: str | None = None):
522
+ self.hc = hc
523
+ self.info_url = info_url or (
524
+ "https://api.hyperliquid.xyz/info" if hc.chain_id == 999 else "https://api.hyperliquid-testnet.xyz/info"
525
+ )
526
+ self._meta: dict[str, tuple[int, int]] | None = None
527
+
528
+ async def _info(self, body: dict) -> Any:
529
+ async with httpx.AsyncClient(timeout=10) as http:
530
+ r = await http.post(self.info_url, json=body)
531
+ r.raise_for_status()
532
+ return r.json()
533
+
534
+ async def asset(self, coin: str) -> tuple[int, int]:
535
+ """(asset index, size decimals) from Hyperliquid's perp meta."""
536
+ if self._meta is None:
537
+ universe = (await self._info({"type": "meta"}))["universe"]
538
+ self._meta = {a["name"]: (i, a["szDecimals"]) for i, a in enumerate(universe)}
539
+ return self._meta[coin]
540
+
541
+ async def order(self, coin: str, is_buy: bool, size: float, type: str = "ioc", slippage_bps: float = 20, reduce_only: bool = False) -> dict:
542
+ """Marketable limit order at mid +/- slippage. Returns the directive submit response."""
543
+ asset, sz_decimals = await self.asset(coin)
544
+ mid = Decimal((await self._info({"type": "allMids"}))[coin])
545
+ px = mid * (1 + Decimal(slippage_bps) / 10_000 * (1 if is_buy else -1))
546
+ px = hl_price(px, sz_decimals)
547
+ sz = Decimal(str(size)).quantize(Decimal(1).scaleb(-sz_decimals))
548
+ if sz <= 0:
549
+ raise ValueError(f"{size} {coin} rounds to zero at {sz_decimals} size decimals")
550
+ nonce = await self.hc.nonce()
551
+ action = {
552
+ "asset": asset,
553
+ "isBuy": is_buy,
554
+ "limitPx": int(px * 10**8), # CoreWriter units: value * 1e8
555
+ "sz": int(sz * 10**8),
556
+ "reduceOnly": reduce_only,
557
+ "encodedTif": {"alo": 1, "gtc": 2, "ioc": 3}[type],
558
+ "cloid": nonce,
559
+ }
560
+ body = {"account": self.hc.account, "nonce": nonce, "action": action}
561
+ body["signature"] = self.hc.sign("HLOrder", signing.perp_order_message(body), domain="HypercallApiSign")
562
+ return await self.hc.request("POST", "/v1/actions/hl_limit_order", json=body)
563
+
564
+
565
+ def hl_price(px: Decimal, sz_decimals: int) -> Decimal:
566
+ """Hyperliquid perp prices: at most 5 significant figures and 6 - szDecimals decimals."""
567
+ digits = px.adjusted() + 1
568
+ px = px.quantize(Decimal(1).scaleb(min(digits - 5, 0)))
569
+ return px.quantize(Decimal(1).scaleb(-(6 - sz_decimals)))
@@ -0,0 +1,325 @@
1
+ """EIP-712 messages a maker signs for RFQ v2, plus the reference premium.
2
+
3
+ Every type below mirrors the Rust signer in
4
+ `public-crates/hypercall-client/src/rfq_v2_signing.rs` field for field: names,
5
+ order and widths are part of the type hash. The parity test signs the Rust
6
+ golden vectors with this module and compares the bytes.
7
+
8
+ Builders take the same JSON shapes the REST API uses (snake_case keys,
9
+ amounts as decimal strings), so a request body and its signed message cannot
10
+ drift apart.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import uuid
16
+ from typing import Any
17
+
18
+ from eth_account import Account
19
+ from eth_account.messages import _hash_eip191_message, encode_typed_data
20
+ from eth_utils import keccak
21
+
22
+ _LEG = [
23
+ {"name": "instrumentId", "type": "bytes32"},
24
+ {"name": "priceMicros", "type": "uint128"},
25
+ ]
26
+ _FEES = [
27
+ {"name": "perExecutionMicros", "type": "uint128"},
28
+ {"name": "cumulativeMicros", "type": "uint128"},
29
+ ]
30
+
31
+ TYPES: dict[str, dict[str, list[dict[str, str]]]] = {
32
+ "AuthorizeRfqReadV2": {
33
+ "AuthorizeRfqReadV2": [
34
+ {"name": "account", "type": "address"},
35
+ {"name": "issuedAtMs", "type": "uint64"},
36
+ {"name": "expiresAtMs", "type": "uint64"},
37
+ {"name": "nonce", "type": "uint64"},
38
+ ]
39
+ },
40
+ "AuthorizeRfqQuoteV2": {
41
+ "AuthorizeRfqQuoteV2": [
42
+ {"name": "terms", "type": "RfqFirmQuoteV2SigningTerms"},
43
+ {"name": "nonce", "type": "uint64"},
44
+ ],
45
+ "RfqFirmQuoteV2SigningTerms": [
46
+ {"name": "quoteId", "type": "bytes16"},
47
+ {"name": "rfqId", "type": "bytes16"},
48
+ {"name": "rfqTermsCommitment", "type": "bytes32"},
49
+ {"name": "makerAccount", "type": "address"},
50
+ {"name": "makerGeneration", "type": "uint64"},
51
+ {"name": "rfqGeneration", "type": "uint64"},
52
+ {"name": "pricedLegs", "type": "RfqV2SigningPriceLeg[]"},
53
+ {"name": "referenceQuantity", "type": "uint128"},
54
+ {"name": "makerReceivesReferencePremium", "type": "bool"},
55
+ {"name": "referencePremiumMicros", "type": "uint128"},
56
+ {"name": "capacity", "type": "uint128"},
57
+ {"name": "fillPolicy", "type": "uint8"},
58
+ {"name": "minimumUnits", "type": "uint128"},
59
+ {"name": "stepUnits", "type": "uint128"},
60
+ {"name": "withdrawalPolicy", "type": "uint8"},
61
+ {"name": "feeLimits", "type": "RfqV2SigningFeeLimits"},
62
+ {"name": "expiresAtMs", "type": "uint64"},
63
+ {"name": "protectionScope", "type": "bytes32"},
64
+ {"name": "hasSourceIndicativeQuote", "type": "bool"},
65
+ {"name": "sourceIndicativeQuoteId", "type": "bytes16"},
66
+ ],
67
+ "RfqV2SigningPriceLeg": _LEG,
68
+ "RfqV2SigningFeeLimits": _FEES,
69
+ },
70
+ "DeclineRfqV2": {
71
+ "DeclineRfqV2": [
72
+ {"name": "rfqId", "type": "bytes16"},
73
+ {"name": "makerAccount", "type": "address"},
74
+ {"name": "operationId", "type": "bytes16"},
75
+ {"name": "expiresAtMs", "type": "uint64"},
76
+ {"name": "nonce", "type": "uint64"},
77
+ ]
78
+ },
79
+ "InvalidateRfqV2": {
80
+ "InvalidateRfqV2": [
81
+ {"name": "rfqId", "type": "bytes16"},
82
+ {"name": "quoteId", "type": "bytes16"},
83
+ {"name": "scope", "type": "uint8"},
84
+ {"name": "reason", "type": "uint8"},
85
+ {"name": "operationId", "type": "bytes16"},
86
+ {"name": "expiresAtMs", "type": "uint64"},
87
+ {"name": "nonce", "type": "uint64"},
88
+ ]
89
+ },
90
+ "BulkWithdrawRfqV2": {
91
+ "BulkWithdrawRfqV2": [
92
+ {"name": "makerAccount", "type": "address"},
93
+ {"name": "scope", "type": "uint8"},
94
+ {"name": "rfqId", "type": "bytes16"},
95
+ {"name": "targets", "type": "RfqV2BulkWithdrawalTarget[]"},
96
+ {"name": "operationId", "type": "bytes16"},
97
+ {"name": "expiresAtMs", "type": "uint64"},
98
+ {"name": "nonce", "type": "uint64"},
99
+ ],
100
+ "RfqV2BulkWithdrawalTarget": [
101
+ {"name": "rfqId", "type": "bytes16"},
102
+ {"name": "quoteId", "type": "bytes16"},
103
+ ],
104
+ },
105
+ "ScheduleRfqQuoteCancelV2": {
106
+ "ScheduleRfqQuoteCancelV2": [
107
+ {"name": "operationId", "type": "bytes16"},
108
+ {"name": "makerAccount", "type": "address"},
109
+ {"name": "cancelAtMs", "type": "uint64"},
110
+ {"name": "expiresAtMs", "type": "uint64"},
111
+ {"name": "nonce", "type": "uint64"},
112
+ ]
113
+ },
114
+ # Perp orders use the directive domain "HypercallApiSign", not "Hypercall".
115
+ "HLOrder": {
116
+ "HLOrder": [
117
+ {"name": "account", "type": "address"},
118
+ {"name": "nonce", "type": "uint64"},
119
+ {"name": "action", "type": "LimitOrder"},
120
+ ],
121
+ "LimitOrder": [
122
+ {"name": "asset", "type": "uint32"},
123
+ {"name": "isBuy", "type": "bool"},
124
+ {"name": "limitPx", "type": "uint64"},
125
+ {"name": "sz", "type": "uint64"},
126
+ {"name": "reduceOnly", "type": "bool"},
127
+ {"name": "encodedTif", "type": "uint8"},
128
+ {"name": "cloid", "type": "uint128"},
129
+ ],
130
+ },
131
+ }
132
+
133
+ FILL_POLICY = {"full_size_once": 0, "one_smaller_package": 1, "repeated_partial": 2}
134
+ ZERO16 = b"\x00" * 16
135
+ ZERO32 = b"\x00" * 32
136
+
137
+
138
+ def instrument_id(symbol: str) -> bytes:
139
+ """Signed instrument identity: keccak256("instrument" || symbol)."""
140
+ return keccak(b"instrument" + symbol.encode())
141
+
142
+
143
+ def uid(value: str | uuid.UUID) -> bytes:
144
+ return uuid.UUID(str(value)).bytes
145
+
146
+
147
+ def b32(hex_value: str) -> bytes:
148
+ return bytes.fromhex(hex_value.removeprefix("0x"))
149
+
150
+
151
+ def digest(primary: str, message: dict[str, Any], chain_id: int, domain: str = "Hypercall") -> bytes:
152
+ """The 32-byte EIP-712 signing hash."""
153
+ return _hash_eip191_message(_signable(primary, message, chain_id, domain))
154
+
155
+
156
+ def sign(primary: str, message: dict[str, Any], key: str, chain_id: int, domain: str = "Hypercall") -> str:
157
+ """Sign and return the 65-byte signature as lowercase 0x hex (v = 27 or 28)."""
158
+ signed = Account.sign_message(_signable(primary, message, chain_id, domain), key)
159
+ return "0x" + signed.signature.hex().removeprefix("0x")
160
+
161
+
162
+ def _signable(primary: str, message: dict[str, Any], chain_id: int, domain: str):
163
+ types = {
164
+ "EIP712Domain": [
165
+ {"name": "name", "type": "string"},
166
+ {"name": "version", "type": "string"},
167
+ {"name": "chainId", "type": "uint256"},
168
+ {"name": "verifyingContract", "type": "address"},
169
+ ],
170
+ **TYPES[primary],
171
+ }
172
+ return encode_typed_data(
173
+ full_message={
174
+ "types": types,
175
+ "primaryType": primary,
176
+ "domain": {
177
+ "name": domain,
178
+ "version": "1",
179
+ "chainId": chain_id,
180
+ "verifyingContract": "0x0000000000000000000000000000000000000000",
181
+ },
182
+ "message": message,
183
+ }
184
+ )
185
+
186
+
187
+ # ---- message builders: wire JSON in, EIP-712 message out -------------------
188
+
189
+
190
+ def read_grant_message(account: str, issued_at_ms: int, expires_at_ms: int, nonce: int) -> dict:
191
+ return {"account": account, "issuedAtMs": issued_at_ms, "expiresAtMs": expires_at_ms, "nonce": nonce}
192
+
193
+
194
+ def firm_quote_message(terms: dict, nonce: int) -> dict:
195
+ """`terms` is the `terms` object of POST /private/rfqs/{id}/quotes/firm."""
196
+ policy = terms["fill_policy"]
197
+ source = terms.get("source_indicative_quote_id")
198
+ scope = terms.get("protection_scope")
199
+ return {
200
+ "terms": {
201
+ "quoteId": uid(terms["id"]),
202
+ "rfqId": uid(terms["rfq_id"]),
203
+ "rfqTermsCommitment": b32(terms["rfq_terms_commitment"]),
204
+ "makerAccount": terms["maker_account"],
205
+ "makerGeneration": terms["maker_generation"],
206
+ "rfqGeneration": terms["rfq_generation"],
207
+ "pricedLegs": [
208
+ {"instrumentId": instrument_id(leg["instrument"]), "priceMicros": int(leg["price_micros"])}
209
+ for leg in terms["priced_legs"]
210
+ ],
211
+ "referenceQuantity": int(terms["reference_quantity"]),
212
+ "makerReceivesReferencePremium": terms["maker_receives_reference_premium"],
213
+ "referencePremiumMicros": int(terms["reference_premium_micros"]),
214
+ "capacity": int(terms["capacity"]),
215
+ "fillPolicy": FILL_POLICY[policy["mode"]],
216
+ "minimumUnits": int(policy.get("minimum", 0)),
217
+ "stepUnits": int(policy.get("step", 0)),
218
+ "withdrawalPolicy": 1 if terms["withdrawal_policy"] == "permitted" else 0,
219
+ "feeLimits": {
220
+ "perExecutionMicros": int(terms["fee_limits"]["per_execution"]),
221
+ "cumulativeMicros": int(terms["fee_limits"]["cumulative"]),
222
+ },
223
+ "expiresAtMs": terms["expires_at_ms"],
224
+ "protectionScope": b32(scope) if scope else ZERO32,
225
+ "hasSourceIndicativeQuote": source is not None,
226
+ "sourceIndicativeQuoteId": uid(source) if source else ZERO16,
227
+ },
228
+ "nonce": nonce,
229
+ }
230
+
231
+
232
+ def decline_message(rfq_id: str, body: dict) -> dict:
233
+ return {
234
+ "rfqId": uid(rfq_id),
235
+ "makerAccount": body["maker_account"],
236
+ "operationId": uid(body["operation_id"]),
237
+ "expiresAtMs": body["expires_at_ms"],
238
+ "nonce": body["nonce"],
239
+ }
240
+
241
+
242
+ def withdraw_quote_message(rfq_id: str, quote_id: str, body: dict) -> dict:
243
+ # scope 1 / reason 1 is "maker withdraws a quote"; both are signed so a
244
+ # withdrawal can't be replayed as an RFQ cancellation.
245
+ return {
246
+ "rfqId": uid(rfq_id),
247
+ "quoteId": uid(quote_id),
248
+ "scope": 1,
249
+ "reason": 1,
250
+ "operationId": uid(body["operation_id"]),
251
+ "expiresAtMs": body["expires_at_ms"],
252
+ "nonce": body["nonce"],
253
+ }
254
+
255
+
256
+ def bulk_withdrawal_message(body: dict) -> dict:
257
+ scope = body["scope"]
258
+ tag = {"quote_ids": 0, "rfq": 1, "all_open": 2}[scope["mode"]]
259
+ return {
260
+ "makerAccount": body["maker_account"],
261
+ "scope": tag,
262
+ "rfqId": uid(scope["rfq_id"]) if tag == 1 else ZERO16,
263
+ "targets": [
264
+ {"rfqId": uid(t["rfq_id"]), "quoteId": uid(t["quote_id"])} for t in scope.get("quote_ids", [])
265
+ ],
266
+ "operationId": uid(body["operation_id"]),
267
+ "expiresAtMs": body["expires_at_ms"],
268
+ "nonce": body["nonce"],
269
+ }
270
+
271
+
272
+ def cancel_schedule_message(body: dict) -> dict:
273
+ return {
274
+ "operationId": uid(body["operation_id"]),
275
+ "makerAccount": body["maker_account"],
276
+ "cancelAtMs": body.get("cancel_at_ms") or 0, # zero removes the schedule
277
+ "expiresAtMs": body["expires_at_ms"],
278
+ "nonce": body["nonce"],
279
+ }
280
+
281
+
282
+ def perp_order_message(body: dict) -> dict:
283
+ """`body` is the POST /v1/actions/hl_limit_order request."""
284
+ a = body["action"]
285
+ return {
286
+ "account": body["account"],
287
+ "nonce": int(body["nonce"]),
288
+ "action": {
289
+ "asset": a["asset"],
290
+ "isBuy": a["isBuy"],
291
+ "limitPx": int(a["limitPx"]),
292
+ "sz": int(a["sz"]),
293
+ "reduceOnly": a["reduceOnly"],
294
+ "encodedTif": a["encodedTif"],
295
+ "cloid": int(a["cloid"]),
296
+ },
297
+ }
298
+
299
+
300
+ # ---- premium ---------------------------------------------------------------
301
+
302
+ _SCALE = 10**12 # prices and quantities are both micros
303
+
304
+
305
+ def reference_premium(legs: list[dict], prices_micros: list[int], reference_quantity: int, step: int | None):
306
+ """(maker_receives, premium_micros) for a quote, or None if not exact.
307
+
308
+ A taker buy leg pays the maker, a taker sell leg pays the taker. The
309
+ server recomputes this and refuses any other value. For partial-fill
310
+ policies the premium of one `step` must also be whole micros.
311
+ Mirrors `rfq_v2_reference_premium` in Rust.
312
+ """
313
+ maker = taker = 0
314
+ for leg, price in zip(legs, prices_micros, strict=True):
315
+ scaled = price * int(leg["quantity_micros_per_unit"]) * reference_quantity
316
+ if leg["taker_side"] == "buy":
317
+ maker += scaled
318
+ else:
319
+ taker += scaled
320
+ receives, scaled = (True, maker - taker) if maker > taker else (False, taker - maker)
321
+ if step is not None and (scaled // reference_quantity * step) % _SCALE:
322
+ return None
323
+ if scaled % _SCALE:
324
+ return None
325
+ return receives, scaled // _SCALE
@@ -0,0 +1,68 @@
1
+ Metadata-Version: 2.5
2
+ Name: hypercall-rfq-example
3
+ Version: 0.1.0
4
+ Summary: Demo helpers for the Hypercall RFQ v2 maker tutorial: EIP-712 signing, read grants, quoting, executions.
5
+ Project-URL: Homepage, https://github.com/hypercall-public/hypercall-rfq-example
6
+ Project-URL: Tutorial, https://blog.hypercall.xyz/build-an-rfq-v2-maker/
7
+ Project-URL: Documentation, https://docs.hypercall.xyz/docs/trading/over-api/rfq-v2
8
+ Author: Hypercall
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: eip712,hypercall,hyperliquid,market-making,options,rfq
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Requires-Python: >=3.11
16
+ Requires-Dist: eth-account>=0.13
17
+ Requires-Dist: httpx>=0.27
18
+ Requires-Dist: websockets>=13
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
21
+ Requires-Dist: pytest>=8; extra == 'test'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # hypercall-rfq-example
25
+
26
+ Demo helpers and the demo maker (`maker.py`) for the Hypercall tutorial
27
+ [Build an RFQ V2 Maker](https://blog.hypercall.xyz/build-an-rfq-v2-maker/). They cover
28
+ read grants, the `rfq_v2` stream with change-feed replay, signed firm quotes,
29
+ declines, withdrawals, the cancel-schedule heartbeat, the executions stream,
30
+ the provider read, and perp hedge orders through Hypercall.
31
+
32
+ This is teaching code, kept short enough to read in one sitting. It is not a
33
+ supported SDK. For production integrations use the Rust client
34
+ (`hypercall-client`) or sign the documented EIP-712 messages yourself.
35
+
36
+ Needs Python 3.11 or newer (the maker uses `asyncio.TaskGroup`).
37
+
38
+ ```bash
39
+ pip install hypercall-rfq-example
40
+ curl -O https://raw.githubusercontent.com/hypercall-public/hypercall-rfq-example/main/maker.py
41
+ export HC_ACCOUNT=0xYourAccount HC_SIGNER_KEY=0xApiWalletKey
42
+ python maker.py --dry-run
43
+ ```
44
+
45
+ `--dry-run` prices and logs RFQs without posting quotes, declines, withdrawals
46
+ or hedges. Without it the maker posts firm, executable quotes.
47
+
48
+ On SIGINT or SIGTERM the maker withdraws every open quote and clears its
49
+ cancel schedule before it exits. A `kill -9` skips that; the 30-second
50
+ dead-man switch then withdraws the quotes instead.
51
+
52
+ The perp hedge only works for a portfolio margin Account contract with an
53
+ on-chain API wallet as the signer. See step 7 of the tutorial for the full
54
+ list; with a plain wallet as `HC_ACCOUNT`, hedge orders fail with
55
+ `400 unknown_account`.
56
+
57
+ ## Tests
58
+
59
+ ```bash
60
+ pip install -e '.[test]' && pytest
61
+ ```
62
+
63
+ `tests/test_signing_parity.py` signs golden vectors generated by the Rust
64
+ signer and must match them byte for byte.
65
+
66
+ ## License
67
+
68
+ MIT
@@ -0,0 +1,7 @@
1
+ hypercall_rfq_example/__init__.py,sha256=e_1jZRpKl_0iy3FeJkY4efNTIiG8LHNSDfmIi-NeHVY,279
2
+ hypercall_rfq_example/client.py,sha256=fX6Qv1LP_9KmGqArXvoR0IbgY65BHgbRAXKh0niO-Po,24470
3
+ hypercall_rfq_example/signing.py,sha256=FO7A84NxSXlg1AxmecvT5QQfHf2wI8DEek_NSICsWwg,12440
4
+ hypercall_rfq_example-0.1.0.dist-info/METADATA,sha256=Q-DWzNlgLiHsHOFA1IVtyKEK3j80poY0cnV966F1oiQ,2625
5
+ hypercall_rfq_example-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ hypercall_rfq_example-0.1.0.dist-info/licenses/LICENSE,sha256=feOA-YpNWvpsQ6p6MvkWYuaAJc-4nql_0rfS-naZi0c,1066
7
+ hypercall_rfq_example-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hypercall
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.