#8489·hummingbot

Upgrade Derive spot & perpetual connectors to Derive v3 API

Author: fengtalityCreated Sep 29, 2026Updated Sep 29, 2026
Labelsenhancementderive

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:

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 /v3 for mainnet and testnet. Delete the unused RPC_ENDPOINT / TESTNET_RPC_ENDPOINT / CHAIN_ID constants, 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 WS public/login params 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), not 2**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 uses 3 × (2 × taker_fee_rate × max(index_price, limit_price) + base_fee). Handle error 11023 and cancel reason signed_max_fee_too_low.
  • Send a User-Agent header 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) or trade:orderbook:all (3), plus off-chain account_info. Surface the errors 14026 (not found), 14030 (expired) and 14031 (unauthorized scope) clearly. Optionally call public/get_wallets_from_session_key at startup to validate the config.
  • Error handling: map the v3 numeric codes instead of matching strings or using Binance codes: 11006 does not exist, 11007 self-cross, 11008 post-only cross, 11000 insufficient funds, 11017/11018 nonce, -32000 rate limit, 9000–9002 retryable.
  • 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_debug in a manual testnet check and add the derive-ts golden vectors as unit tests for signing.
  • Remove the unused eip712-structs from setup/pip_packages.txt.

Spot (connector/exchange/derive)

  • get_all_instruments (instrument_type: "erc20"): handle the new {instruments, pagination} response, loop over pages, and use is_active, maker_fee_rate, taker_fee_rate, base_fee, maximum_amount.
  • Parse the slim get_ticker format (b/B/a/A/M/I) everywhere it is used for last price, mid price and the rate source. Consider public/get_tickers for bulk price fetches in DeriveRateSource.
  • Trading fees: take them from instrument maker_fee_rate / taker_fee_rate in _update_trading_fees. The current defaults of 0.01 / 0.03 are 1% / 3%, which is a units bug.
  • Balances: private/get_collaterals (or get_subaccount). Compute available vs total properly; today available = total. Optionally subscribe to {subaccount_id}.balances.
  • Order status: poll with get_open_orders + get_order_history in place of the removed get_orders. Map the new statuses expired, untriggered and algo_active, and use cancel_reason for failure messages.
  • LIMIT_MAKER → time_in_force: "post_only". Today it is sent as plain gtc.
  • Round prices to the instrument tick_size, not to 4/5 significant figures.
  • Trade updates: use liquidity_role for 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) and M (mark) from the slim ticker and from ticker_slim.{inst}.1000. Use perp_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_history schema in v3. public/get_funding_rate_history is also available.
  • Positions: there is no positions WS channel in v3, so poll private/get_positions. Map entry_price from the response's average entry price field; today it is set to index_price, which is wrong.
  • Leverage: expose the max leverage from perp_details.srm_perp_margin_requirements.max_leverage. Derive is cross-margined per subaccount, so set_leverage stays 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 from PositionAction.CLOSE instead of always sending False. Handle 11024/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 as CLOSE (derive_perpetual_derivative.py ~551, ~698, ~893).
  • Perp: _process_update_positions looks up self._trading_rules with 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 to Decimal(asset.get("amount"), 0), multiplies the amount by the amount precision, and calls set_leverage with the exchange symbol.
  • Perp: _all_trade_updates_for_order returns None.
  • Perp: the perp→HB pair mapping hardcodes the USDC quote (replace("USDC","PERP")). Use the instrument quote_currency.
  • Perp: MARKET orders are priced at the plain mid with no slippage buffer (spot uses ±5%).
  • Spot: the trader / market_maker rate-limit branches are inverted (derive_exchange.py ~480).
  • Spot: _place_cancel sends the HB trading pair as instrument_name without mapping it to the exchange symbol.
  • _update_trade_history: on request failure, all_fills_response stays [] and is then indexed like a dict.
  • _update_balances has a bare raise outside any except.
  • DeriveRateSource.get_prices only fills results when quote_token is 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.py and test/hummingbot/core/rate_oracle/sources/test_derive_rate_source.py to 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_positions response fields against the live v3 API. The SDK specs are generated and may lag behind.