@lit-protocol/lit-venues 0.2.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/README.md ADDED
@@ -0,0 +1,122 @@
1
+ # @lit-protocol/lit-venues
2
+
3
+ Native exchange venue connectors for Lit Actions / Flows. Binance (+ binance.us),
4
+ Coinbase Advanced Trade, and Hyperliquid perps behind one small, auditable,
5
+ ccxt-shaped interface.
6
+
7
+ > Ported from the Chipotle/lit-node-express runtime repo, where it was developed
8
+ > against the Lit Action sandbox. The connectors are **plain library code** — not
9
+ > a runtime primitive — so they live as a standalone package here in flows. The
10
+ > two TEE-side primitives they can use (`Lit.Actions.proxiedFetch` for egress and
11
+ > the email-approval ops) are part of the **Chipotle runtime**, not this package;
12
+ > a flow reaches them by executing on a Chipotle environment that has them.
13
+
14
+ Design constraints, by construction:
15
+
16
+ - **Action-runtime portable.** Only `fetch` + plain JS — no Node built-ins, no
17
+ `Buffer`, no WebCrypto assumptions. Request signing (HMAC-SHA256, Ed25519,
18
+ ES256 JWT, EIP-712/secp256k1) uses bundled `@noble/hashes` + `@noble/curves`.
19
+ - **Quota-aware.** Single-symbol market lookups (`fetchMarket`), no full-market
20
+ loads, small responses — designed for the 50-outbound-fetch / 1MB-response
21
+ action limits. Pre-fetched rules can be injected via `markets` to spend zero
22
+ fetches.
23
+ - **Exact decimals.** Amounts/prices are decimal strings end to end; `addDec` /
24
+ `subDec` / `roundDownToIncrement` do scaled-BigInt math. Hyperliquid's signed
25
+ action hash commits to `wireDecimal`-normalized strings — no float ever
26
+ touches an order.
27
+ - **Egress-ready.** A `proxy` config routes through the in-TEE
28
+ `Lit.Actions.proxiedFetch` op (provided by the Chipotle runtime); inert
29
+ elsewhere.
30
+
31
+ ## Build
32
+
33
+ This package builds to an IIFE bundle (for inlining into a flow's action code,
34
+ which runs as a plain script, not a module) and an ESM build:
35
+
36
+ ```sh
37
+ npm install
38
+ npm test # vitest — signing pinned to Binance docs / RFC 8032 / Hyperliquid SDK vectors
39
+ npm run build # esbuild → dist/lit-venues.iife.js (+ .mjs), prints size + sha384
40
+ npm run typecheck
41
+ ```
42
+
43
+ ## Usage inside a flow's Lit Action (inline bundle, v0)
44
+
45
+ ```js
46
+ // dist/lit-venues.iife.js concatenated above the action → global `LitVenues`
47
+ async function main({ sealedCreds }) {
48
+ const creds = JSON.parse(await Lit.Actions.Decrypt(sealedCreds)); // venue-credentials-v1
49
+ const binance = LitVenues.createVenue({
50
+ venueId: 'binance',
51
+ sandbox: true, // spot testnet
52
+ credentials: { apiKey: creds.apiKey, secret: creds.secret, keyType: creds.keyType },
53
+ proxy: creds.egress?.proxyUrl, // routes via Lit.Actions.proxiedFetch; inert without it
54
+ });
55
+ return { balances: await binance.fetchBalances() };
56
+ }
57
+ ```
58
+
59
+ PKP-native venues need no sealed credential — the signing key is the
60
+ action-bound TEE key:
61
+
62
+ ```js
63
+ async function main() {
64
+ const hl = LitVenues.createVenue({
65
+ venueId: 'hyperliquid',
66
+ credentials: {
67
+ keyType: 'pkp-eip712',
68
+ privateKey: await Lit.Actions.getLitActionPrivateKey(), // never leaves the TEE
69
+ accountAddress: '0xMASTER…', // agent mode: PKP trades for the user's master account
70
+ },
71
+ });
72
+ return { positions: await hl.fetchPositions() };
73
+ }
74
+ ```
75
+
76
+ Once published, the ESM build (`dist/lit-venues.mjs`) becomes importable via an
77
+ integrity-pinned CDN import path instead of inlining.
78
+
79
+ ## Surface
80
+
81
+ `createVenue({ venueId, credentials?, sandbox?, proxy?, fetchImpl?, nowMs?, markets?, signFn?, slippageBps?, builder? })` → `VenueClient`:
82
+ `fetchTicker`, `fetchMarket`, `fetchBalances`, `createOrder`, `cancelOrder`, `fetchOpenOrders`, `fetchMyTrades`,
83
+ plus the optional perp surface: `fetchPositions`, `setLeverage`, `fetchFundingRate`.
84
+
85
+ Errors are `VenueError` with a unified taxonomy: `auth`, `insufficient_funds`,
86
+ `bad_symbol`, `rate_limited`, `venue_unavailable`, `invalid_request`, `unknown`
87
+ (plus `httpStatus` / raw `venueCode`).
88
+
89
+ Amounts/prices are **decimal strings** end to end — use `LitVenues.addDec` /
90
+ `subDec` / `roundDownToIncrement`, never floats.
91
+
92
+ ## Venue notes
93
+
94
+ - **binance** — `sandbox: true` → `testnet.binance.vision`. HMAC by default; set
95
+ `keyType: 'ed25519'` for Binance's recommended self-generated keys (PKCS8 PEM,
96
+ hex, or base64). binance.com geo-blocks US egress (451) — route through the
97
+ egress proxy or use the spot testnet.
98
+ - **binanceus** — separate venue id, no testnet.
99
+ - **coinbase** — Advanced Trade with CDP keys (ES256 JWT; no Ed25519 here). PEMs
100
+ accepted with real newlines OR the literal `\n` of the CDP JSON download. **No
101
+ sandbox** — `sandbox: true` throws. Market BUY orders take `quoteAmount`.
102
+ - **hyperliquid** — PKP-native perps: no API key; every trading action is an
103
+ EIP-712 signature (msgpack action hash → phantom agent, chainId 1337), pinned
104
+ byte-for-byte to the official SDK's test vectors in
105
+ `test/hyperliquid-signing.test.ts`. `sandbox: true` →
106
+ `api.hyperliquid-testnet.xyz`. Reads work with `accountAddress` alone; trading
107
+ needs `privateKey` (or a custom `signFn`). When the key is a registered agent
108
+ (API wallet), reads auto-resolve its MASTER. `approveAgent()` lets a master key
109
+ grant the PKP trade-only powers — agents structurally cannot withdraw.
110
+ `fetchBalances` merges perp equity + spot USDC. Market orders are aggressive IOC
111
+ limits (`slippageBps`, default 5%) obeying 5-sig-fig / szDecimals rules.
112
+
113
+ Withdrawal endpoints are deliberately absent (policy-gated sweeps go through the
114
+ Chipotle runtime's email-approval primitive).
115
+
116
+ ## What stayed in the Chipotle runtime repo
117
+
118
+ - `op_lit_proxied_fetch` (`Lit.Actions.proxiedFetch`) — in-TEE egress op (Rust).
119
+ - The email-approval ops + `ApprovalService` (in-TEE attestation verify).
120
+ - The chipotle SDK quickstart examples (CID-pinned PKP setup scripts).
121
+
122
+ Those are runtime/SDK concerns, not portable library code, so they remain there.