12pip install requests eth-account web3 python quickstart.py
HV_GATEWAY is the exchange's address: the web client's, the name these
pages are on without docs.. The program defaults to the testnet's.HV_PRIVATE_KEY is the key to trade with. Without it the program makes a new
one and prints it: export it before the next run, or you start over with an
empty account."""Hypervolic quickstart: from a fresh key to a resting order and its cancel. pip install requests eth-account web3 python quickstart.py HV_GATEWAY is the exchange's address; HV_PRIVATE_KEY the key to trade with. Without a key the program makes one and prints it: keep it for the next run. """ import os import sys import time from urllib.parse import urljoin import requests from eth_account import Account from eth_account.messages import encode_defunct from web3 import Web3 GATEWAY = os.environ.get("HV_GATEWAY", "https://testnet.hv.exchange").rstrip("/") DEPOSIT = 100_000_000 # $100, in micro-USDC if os.environ.get("HV_PRIVATE_KEY"): acct = Account.from_key(os.environ["HV_PRIVATE_KEY"]) else: acct = Account.create() print(f"new key: export HV_PRIVATE_KEY={acct.key.hex()}") print("address", acct.address) http = requests.Session() def call(method, path, **kw): r = http.request(method, f"{GATEWAY}{path}", timeout=30, **kw) if r.status_code >= 400: sys.exit(f"{method} {path}: {r.status_code} {r.text}") return r.json() # 1. What to sign for, and where the chain is. config = call("GET", "/v1/config") SETTLEMENT = Web3.to_checksum_address(config["settlement"]) USDC = Web3.to_checksum_address(config["usdc"]) DOMAIN = { "name": "Hypervolic", "version": "1", "chainId": config["chainId"], "verifyingContract": SETTLEMENT, } print("chain", config["chainId"], config["chainName"], "contract", SETTLEMENT) # 2. A session, for reading the account: sign the gateway's sign-in message. ch = call("POST", "/v1/session/challenge", json={"address": acct.address}) signed = acct.sign_message(encode_defunct(text=ch["message"])) session = call("POST", "/v1/session", json={ "address": acct.address, "challenge": ch["challenge"], "signature": "0x" + bytes(signed.signature).hex(), }) http.headers["Authorization"] = f"Bearer {session['token']}" def account(): return call("GET", f"/v1/account/{acct.address}") # 3. Funds: test USDC from the faucet, then a deposit to the settlement # contract. Skipped once the account holds free cash. me = account() if not me["known"] or me["engine"]["freeCash"] < DEPOSIT // 2: w3 = None for url in [config["rpcUrl"], *config.get("rpcFallback", [])]: w3 = Web3(Web3.HTTPProvider(urljoin(GATEWAY + "/", url))) if w3.is_connected(): break usdc = w3.eth.contract(address=USDC, abi=[ {"name": "balanceOf", "type": "function", "stateMutability": "view", "inputs": [{"name": "a", "type": "address"}], "outputs": [{"name": "", "type": "uint256"}]}, {"name": "approve", "type": "function", "stateMutability": "nonpayable", "inputs": [{"name": "s", "type": "address"}, {"name": "v", "type": "uint256"}], "outputs": [{"name": "", "type": "bool"}]}, ]) hv = w3.eth.contract(address=SETTLEMENT, abi=[ {"name": "MIN_DEPOSIT", "type": "function", "stateMutability": "view", "inputs": [], "outputs": [{"name": "", "type": "uint256"}]}, {"name": "deposit", "type": "function", "stateMutability": "nonpayable", "inputs": [{"name": "amount", "type": "uint256"}], "outputs": []}, ]) amount = max(DEPOSIT, hv.functions.MIN_DEPOSIT().call()) if usdc.functions.balanceOf(acct.address).call() < amount: # The faucet's claim is its text for this address, signed (personal_sign). ch = http.get(f"{GATEWAY}/faucet/challenge", params={"address": acct.address}, timeout=30) if not ch.ok: sys.exit(f"faucet: {ch.status_code} {ch.text}") text = ch.json()["message"] claim = acct.sign_message(encode_defunct(text=text)) r = http.post(f"{GATEWAY}/faucet/grant", timeout=120, json={ "address": acct.address, "message": text, "signature": "0x" + bytes(claim.signature).hex(), }) if not r.ok: sys.exit(f"faucet: {r.status_code} {r.text}") print("faucet", r.json()) while usdc.functions.balanceOf(acct.address).call() < amount: time.sleep(2) def send(fn): tx = fn.build_transaction({ "from": acct.address, "chainId": config["chainId"], "nonce": w3.eth.get_transaction_count(acct.address, "pending"), }) h = w3.eth.send_raw_transaction(acct.sign_transaction(tx).raw_transaction) if w3.eth.wait_for_transaction_receipt(h, timeout=300).status != 1: sys.exit(f"transaction {h.hex()} reverted") send(usdc.functions.approve(SETTLEMENT, amount)) send(hv.functions.deposit(amount)) print("deposited", amount / 1e6, "USDC; waiting for the exchange to credit it") # Credited once the deposit's block is a few seconds old (config["confirmationSeconds"]). while not me["known"] or me["engine"]["freeCash"] < amount // 2: time.sleep(5) me = account() print("free cash", me["engine"]["freeCash"] / 1e6, "USDC") # 4. A contract: a call that expires more than an hour from now. now = int(time.time() * 1000) - 1_577_836_800_000 # engine milliseconds: since 2020-01-01Z inst = min( (i for i in call("GET", "/v1/instruments") if i["right"] == 0 and i["expiryMs"] > now + 3_600_000), key=lambda i: (i["expiryMs"], abs(i["strike"] - 500_000)), ) book = call("GET", f"/v1/book/{inst['underlyingKey']}/{inst['specifier']}") print("contract", inst["underlyingKey"], inst["specifier"], "strike", inst["strike"], "best bid", book["bids"][:1], "best ask", book["asks"][:1]) # 5. A signed order: buy one contract at 0.001, $0.10, well under any ask, so it rests. ORDER = {"Order": [ {"name": "maker", "type": "address"}, {"name": "underlyingKey", "type": "uint64"}, {"name": "optionSpecifier", "type": "uint64"}, {"name": "side", "type": "uint8"}, {"name": "size", "type": "uint64"}, {"name": "limitPrice", "type": "uint64"}, {"name": "nonce", "type": "uint64"}, {"name": "expiresAt", "type": "uint64"}, {"name": "maxFeePerMille", "type": "uint8"}, ]} nonce = time.time_ns() // 1_000 # microseconds: increasing, and under 2^54 order = { "maker": acct.address, "underlyingKey": inst["underlyingKey"], "optionSpecifier": inst["specifier"], "side": 0, # buy "size": 1, "limitPrice": 1_000, "nonce": nonce, "expiresAt": inst["expiryMs"], # good until the contract expires "maxFeePerMille": -(-max(inst["makerFeeBps"], inst["takerFeeBps"]) // 10), # tens of bps, rounded up } sig = Account.sign_typed_data(acct.key, DOMAIN, ORDER, order).signature placed = call("POST", "/v1/orders?wait=2000", json={"order": order, "signature": "0x" + bytes(sig).hex()}) print("order", placed) r = http.get(f"{GATEWAY}/v1/orders/{acct.address}/{nonce}", timeout=30) print("status", r.status_code, r.json()) # 6. Cancel it, by its nonce, under a nonce of the cancel's own. CANCEL = {"Cancel": [ {"name": "maker", "type": "address"}, {"name": "nonce", "type": "uint64"}, {"name": "orderNonce", "type": "uint64"}, ]} cancel = {"maker": acct.address, "nonce": nonce + 1, "orderNonce": nonce} sig = Account.sign_typed_data(acct.key, DOMAIN, CANCEL, cancel).signature print("cancel", call("POST", "/v1/cancel", json={**cancel, "signature": "0x" + bytes(sig).hex()})) r = http.get(f"{GATEWAY}/v1/orders/{acct.address}/{nonce}", timeout=30) print("status", r.status_code, r.json())
1234567891011new key: export HV_PRIVATE_KEY=9fd3c4a0… address 0x3A36a34253D426dd5D6749C668BF15443C97Eb31 chain 84532 Base Sepolia contract 0x… faucet {'address': '0x3A36…', 'usdc': '1000000000', 'eth': '500000000000000', 'txs': […], 'nextAt': 1794543067} deposited 100.0 USDC; waiting for the exchange to credit it free cash 100.0 USDC contract 7 931117472660193546 strike 500000 best bid [] best ask [{'price': 31000, 'quantity': 5}] order {'status': 'resting', 'orderId': '11:0', 'clientId': 1794456685029978, 'fills': []} status 200 {'state': 'resting', 'orderId': '11:0', 'remaining': 1, 'filled': 0, 'position': 6} cancel {'status': 'cancelled'} status 200 {'state': 'done', 'how': 'cancelled', 'orderId': '11:0', 'remaining': 0, 'filled': 0, 'position': 7}
GET /v1/config names the chain, the settlement
contract and the USDC token. The contract's address and the chain id are the
EIP-712 domain every signature is made under. Read them here on every
start: a reset is a new contract.deposit. The exchange credits the deposit once its block
is a few seconds old (confirmationSeconds in
GET /v1/config), and your first deposit opens your
account. See
Funding. The program skips this step once the account has
free cash.GET /v1/instruments lists every contract with
its expiry, strike and fee rates. Python's integers are exact, so the
specifier, which is often above 253, survives as it is.nonce is its name: unique
for your account and increasing (see Nonces).
expiresAt equal to the contract's expiry makes it good until the contract
expires. With ?wait, the answer is the engine's: resting, filled,
expired or refused with a code. See Place an order.