Upgrade Derive spot & perpetual connectors to Derive v3 API
Summary
Derive has launched its v3 API. Settlement now happens on Ethereum L1 (mainnet chainId 1, testnet Sepolia 11155111) instead of the Derive L2 (chain 957). Our derive (spot) and derive_perpetual connectors still target the v2 API at api.lyra.finance: v2 URLs, X-Lyra* headers, the chain-957 domain separator and millisecond nonces. They need to be upgraded to v3.
The three official SDKs are the reference:
- https://github.com/derivexyz/derive-py (PyPI
derive-py0.1.3; Python signing helpers and OpenAPI/AsyncAPI specs inspecs/) - https://github.com/derivexyz/derive-ts (
@derivexyz/derive-ts3.0.26; the most complete and current, and has golden signing vectors intest/unit/fixtures/golden-vectors.json) - https://github.com/derivexyz/derive-rs (⚠️ its mainnet values are stale: it still has
wss://api.lyra.finance/wsand the v2 domain separator; only its testnet values are current)
Docs: https://docs.derive.xyz/migrating/breaking-changes · https://docs.derive.xyz/openapi.json · https://docs.derive.xyz/error-codes
Recommendation: port the signing logic into hummingbot/connector/other/derive_common_utils.py (about 150 LOC, taken from derive_py/_web3/action_signing/ and derive_py/config/contracts.py) rather than depending on derive-py. The package is a young beta, pulls in pandas, rich, click and web3 7, and ships its own HTTP/WS session stack, which would duplicate our web-assistant layer.
What changes in v3 (relevant to us)
| v2 (current connector) | v3 | |
|---|---|---|
| REST base (mainnet) | https://api.lyra.finance |
https://api.derive.xyz/v3 |
| WS (mainnet) | wss://api.lyra.finance/ws |
wss://api.derive.xyz/v3/ws |
| REST base (testnet) | https://api-demo.lyra.finance |
https://testnet.api.derive.xyz/v3 |
| WS (testnet) | wss://api-demo.lyra.finance/ws |
wss://testnet.api.derive.xyz/v3/ws |
| Chain ID | 957 / 901 | 1 / 11155111 |
DOMAIN_SEPARATOR mainnet |
0xd96e5f90…441b |
0xda616dfabb88681b08e1592820a41d55ddc62d68de110e327ae99d734506fe19 |
DOMAIN_SEPARATOR testnet |
0x9bcf4dc0…1105 |
0x24d674cd5f2b9d564691c51e9d88f649b99246a2244dd74ce27b96578d773e85 |
| Auth headers | X-LyraWallet / X-LyraTimestamp / X-LyraSignature |
X-DeriveWallet / X-DeriveTimestamp / X-DeriveSignature |
| Nonce | int(ms + "0") |
UTC nanoseconds, sent as a JSON string; ms/µs nonces are rejected |
signature_expiry_sec |
2**31-1 |
must be 300 s – 120 days from now (error 11011), and ≤ the session key's expiry (14038) |
| Signed decimals | e18 | still e18 words, but precision beyond 1e-12 is rejected (not truncated); values must fit in i128 |
public/get_ticker |
full ticker (best_bid_price, perp_details, …) |
slim ticker: A, B, I, M, a, b, f, maxp, minp, stats, t |
| Session keys | unscoped | scoped (protocol scopes, expiry, optional subaccount list, optional IP whitelist) |
private/get_orders |
exists | removed; use private/get_open_orders + private/get_order_history |
| REST requirement | — | requests without a User-Agent header are rejected |
Unchanged: ACTION_TYPEHASH (0x4d7a9f27…af17), the EIP-712 domain name/version ("Matching", "1.0", verifyingContract 0xeB8d770ec18DB98Db922E9D83260A585b9F0DeAD), TRADE_MODULE (0xB8D20c2B7a1Ad2EE33Bc50eF10876eD3035b5e7b, now the same on every network), the trade module data layout (address asset, uint subId, int limitPrice, int amount, uint maxFee, uint recipientId, bool isBid), the JSON-RPC envelope, the WS public/login / subscribe flow, the orderbook.{inst}.{group}.{depth}, trades.{inst}, ticker_slim.{inst}.{interval} and {subaccount_id}.orders|trades channels, and instrument naming (ETH-PERP, ETH-USDC).
Tasks
Shared (derive_common_utils.py, auth, constants: both connectors)
- Update the base/WS URLs to
/v3for mainnet and testnet. Delete the unusedRPC_ENDPOINT/TESTNET_RPC_ENDPOINT/CHAIN_IDconstants, or replace them with the v3 values if they are used. - Compute the domain separator from
(name="Matching", version="1.0", chainId, verifyingContract)instead of hardcoding it, and check the result against the v3 constants above. Hardcoding it is how the separator went stale this time. - Rename the auth headers to
X-Derive*. The WSpublic/loginparams become{wallet, timestamp (ms, JSON number), signature}. - Nonce: UTC nanoseconds, serialized as a string. This also fixes the current same-millisecond collision.
-
signature_expiry_sec: a bounded value (e.g. now + 1 h, configurable), not2**31-1. - Encode limit price, amount and max_fee at 1e-12 precision, and format the wire decimals from the signed e18 value.
-
max_fee: derive it per order instead of the hardcoded"1000". derive-ts uses3 × (2 × taker_fee_rate × max(index_price, limit_price) + base_fee). Handle error11023and cancel reasonsigned_max_fee_too_low. - Send a
User-Agentheader on REST requests. - Session keys: document the v3 scoped-key setup. The user registers a key with scope
trade:orderbook:spot(4),trade:orderbook:perp(5) ortrade:orderbook:all(3), plus off-chainaccount_info. Surface the errors14026(not found),14030(expired) and14031(unauthorized scope) clearly. Optionally callpublic/get_wallets_from_session_keyat startup to validate the config. - Error handling: map the v3 numeric codes instead of matching strings or using Binance codes:
11006does not exist,11007self-cross,11008post-only cross,11000insufficient funds,11017/11018nonce,-32000rate limit,9000–9002retryable. - Rate limits: replace the hardcoded 5/s and 500/s tiers with values from
public/getRateLimits(matching / non-matching / per-endpoint), or at least check the tiers against it. - Use
private/order_debugin a manual testnet check and add the derive-ts golden vectors as unit tests for signing. - Remove the unused
eip712-structsfromsetup/pip_packages.txt.
Spot (connector/exchange/derive)
-
get_all_instruments(instrument_type: "erc20"): handle the new{instruments, pagination}response, loop over pages, and useis_active,maker_fee_rate,taker_fee_rate,base_fee,maximum_amount. - Parse the slim
get_tickerformat (b/B/a/A/M/I) everywhere it is used for last price, mid price and the rate source. Considerpublic/get_tickersfor bulk price fetches inDeriveRateSource. - Trading fees: take them from instrument
maker_fee_rate/taker_fee_ratein_update_trading_fees. The current defaults of0.01/0.03are 1% / 3%, which is a units bug. - Balances:
private/get_collaterals(orget_subaccount). Compute available vs total properly; today available = total. Optionally subscribe to{subaccount_id}.balances. - Order status: poll with
get_open_orders+get_order_historyin place of the removedget_orders. Map the new statusesexpired,untriggeredandalgo_active, and usecancel_reasonfor failure messages. -
LIMIT_MAKER→time_in_force: "post_only". Today it is sent as plaingtc. - Round prices to the instrument
tick_size, not to 4/5 significant figures. - Trade updates: use
liquidity_rolefor maker/taker fee attribution. - Optional:
private/replace,cancel_by_label,cancel_all,private/set_cancel_on_disconnect.
Perp (connector/derivative/derive_perpetual)
- Everything in the spot section that applies (instruments with
instrument_type: "perp", slim ticker, fees, order status, post-only, tick size). - Funding info: read
f(funding rate),I(index) andM(mark) from the slim ticker and fromticker_slim.{inst}.1000. Useperp_details.max_rate_per_hour/min_rate_per_hour. Check whether funding is still paid hourly instead of assuming(now//3600+1)*3600. - Funding payments: check the
private/get_funding_historyschema in v3.public/get_funding_rate_historyis also available. - Positions: there is no positions WS channel in v3, so poll
private/get_positions. Mapentry_pricefrom the response's average entry price field; today it is set toindex_price, which is wrong. - Leverage: expose the max leverage from
perp_details.srm_perp_margin_requirements.max_leverage. Derive is cross-margined per subaccount, soset_leveragestays a no-op but should say so in its return message. - Subaccount risk universe (FALLBACK/PRIME/HYPE/ALTCOIN/RWA): the instrument list can be filtered with
risk_universe_id. Decide whether to add it as a config option or derive it from the subaccount. -
reduce_only: set it fromPositionAction.CLOSEinstead of always sendingFalse. Handle11024/11025. - Optional: native trigger orders (
trigger_type: stoploss|takeprofit) for executor stop-loss / take-profit.
Existing bugs to fix during the rewrite
These were found by reading the current code. Most are in both connectors unless marked.
- Testnet signs with the mainnet
TRADE_MODULE_ADDRESS. v3 uses one address on every network, so this goes away once the constants are updated. - Perp:
position_side == "LONG"compares an enum to a string, so every fill is recorded asCLOSE(derive_perpetual_derivative.py~551, ~698, ~893). - Perp:
_process_update_positionslooks upself._trading_ruleswith the exchange symbol (ETH-PERP), which raises a KeyError that is swallowed, so WS position updates never apply. It also passes an invalid second argument toDecimal(asset.get("amount"), 0), multiplies the amount by the amount precision, and callsset_leveragewith the exchange symbol. - Perp:
_all_trade_updates_for_orderreturnsNone. - Perp: the perp→HB pair mapping hardcodes the
USDCquote (replace("USDC","PERP")). Use the instrumentquote_currency. - Perp: MARKET orders are priced at the plain mid with no slippage buffer (spot uses ±5%).
- Spot: the
trader/market_makerrate-limit branches are inverted (derive_exchange.py~480). - Spot:
_place_cancelsends the HB trading pair asinstrument_namewithout mapping it to the exchange symbol. -
_update_trade_history: on request failure,all_fills_responsestays[]and is then indexed like a dict. -
_update_balanceshas a bareraiseoutside anyexcept. -
DeriveRateSource.get_pricesonly fills results whenquote_tokenis given (an indentation bug). - Remove the stray Cython stubs in
derive_perpetual/(dummy.cpp,dummy.pyx,dummy.pxd,dummy.cpython-313-darwin.so) and dead constants (HBOT_ORDER_ID_PREFIX,ORDER_STATUS_TYPE, …).
Tests & docs
- Update the fixtures in
test/hummingbot/connector/exchange/derive/,test/hummingbot/connector/derivative/derive_perpetual/,test/hummingbot/connector/other/test_derive_common_utils.pyandtest/hummingbot/core/rate_oracle/sources/test_derive_rate_source.pyto the v3 response shapes. - Signing unit tests against the derive-ts golden vectors.
- End-to-end test on the Sepolia testnet: place, cancel and fill orders for spot and perp, check balances, and for perp check positions and funding.
- Update the connector docs: new session-key setup with scopes, account creation via L1 deposit (v3 has no
create_subaccount), and testnet on Sepolia.
Open questions / blockers
- Mainnet settlement contracts are not published yet. Both SDKs have zero-address placeholders; only Sepolia contracts are live. Trade signing doesn't need them, but mainnet availability should be confirmed before release.
- Will the v2 API (
api.lyra.finance) be sunset, and when? Existing users need a migration note: new session key, and possibly a new subaccount after moving funds to L1. - Confirm the funding interval and the
get_funding_history/get_positionsresponse fields against the live v3 API. The SDK specs are generated and may lag behind.
Source: hummingbot/hummingbot