# Grvt API — signing: EIP-712 types, field mappings, the signing walkthrough and signing test cases Generated from contract.json (contract 0.1.0). Pages are separated by `=====` lines; each starts with its path. Links are site paths: fetch them from the host that served this file. ===== index.md # Overview Grvt is a crypto derivatives exchange. Its API lets you read market data, trade and move funds, with an SDK (Python, TypeScript, Go or Rust) or with plain HTTP and WebSocket calls. > [!WARNING] > **Preview.** The SDKs are in preview: any 0.x release can change them. The HTTP and WebSocket API is not > affected. ## Start here To place your first order on testnet (the test exchange, with free funds): 1. Install the SDK from your SDK's page ([Python](/sdks/python.md), [TypeScript](/sdks/typescript.md), [Go](/sdks/go.md), [Rust](/sdks/rust.md)), then run the [Quickstart](/guides/quickstart.md): one example reads market data, then one places and cancels an order. 2. Back on your SDK's page: create a client, then place, track and cancel an order. 3. [Errors and retries](/guides/errors-and-retries.md): what to do when a call fails, above all when you don't know whether an order was placed. Read these when you need them: [Environments](/guides/environments.md) (testnet or production), [Authentication](/guides/authentication.md), [Accounts and permissions](/guides/accounts.md) and [Rate limits](/guides/rate-limits.md). **Advanced:** [WebSocket](/guides/websocket.md) protocol details, [Recovery recipes](/guides/recovery.md), [Signing](/guides/signing.md) by hand, and the [C++ signing core and reference](/sdks/cpp.md): C++ has no client, so your app handles networking, sessions, streams and recovery itself. **Topics:** [Strategies](/guides/strategies.md), [Stable funding perps (SFP)](/guides/stable-perps.md), [Builders](/guides/builders.md), [Deposits and withdrawals](/guides/deposits-and-withdrawals.md) and [Referrals](/guides/referrals.md). Other ways in: - Writing code with an AI agent: give it [Notes for coding agents](/AGENTS.md) and [llms.txt](/llms.txt). - Looking for a call: [All calls](/reference/index.md) lists every RPC and stream. - Trading several exchanges through one library: [CCXT](https://docs.ccxt.com/#/exchanges/grvt) supports Grvt. - Questions about your account or the Grvt web app: the [Help Center](https://help.grvt.io/en/). ## Glossary | Term | What it is | |---|---| | Main account | Your account on Grvt, identified by a `0x` address (`main_account_id`). Deposits arrive here and withdrawals leave from here; it does not trade. The Grvt web app calls it the **Funding Account**, and some calls say "funding account". | | Sub-account | A trading account under your main account, identified by a number, the sub-account ID (`sub_account_id`). Orders, positions and margin live here. The Grvt web app calls it a **Trading Account**. Move funds between the main account and its sub-accounts with [transfer](/reference/rpc/transfer.md). | | API key | Logs you in: exchanged for a session ([Authentication](/guides/authentication.md)). | | Signing key | Signs orders, transfers and withdrawals and never leaves your machine ([Two keys, two jobs](/guides/authentication.md#two-keys-two-jobs)). | | Session | The `gravity` cookie and `X-Grvt-Account-Id` header a login returns. Every call to the trading host sends them. | ## How the API is laid out | Part | Host | What it does | |---|---|---| | Market data | `market-data.` | Instruments, tickers, order books, trades, candles. Public, no login. | | Trading | `trades.` | Orders, positions, fills, accounts, transfers. Needs a session. | | Edge | `edge.` | Login (API key or wallet signature). | `` is `testnet.grvt.io` or `grvt.io` ([Environments](/guides/environments.md)). The market data and trading hosts speak the same two protocols: - **HTTP**: `POST /full/v1/` with a JSON body. The response body is the result object. - **WebSocket**: JSON-RPC 2.0 on `/ws/full`. Every RPC works here too (`method: "v1/"`), and streams are subscribed with `method: "subscribe"`. Writes that move money or create orders carry an **EIP-712 signature** made with your signing key. The SDKs sign for you; [Signing](/guides/signing.md) explains the bytes if you sign yourself. ## Contract and signing test cases The reference pages and the SDKs are generated from the same API contract ([contract.json](/downloads/contract.json)), so they agree on names and types. [signing.json](/downloads/signing.json) holds signing test cases to check your own signing code against. ===== guides/environments.md # Environments Grvt has two environments: testnet, with free test funds, and production, with real funds. Test on testnet first. Each has its own accounts, API keys and balances. On this site, the API environment picker appears only on pages it changes. It switches the URLs on those pages, and the generated code samples on reference pages, and stays set as you move between them. Every other example is written for testnet. For production, use the production values in [Pick an environment](/guides/environments.md#pick-an-environment). Tutorials and live tools always use testnet. ## Pick an environment - **With an SDK:** pass the environment name when you create the client. Production is `"prod"`. - **Without an SDK:** set `GRVT_DOMAIN` to `testnet.grvt.io` or `grvt.io`. The raw Markdown examples use it. | Environment | `GRVT_DOMAIN` | Chain ID | Ethereum chain ID | |---|---|---|---| | Testnet | `testnet.grvt.io` | 326 | 11155111 (Sepolia) | | Production | `grvt.io` | 325 | 1 (Ethereum mainnet) | The chain ID is Grvt's own chain, used in every signature. The Ethereum chain ID is the network Grvt settles to; you need it only for wallet transactions on Ethereum itself. | SDK | Testnet | Production | By name (e.g. from `GRVT_ENV`) | |---|---|---|---| | Python | `Grvt(env="testnet")` | `Grvt(env="prod")` | `Grvt(env=os.environ["GRVT_ENV"])` | | TypeScript | `new Grvt({ env: "testnet" })` | `new Grvt({ env: "prod" })` | `new Grvt({ env: process.env.GRVT_ENV! })` | | Go | `grvt.Config{Env: grvt.Testnet()}` | `grvt.Config{Env: grvt.Prod()}` | `grvt.EnvironmentNamed(os.Getenv("GRVT_ENV"))` | | Rust | `Config::testnet()` | `Config::prod()` | `Config::named(&std::env::var("GRVT_ENV")?)?` | **Watch out:** the chain ID is part of every signature, so a signature made for testnet is not valid on production. In a request, `signature.chain_id` `"0"` means "this environment's chain ID". ## Hosts ```sh export GRVT_DOMAIN=testnet.grvt.io ``` | Service | URL | |---|---| | Market data (HTTP) | `https://market-data.$GRVT_DOMAIN` | | Market data (WebSocket) | `wss://market-data.$GRVT_DOMAIN/ws/full` | | Trading (HTTP) | `https://trades.$GRVT_DOMAIN` | | Trading (WebSocket) | `wss://trades.$GRVT_DOMAIN/ws/full` | | Edge (login) | `https://edge.$GRVT_DOMAIN` | | Server time | `GET https://market-data.$GRVT_DOMAIN/time` returns `{"server_time": }` | Production runs in AWS Tokyo (`ap-northeast-1`). Run latency-sensitive apps close to it. ## Encoding: full or lite Every gateway speaks two JSON encodings. They are the same API: same calls, routes, stream channels, values and enums. Only the field names differ. | | Full | Lite (SDK default) | |---|---|---| | HTTP | `/full/v1/` | `/lite/v1/` | | WebSocket | `/ws/full` | `/ws/lite` | | Field names | `{"instrument": "BTC_USDT_Perp"}` | `{"i": "BTC_USDT_Perp"}` | Lite messages are smaller: order book stream messages are about 30% smaller. HTTP responses are already gzipped, so lite saves much less there. - **With an SDK**, you get lite by default. Your code doesn't change: models, field names, errors and signing stay as on these pages, and the SDK renames fields on the wire. To see full names on the wire (for example while debugging raw messages), set the client's encoding to full (`encoding="full"` in Python, `encoding: "full"` in TypeScript, `Encoding: grvt.EncodingFull` in Go, `.encoding(Encoding::Full)` in Rust). - **By hand**, each field's lite name is fixed per type. The same short name can mean different things in different types (`s` is the stream in a stream message and the size in a book level), so rename per type. Errors are lite too: `{"c": 1003, "m": "...", "s": 400}` over HTTP. - **Don't mix encodings.** A full field name sent to a lite path is ignored, not rejected: the call runs without that field and can fail with an unrelated error such as `1004 Data Not Found`. - Login (edge) and `GET /time` have one encoding only. They are the same for full and lite clients. The reference pages show each field's lite name next to its full name (`lite i`), and their raw examples come in Full and Lite versions. ## Get testnet funds 1. Open [testnet.grvt.io/exchange/deposit](https://testnet.grvt.io/exchange/deposit). 2. Click **Mint testnet tokens** (USDT, USDC or GRVT). They go to your Funding Account (main account). 3. **Move** them to the Trading Account (sub-account) you trade from. **Watch out:** without funds, orders fail with `2080 InsufficientMargin`. ===== guides/signing.md # Signing Orders, transfers, withdrawals, wallet login, vault, position margin and qualified maker calls carry an [EIP-712](https://eips.ethereum.org/EIPS/eip-712) signature made with your [signing key](/guides/authentication.md#two-keys-two-jobs). **With an SDK**, the SDK signs for you: read only [Rules that cause most rejections](/guides/signing.md#rules-that-cause-most-rejections). **Advanced:** the rest of this page is for signing in another language. It walks through the `limit_order` test signing case from [signing.json](/downloads/signing.json): if your code prints the same digest and `r`/`s`/`v`, it is right. ## The steps To sign an order, transfer or withdrawal yourself with EIP-712: 1. **Start from the request JSON** you will send, with a `signature` object that has `signer`, `nonce`, `expiration` and `chain_id` but no `r`/`s`/`v` yet. 2. **Look up metadata**: per instrument, `instrument_hash` and `base_decimals`, plus `quote_decimals` for position margin calls ([get_instrument](/reference/rpc/get_instrument.md)); per currency, `id` and `balance_decimals` ([get_currency](/reference/rpc/get_currency.md)) for transfers, withdrawals and strategies; for vault calls, your main account (see [Main account](/guides/signing.md#main-account)). 3. **Map wire fields to the EIP-712 message** using the signed type's table ([Order](/reference/signing/Order.md)). Each field has one transform: | Transform | What it does | Example (`limit_order`) | |---|---|---| | `copy` | value as is; 64-bit ints arrive as strings | `sub_account_id` `"8289849667772468"` → `8289849667772468` | | `enumCode` | enum name → its integer ([Enums](/reference/enums.md)) | `GOOD_TILL_TIME` → `1` | | `assetKey` | instrument → `instrument_hash` as uint256 | `BTC_USDT_Perp` → `0x030501` = `197889` | | `scaled` | decimal string × 10^decimals, exact | size `"0.01"` × 10^9 → `10000000`; price `"60000"` × 10^9 → `60000000000000` | | `sig.nonce`, `sig.expiration` | copied from the signature object | `1001`, `4102444800000000000` (unix **ns**; the SDKs use now + 1 day) | | `sig.chainId` | domain chain ID; `"0"` = the environment's | `326` (testnet) | 4. **Hash**: `digest = keccak256(0x19 0x01 ‖ domainSeparator ‖ structHash)`, with domain `{name: "GRVT Exchange", version: "0", chainId}` (no `verifyingContract`). 5. **Sign** the digest with secp256k1, keeping `s` in the lower half of the curve order ("low-s"), and write into the signature object: `r` and `s` as `0x` + 64 hex chars, `v` as `27` or `28`. ## The code Runnable as is (`pip install coincurve pycryptodome`). It prints the intermediate values and checks them against the signing case: [Download this example](/downloads/examples/python/examples/manual_signing.py) ```python from decimal import Decimal from coincurve import PrivateKey from Crypto.Hash import keccak def keccak256(data: bytes) -> bytes: return keccak.new(digest_bits=256, data=data).digest() def word(n: int) -> bytes: """One EIP-712 32-byte word. Negative ints are two's complement.""" return (n % 2**256).to_bytes(32, "big") def scaled(value: str, decimals: int) -> int: """Decimal string -> integer. More fractional digits than `decimals` is an error, never rounded.""" n = Decimal(value).scaleb(decimals) if n != n.to_integral_value(): raise ValueError(f"{value} has more than {decimals} decimals") return int(n) # Step 1: the request you want to send (signature without r, s, v yet). request = { "order": { "sub_account_id": "8289849667772468", "is_market": False, "time_in_force": "GOOD_TILL_TIME", "post_only": True, "reduce_only": False, "legs": [{"instrument": "BTC_USDT_Perp", "size": "0.01", "limit_price": "60000", "is_buying_asset": True}], # expiration: unix nanoseconds. The SDKs use now + 1 day (at most 30 days; 180 for take-profit and # stop-loss orders); this signing test case uses 2100-01-01 so its digest never changes. "signature": { "signer": "0x1267c6181aee40f5ddbd70c56ecf4613117326b5", "expiration": "4102444800000000000", "nonce": 1001, "chain_id": "326", }, "metadata": {"client_order_id": "1001"}, } } # Step 2: instrument metadata, from get_instrument / get_all_instruments. instruments = {"BTC_USDT_Perp": {"instrument_hash": "0x030501", "base_decimals": 9}} TIME_IN_FORCE = {"GOOD_TILL_TIME": 1, "ALL_OR_NONE": 2, "IMMEDIATE_OR_CANCEL": 3, "FILL_OR_KILL": 4} # Step 3: map wire fields to the EIP-712 message. o, sig = request["order"], request["order"]["signature"] legs = [ { "assetID": int(instruments[leg["instrument"]]["instrument_hash"], 16), "contractSize": scaled(leg["size"], instruments[leg["instrument"]]["base_decimals"]), "limitPrice": scaled(leg.get("limit_price", "0"), 9), "isBuyingContract": leg["is_buying_asset"], } for leg in o["legs"] ] message = { "subAccountID": int(o["sub_account_id"]), "isMarket": o.get("is_market", False), "timeInForce": TIME_IN_FORCE[o["time_in_force"]], "postOnly": o.get("post_only", False), "reduceOnly": o.get("reduce_only", False), "legs": legs, "nonce": sig["nonce"], "expiration": int(sig["expiration"]), } # Step 4: hash. structHash = keccak(typeHash || encoded fields); an array is the keccak of its element hashes. LEG_TYPE = b"OrderLeg(uint256 assetID,uint64 contractSize,uint64 limitPrice,bool isBuyingContract)" ORDER_TYPE = ( b"Order(uint64 subAccountID,bool isMarket,uint8 timeInForce,bool postOnly,bool reduceOnly," b"OrderLeg[] legs,uint32 nonce,int64 expiration)" ) + LEG_TYPE def leg_hash(leg: dict) -> bytes: return keccak256( keccak256(LEG_TYPE) + word(leg["assetID"]) + word(leg["contractSize"]) + word(leg["limitPrice"]) + word(leg["isBuyingContract"]) ) struct_hash = keccak256( keccak256(ORDER_TYPE) + word(message["subAccountID"]) + word(message["isMarket"]) + word(message["timeInForce"]) + word(message["postOnly"]) + word(message["reduceOnly"]) + keccak256(b"".join(leg_hash(leg) for leg in message["legs"])) + word(message["nonce"]) + word(message["expiration"]) ) chain_id = int(sig["chain_id"]) or 326 # "0" means the environment's chain ID domain_separator = keccak256( keccak256(b"EIP712Domain(string name,string version,uint256 chainId)") + keccak256(b"GRVT Exchange") + keccak256(b"0") + word(chain_id) ) digest = keccak256(b"\x19\x01" + domain_separator + struct_hash) print("domain_separator 0x" + domain_separator.hex()) print("struct_hash 0x" + struct_hash.hex()) print("digest 0x" + digest.hex()) # Step 5: sign the digest (secp256k1, low-s) and fill in r, s, v. key = PrivateKey(bytes.fromhex("bfe25ff07bd38cb3fbc28a2a296d41aabd68a78c929d257935906489fc9c6d89")) # public TEST key raw = key.sign_recoverable(digest, hasher=None) # 65 bytes: r || s || recovery id sig["r"] = "0x" + raw[:32].hex() sig["s"] = "0x" + raw[32:64].hex() sig["v"] = raw[64] + 27 print(sig) assert digest.hex() == "7f8fecb8997024f85a5a9a44730f79d2cef290688d6a022d8e98e95ccc1f98c9" assert sig["r"] == "0x62b6d0047530e701aa06d4b7de9dca76916219b8561424bd246a519bdc31bf7d" assert sig["s"] == "0x2447b83565fa6cac90c607e5c4a3f96cda386f92d7fb51f45dea12c2f8e09904" assert sig["v"] == 27 ``` Expected output: ```text domain_separator 0x1254f97f8495f704630a238cbcd898a4b8ab20d77bb93e17049d3445f4f81f16 struct_hash 0x0248f8af0c644bb95dfe45feed4897e787765ca0fb1bece6dd5e9e016feceee8 digest 0x7f8fecb8997024f85a5a9a44730f79d2cef290688d6a022d8e98e95ccc1f98c9 ``` The key is a published test key (`keccak256("GRVT SDK TEST KEY - PUBLIC - NEVER FUND")`). Never fund its address. ## Rules that cause most rejections - **Precision.** Reject a value with more fractional digits than its scale allows, before signing; don't round it. BTC has 9 base decimals, so size `"1.1234567891"` is an error (signing case `order_over_precision`). Check this yourself: today the exchange accepts such a value and drops the extra digits, so it acts on a different number than the one you meant. - **Expiration.** `expiration` is unix **nanoseconds**, at most 30 days ahead (take-profit and stop-loss orders may be accepted up to 180 days ahead). It is measured on the exchange's clock with no allowance for skew: one already past fails with `2001`, and one too far ahead is rejected with reason `EXCEED_MAX_SIGNATURE_EXPIRATION`. If your clock may drift, use the exchange's [server time](/guides/environments.md#hosts). On an order it is also the order's lifetime: an order still open at that time is cancelled with reject reason `EXPIRED`. The SDKs set it 24 hours ahead unless you set `signature.expiration` yourself, so give orders that should rest longer a later expiration. - **Units.** Prices always use 9 decimals. Sizes use the instrument's `base_decimals`. Transfer and withdrawal amounts use the currency's `balance_decimals`. Position margin amounts use the instrument's `quote_decimals`. Each signed type page gives the scale of every field. - **Negative values.** Signed fields (`int64`, `int32`) can be negative and are encoded as two's complement: `add_position_margin` with amount `"-100.25"` signs `-100250000` (signing case `remove_position_margin`). - **`r`, `s`, `v` format.** `r` and `s` are `0x` plus 64 hex characters each; `v` is 27 or 28. Keep the `0x`: without it the signature fails to verify, although error `2006`'s message says "without 0x prefix". - **Nonce.** A random uint32, new for each new instruction. An exact repeat of a signed transfer fails with `4007 ErrDuplicatedTransfer`. Orders are told apart by client order ID instead (next rule); what a repeated order does is in [Why not resend](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown). - **Client order ID.** `metadata.client_order_id` is not signed. Use any non-zero uint64 that none of the sub-account's open orders uses, trigger orders included (take-profit and stop-loss orders waiting for their price): `0` fails with `2011`, a duplicate with `2012`, and the sub-account's last client order ID again with `2013`. Use a new ID for each order: once an order closes, its ID is accepted again. A lookup by client order ID returns the open order with that ID or, if none is open, any closed order that used it, not necessarily the latest. - **ID ranges.** The Grvt web app picks IDs below 2^63. The SDKs make IDs from 2^63 up (2^63 plus Unix seconds × 2^31 plus a counter), so they never clash with the web app's and are unique within one process. Each process starts its counter at a random 31-bit value, so two processes on one sub-account rarely pick the same ID: in a given second, each pair of their orders has about a 1 in 2^31 (2 billion) chance of matching. If you pick your own and the web app also trades the sub-account, pick from 2^63 up too. If many processes trade the sub-account at once and even that chance is too much, give each process its own IDs. - **Chain ID.** Testnet 326, production 325; `"0"` means the environment's chain ID. Put the same value you signed with in the request. - **Signer address.** `signature.signer` is the address of the key that signed. That wallet must be allowed to trade for the sub-account. ## Builder fee orders When `order.builder` is set to a non-zero address, sign `OrderWithBuilderFee` instead of `Order`. It adds two fields between `legs` and `nonce`: ```text OrderWithBuilderFee(uint64 subAccountID,bool isMarket,uint8 timeInForce,bool postOnly,bool reduceOnly,OrderLeg[] legs,address builder,uint32 builderFee,uint32 nonce,int64 expiration)OrderLeg(uint256 assetID,uint64 contractSize,uint64 limitPrice,bool isBuyingContract) ``` - `builder`: the builder's address (`address` transform, 20 bytes, left-padded in the word). - `builderFee`: `builder_fee` is a **percentage** string; signed value = `builder_fee` × 10^4. `"0.001"` (0.001%) → `10`. Signing case `order_with_builder_fee`, digest `0x09b6c3c367b5641f38ab3750d2f5dc45325f3e46c15a3b6fe03e92b3ca7942af`. ## Main account **When:** you sign `VaultInvestV3`, `VaultRedeemV3` or `VaultBurnLpToken`. These sign `accountID`, which is not in the request: the server uses your session's main account. 1. Call [funding_account_summary](/reference/rpc/funding_account_summary.md) once and read `result.main_account_id`. 2. Sign that address as `accountID`. The SDKs do this for you on the first vault call. In C++, `needs_` reports that the call needs it, and your app passes it in. ## Other signed types | Type | Used by | Notes | |---|---|---| | [Transfer](/reference/signing/Transfer.md), [TransferV2](/reference/signing/TransferV2.md), [TransferV3](/reference/signing/TransferV3.md) | [transfer](/reference/rpc/transfer.md) | V2 when wallet types are set; V3 for currency ids above 255 | | [Withdrawal](/reference/signing/Withdrawal.md), [WithdrawalV2](/reference/signing/WithdrawalV2.md) | [withdrawal](/reference/rpc/withdrawal.md) | V2 for currency ids above 255 | | [WalletLogin](/reference/signing/WalletLogin.md) | [wallet login](/reference/rpc/login_wallet.md) | expiration at most 5 minutes ahead | | [VaultInvestV3](/reference/signing/VaultInvestV3.md) | [vault_invest](/reference/rpc/vault_invest.md) | signs your main account | | [VaultRedeemV3](/reference/signing/VaultRedeemV3.md) | [vault_redeem](/reference/rpc/vault_redeem.md) | signs your main account | | [VaultBurnLpToken](/reference/signing/VaultBurnLpToken.md) | [vault_burn_tokens](/reference/rpc/vault_burn_tokens.md) | signs your main account; `currency` is not signed | | [AddIsolatedPositionMargin](/reference/signing/AddIsolatedPositionMargin.md) | [add_position_margin](/reference/rpc/add_position_margin.md) | negative `amount` removes margin | | [SetSubAccountPositionMarginConfig](/reference/signing/SetSubAccountPositionMarginConfig.md) | [set_position_config](/reference/rpc/set_position_config.md) | | | [SetDeriskToMaintenanceMarginRatio](/reference/signing/SetDeriskToMaintenanceMarginRatio.md) | [set_derisk_mm_ratio](/reference/rpc/set_derisk_mm_ratio.md) | | Each type page lists its fields, type hash, where every field comes from, and its signing cases. The same data is under `signed` in [contract.json](/downloads/contract.json). ===== sdks/cpp.md # C++ signing core and reference > [!WARNING] > **Preview.** Any 0.x release can change the API. Pin the commit you build from. **Advanced.** The C++ signing core is for apps that already have their own networking and event loop. It signs requests and encodes them as JSON; your code does the rest. For a full client, use another SDK. | What you get | What you build yourself | |---|---| | Exact decimal values | HTTP and WebSocket clients | | EIP-712 encoding and hashing | Login, session renewal and the cancel-on-disconnect countdown | | An optional libsecp256k1 signer for private keys in the same process | Timers, streams and order books | | Executable reference examples | Recovery after lost answers and stream gaps | | | Loading metadata, choosing the environment, nonce and expiration | | | Business checks: tick size, minimum size, minimum notional | There is no client and no wrapper for each RPC or stream. ## Build the core **Not published as a package yet:** build it from source, from its public repository [grvt-signing-cpp](https://github.com/gravity-technologies/grvt-signing-cpp), and pin the commit you build from. 1. Install CMake 3.24+ and GCC or Clang with C++20 or newer, on Linux or macOS. MSVC isn't supported, because the core uses `__int128` arithmetic. 2. Clone, build and install: ```sh git clone https://github.com/gravity-technologies/grvt-signing-cpp cd grvt-signing-cpp cmake -S . -B build -DCMAKE_BUILD_TYPE=Release cmake --build build cmake --install build --prefix /opt/grvt ``` 3. Optional, for private keys in the same process: install libsecp256k1 with its recovery module (`apt install libsecp256k1-dev` or `brew install secp256k1`). Then configure with `-DGRVT_SIGNING_WITH_SECP256K1=ON`. The default build doesn't need it. 4. Link the package from your CMake project: ```cmake find_package(grvt_signing REQUIRED) target_link_libraries(app PRIVATE grvt::signing) # Also link grvt::signer when using the optional private-key signer. ``` 5. Optional: run `ctest --test-dir build --output-on-failure`. It checks the signing cases, the installed package (the digest path and the optional signer separately) and the reference. Test your own integration against [signing.json](/downloads/signing.json) too; an installed build has it at `share/grvt_signing/signing.json`. **Errors.** Every function that can fail returns `grvt::Result`: the value, or a `grvt::Error` with a `kind` (`signing`, `decode` or `config`) and a `message`. Encoding and signing failures are returned, not thrown. ## Run the reference **When:** you want to see the whole signing flow before writing your own transport. From the source directory, build with examples turned on and run `grvt_signing_reference`: ```sh cmake -S . -B build -DGRVT_SDK_BUILD_EXAMPLES=ON cmake --build build --target grvt_signing_reference ./build/grvt_signing_reference ``` The source below keeps signing separate from the transport, which your code supplies. It uses fixed inputs and made-up host data and makes no network calls, so it doesn't prove that login, networking or order recovery work against the exchange. [Download this example](/downloads/examples/cpp/examples/reference.cpp) ```cpp // Offline reference. Replace the print callback with your own HTTP transport. #include // Published conformance inputs. These are test values, never production credentials. #include "grvt/grvt.hpp" namespace reference { inline auto order() { grvt::models::OrderLeg leg("BTC_USDT_Perp", *grvt::Decimal::parse("0.01"), true); leg.limit_price = *grvt::Decimal::parse("60000"); grvt::models::OrderInput input(grvt::enums::TimeInForce::GOOD_TILL_TIME, std::vector{leg}); input.sub_account_id = 8289849667772468ULL; input.is_market = false; input.post_only = true; input.reduce_only = false; input.metadata.emplace(); input.metadata->client_order_id = (1ULL << 63) | 1001; // API client ID range input.signature.emplace(); input.signature->signer = "0x1267c6181aee40f5ddbd70c56ecf4613117326b5"; input.signature->nonce = 1001; input.signature->expiration = grvt::timestamp_from_ns(4102444800000000000LL); input.signature->chain_id = 326; return grvt::models::ApiCreateOrderRequestInput(std::move(input)); } inline grvt::SigningMetadata metadata() { grvt::SigningMetadata meta; meta.instruments["BTC_USDT_Perp"] = {"0x030501", 9, 6}; return meta; } inline constexpr auto test_key = "0xbfe25ff07bd38cb3fbc28a2a296d41aabd68a78c929d257935906489fc9c6d89"; } // namespace reference #ifdef GRVT_WITH_SIGNER #include "grvt/signer.hpp" #endif // The host owns HTTP, secrets, cookies and account state. Nothing is sent by this example. using HostPost = void (*)(std::string_view path, std::string_view cookie, std::string_view account_id, std::string_view body); void print_wire(std::string_view path, std::string_view cookie, std::string_view account_id, std::string_view body) { std::printf("POST %.*s\n", int(path.size()), path.data()); if (!cookie.empty()) std::printf("Cookie: %.*s\n", int(cookie.size()), cookie.data()); if (!account_id.empty()) std::printf("X-Grvt-Account-Id: %.*s\n", int(account_id.size()), account_id.data()); std::printf("%.*s\n", int(body.size()), body.data()); } int main() { HostPost post = &print_wire; // API-key login wire shape. Read Set-Cookie gravity and X-Grvt-Account-Id from the // real response in the host. Never print real keys or cookies in production logs. post("/auth/api_key/login", {}, {}, R"({"api_key":"REPLACE_IN_HOST"})"); auto order = reference::order(); auto meta = reference::metadata(); grvt::SignContext ctx; ctx.chain_id = 326; // caller selects the chain; the core has no environment lookup ctx.metadata = &meta; auto digest = grvt::signing::digest_order_create_order(order, ctx); if (!digest) return 1; std::printf("digest: %s\n", grvt::hex0x(digest->digest).c_str()); #ifdef GRVT_WITH_SIGNER auto signer = grvt::PrivateKeySigner::from_hex(reference::test_key); if (!signer) return 2; ctx.signer = &*signer; ctx.verify = &grvt::verify_signature; if (!grvt::signing::sign_order_create_order(order, ctx)) return 3; post("/full/v1/create_order", "gravity=HOST_COOKIE", "HOST_ACCOUNT_ID", grvt::encode(order)); #endif // If a write times out after sending, its result is unknown. Keep client_order_id // and reconcile with get_order/order history. An absent lookup does not prove that // the order was rejected. Keep the result unknown and never automatically resend. // A fresh nonce is not a retry guarantee. The host owns this policy and its storage. std::puts("unknown write: reconcile by client_order_id; absent lookup stays unknown; never automatically resend"); return 0; } ``` **Watch out:** don't submit its recorded request as a new order. It uses fixed test values, not a live nonce or expiration. ## Connect a live application **When:** you are ready to send real requests. Start on testnet. 1. Pick the [environment URLs and chain ID](/guides/environments.md) for one environment, and use them together. 2. Log in with your API key over HTTP ([Authentication](/guides/authentication.md#by-hand)). 3. Save the returned `gravity` cookie and `X-Grvt-Account-Id`. Send both on private requests and on the WebSocket upgrade. 4. Load current instrument and currency metadata from the API into a `grvt::SigningMetadata` (`instrument_hash`, `base_decimals` and `quote_decimals` per instrument; `id` and `balance_decimals` per currency; your `main_account` for vault calls), and point `SignContext::metadata` at it. `grvt::signing::needs_` says which entries a request needs. 5. Set these yourself, and use exact decimal text for every price, size and amount: - Chain ID: `SignContext::chain_id`. A request whose `signature.chain_id` is `"0"` (the environment's) is signed with it; a call fails with a `config` error if both are 0. - Nonce: a fresh uint32 from an OS secure random source, for each new signed action. - Expiration: a future Unix timestamp in nanoseconds, at most 30 days ahead (180 for take-profit and stop-loss orders) ([Expiration](/guides/signing.md#rules-that-cause-most-rejections)). - Client order ID: your own, saved before you send, so you can [look the order up](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown) if its response is lost. 6. Sign. Call `grvt::signing::digest_` to get a digest for an external signer, or `grvt::signing::sign_` with a signer. An order with `builder` set is signed as `OrderWithBuilderFee` ([Builder fee orders](/guides/signing.md#builder-fee-orders)). Bulk orders have separate functions to make the digests (`digests_order_bulk_orders`) and to attach the signatures (`attach_order_bulk_orders`). 7. Encode the signed request with `grvt::encode(request)`, which writes the wire JSON, and send it with your own HTTP or WebSocket client. Your app also checks stream sequence numbers, reconnects and recovers state ([WebSocket](/guides/websocket.md), [Errors and retries](/guides/errors-and-retries.md)). [Signing](/guides/signing.md) has the signing details. **Watch out:** - Read credentials from environment variables or your secret store. Keep signing keys out of request bodies and logs. - Turn off redirects, including during WebSocket handshakes. A followed redirect sends a second request, which can forward your credentials or replay a signed write. - Keep metadata, chain ID, nonce and expiration consistent with the environment and account you send to. The core doesn't load or choose any of them for you. - `attach_order_bulk_orders` requires `SignContext::verify`. Your callback must check that each digest and signature recover to the expected address: returning success without checking proves nothing about the signing key. The optional adapter provides `grvt::verify_signature` for this.
Guarantees and edge cases - Inside a `Signer` callback, `SigningRequest::typed_data()` gives you the typed data, for wallets that need it. Digest results and their copies don't keep the typed data. - Before your verifier runs, the core checks the signature shape, low-s ([Signing](/guides/signing.md#the-steps)) and the signer field. - The sign and digest functions only read the `SignContext`. Threads can share one while each signs its own request, if your `Signer` is safe to call from several threads at once (`PrivateKeySigner` is) and nothing changes the metadata meanwhile. - `digest_order_create_order`, and `sign_order_create_order` with `PrivateKeySigner`, allocate no memory after the first few calls when you reuse the same request object. Errors and `typed_data()` do allocate.
## What the core checks - It validates encoding inputs and the signing metadata it needs. - It rejects any value it can't represent exactly at the required scale. It never rounds. A valid digest doesn't mean the exchange will accept the order. ## Not supported yet - **A client.** The core has no HTTP, WebSocket, login, session renewal or recovery, on purpose: your application owns them, as the table at the top of this page lists. - **MSVC.** The core uses `__int128` arithmetic; build with GCC or Clang ([Build the core](/sdks/cpp.md#build-the-core)). ===== guides/builders.md # Builders A builder is a Grvt account, usually an app or a bot, that places orders for its users and earns its own fee on them. Use this page if you run such an app. How it fits together: - **Builder account**: your own Grvt main account. Builder fees are paid into it. - **Authorization**: each user signs once, naming your builder account and the highest builder fee they accept, one cap for futures (perpetuals included) and one for spot. - **Builder order**: an order with `builder` and `builder_fee` set. The user pays the builder fee on each fill, on top of the trading fee. The calls for orders and builder fees are under [Builders](/reference/index.md#builders) in the reference. Authorizing a builder has no SDK method yet: send it over HTTP as shown below. ## Authorize a builder **When:** a user connects your app for the first time, or you want to change their fee caps. One call, `POST /auth/builder/authorize` on the edge host, works in two modes. What you send picks the mode: | Mode | Use it when | The user signs | Response | |---|---|---|---| | **With an API key** | your app trades for the user with its own key | `AddAccountSignerWithBuilder` | `{"api_key": "..."}` | | **[Authorize only](/guides/builders.md#authorize-only)** | your app already has a key, or the user changes their caps | `AuthorizeBuilder` | `{}` | Sending `builder_api_key_signer` and `builder_api_key_permissions` picks the first mode; leaving both out picks the second. The steps below are for the first. 1. Get two main account IDs (`0x` addresses): the user's and your builder account's. [funding_account_summary](/reference/rpc/funding_account_summary.md) returns `main_account_id` for the account you are logged in to. 2. Choose the caps, `max_futures_fee_rate` and `max_spot_fee_rate`. Each is a **percentage** string with at most 4 decimals: `"0.1"` means 0.1%. 3. Generate a key pair in your app. Its address is the **builder signer**; it must not already be a signer on Grvt. 4. Choose the key's permissions on the user's main account: names joined with `&` in this order: `Admin`, `InternalTransfer`, `ExternalTransfer`, `Withdraw`, `VaultInvestor`, `Trade`. For example `"Trade"` or `"InternalTransfer&Trade"`. Ask only for what you need, usually `Trade`. 5. Have the user sign `AddAccountSignerWithBuilder` ([below](/guides/builders.md#the-signed-message)) with an admin wallet of their main account (Funding Admin). 6. Send it to the edge host. It needs no session: the signature authenticates it. ```sh export GRVT_DOMAIN=testnet.grvt.io curl -sS "https://edge.$GRVT_DOMAIN/auth/builder/authorize" \ -H "Content-Type: application/json" \ --data @- <<'EOF' { "main_account_id": "0x1111111111111111111111111111111111111111", "builder_account_id": "0x2222222222222222222222222222222222222222", "max_futures_fee_rate": "0.1", "max_spot_fee_rate": "0.05", "builder_api_key_signer": "0x4444444444444444444444444444444444444444", "builder_api_key_permissions": "Trade", "builder_api_key_label": "My trading app", "signature": { "signer": "0x3333333333333333333333333333333333333333", "r": "0x...", "s": "0x...", "v": 27, "expiration": "1767225600000000000", "nonce": 1001, "chain_id": "326" } } EOF ``` A success returns HTTP 200 and `{"api_key": "..."}`: an API key on the user's main account, tied to the builder signer. Log in with it ([Authentication](/guides/authentication.md)) and sign the user's orders with the builder signer's key. [Permissions](/guides/accounts.md#permissions) explains what each permission allows on a main account. [get_authorized_builders](/reference/rpc/get_authorized_builders.md), called on the user's session, lists your builder account with its caps. **Watch out:** - Grvt keeps only a hash of the API key, so this response is the only time you see it. Store it right away. - To change the caps, use [Authorize only](/guides/builders.md#authorize-only) with the new values; the first mode would add another API key. Authorizing again with the same caps fails with "the builder is already authorized for this main account". - Grvt sets a maximum for the caps. A cap above it, or a negative one, fails with "invalid builder fee rate". - Permission names out of order (`"Trade&Admin"`) or unknown names fail with HTTP 400. ### Authorize only **When:** your app already has a way to trade for the user, or the user changes the caps of a builder they authorized before. This mode only records your builder account and its caps on the user's main account. It creates no API key. 1. Get the two main account IDs and choose the caps, as in steps 1 and 2 above. 2. Have the user sign `AuthorizeBuilder` ([below](/guides/builders.md#the-signed-message)) with an admin wallet of their main account. 3. Send it to the same route, without the `builder_api_key_*` fields. ```sh export GRVT_DOMAIN=testnet.grvt.io curl -sS "https://edge.$GRVT_DOMAIN/auth/builder/authorize" \ -H "Content-Type: application/json" \ --data @- <<'EOF' { "main_account_id": "0x1111111111111111111111111111111111111111", "builder_account_id": "0x2222222222222222222222222222222222222222", "max_futures_fee_rate": "0.2", "max_spot_fee_rate": "0.05", "signature": { "signer": "0x3333333333333333333333333333333333333333", "r": "0x...", "s": "0x...", "v": 27, "expiration": "1767225600000000000", "nonce": 1002, "chain_id": "326" } } EOF ``` A success returns HTTP 200 and `{}`. The new caps apply to the user's next orders with your builder account. The cap, signature and same-caps errors are the same as in the first mode. ### The signed message The domain is the same as for every Grvt signature: `{name: "GRVT Exchange", version: "0", chainId}`, with the environment's chain ID (326 on testnet, 325 on production). [Signing](/guides/signing.md) walks through the hashing. With an API key, the user signs: ```text AddAccountSignerWithBuilder(address accountID,address signer,string permissions,address builderAccountID,uint32 maxFutureFeeRate,uint32 maxSpotFeeRate,uint32 nonce,int64 expiration) ``` | Field | From the request | |---|---| | `accountID` | `main_account_id` | | `signer` | `builder_api_key_signer` | | `permissions` | `builder_api_key_permissions`, the same string (an EIP-712 `string`: its keccak256 hash is encoded) | | `builderAccountID` | `builder_account_id` | | `maxFutureFeeRate` | `max_futures_fee_rate` × 10^4: `"0.1"` → `1000`, `"0.001"` → `10` | | `maxSpotFeeRate` | `max_spot_fee_rate` × 10^4 | | `nonce` | `signature.nonce`, a random uint32 | | `expiration` | `signature.expiration`, unix nanoseconds, in the future and at most 30 days ahead | Authorize only, the user signs: ```text AuthorizeBuilder(address mainAccountID,address builderAccountID,uint32 maxFutureFeeRate,uint32 maxSpotFeeRate,uint32 nonce,int64 expiration) ``` The fields come from the request the same way: `mainAccountID` is `main_account_id`, and the rest match the table above.
Errors Errors come back with an HTTP status and a message: | Status | Message | Fix | |---|---|---| | 400 | `invalid main account ID` / `invalid builder account ID` | Use existing main account IDs (`0x` addresses). | | 400 | `builder account ID cannot be the same as main account ID` | Use a separate builder account. | | 400 | `invalid signature` / `signature has expired` / `signature expiration exceeds the maximum of 30 days` | Check the signed fields, the chain ID and `expiration`. | | 400 | `signature nonce has already been used` | Sign again with a new nonce. | | 400 | `the main account requires more signatures than provided` | The account needs approvals from several admins ([Approvals by several admins](/guides/accounts.md#approvals-by-several-admins)). | | 400 | `the signer wallet is already in use; please choose a different one` | Generate a new builder signer. | | 400 | `API key label cannot be empty when permissions or signer are provided` | Set `builder_api_key_label`. | | 401 | `the signer in the signature is not authorized to represent the main account` | Sign with an admin wallet of the user's main account. |
## Place builder orders **When:** your app places an order for a user who has authorized your builder account. 1. Set `order.builder` to your builder main account ID. 2. Set `order.builder_fee` to your fee for this order, a percentage string such as `"0.05"` (0.05%). It must be at most the user's cap for this market: the futures cap for perpetuals, the spot cap for spot swaps. 3. Sign and send the order as usual. The SDKs sign `OrderWithBuilderFee` when `builder` is set; by hand, see [Builder fee orders](/guides/signing.md#builder-fee-orders). The builder fee is the order's builder fee rate times the trade's notional value, in the quote currency. It is charged on each fill and paid into your builder account. Spot buys carry no builder fee; spot sells do. **Watch out:** these errors mean the order was rejected, not placed: | Code | Name | Cause | |---|---|---| | `7504` | `ErrBuilderNotAuthorized` | The user hasn't authorized this builder account. | | `7505` | `ErrBuilderFeeExceedsAuthorizationLimit` | `builder_fee` is above the user's cap. | | `7506` | `ErrBuilderMissing` | `builder_fee` is set without `builder`. | | `7501` | `ErrBuilderFeeNegative` | `builder_fee` is negative. | ## See your builder fees - On the user's side, each fill has `builder`, `builder_fee_rate` and `builder_fee` (the amount paid, in the quote currency): [fill_history](/reference/rpc/fill_history.md). - On your side, [builder_fill_history](/reference/rpc/builder_fill_history.md) lists the fills where your account was the builder. Call it with a session for your builder account; other accounts get an empty list. ===== guides/deposits-and-withdrawals.md # Deposits and withdrawals Use this page to move funds between Grvt and wallets on other chains from code: - **Deposits:** each main account has a deposit address on every supported chain. Tokens sent there are bridged to Grvt and credited to your main account. - **Withdrawals to other chains** go through Grvt's bridge partner: get a quote, sign a transfer, then track the payout. - **Withdrawals to Ethereum** use the [withdrawal](/reference/rpc/withdrawal.md) call instead, which the SDKs have. The deposit address and bridge calls are on the edge host and have no SDK methods yet. Send them over HTTP as shown here. ## Authenticate edge calls - **Deposit addresses:** send your API key in an `X-API-Key` header. A session cookie from a login works too. - **Bridge withdrawals:** send the session cookie, `Cookie: gravity=...`, from a login ([Authentication](/guides/authentication.md#by-hand)). The API key header alone gets HTTP 401 (`err_auth_user_not_logged_in`). Errors come back with an HTTP status and a body like `{"code": "err_withdrawal_quote_expired", "message": "withdrawal quote has expired", "params": {}}`. Match on `code`. ## Get your deposit addresses ```sh export GRVT_DOMAIN=testnet.grvt.io curl -sS "https://edge.$GRVT_DOMAIN/api/v1/deposit/addresses" \ -H "X-API-Key: $GRVT_API_KEY" ``` The response lists one entry per chain: ```json nocheck { "chains": [ { "chain": "BASE_SEPOLIA", "chain_id": "84532", "deposit_address": "0x...", "supported_tokens": [{"name": "USDT", "contract_address": "0x..."}] }, { "chain": "SOLANA_TEST", "chain_id": "solana_test", "deposit_address": "", "supported_tokens": [{"name": "USDT", "contract_address": "..."}] } ] } ``` | Field | Meaning | |---|---| | `chain` | The chain's name. Pass it back exactly as returned. | | `chain_id` | The EVM chain ID, or a name for chains without one, such as `"solana"` and `"tron"` (`"solana_test"` and `"tron_test"` on testnet). | | `deposit_address` | Send tokens here. Empty when the address doesn't exist yet ([Create an address](/guides/deposits-and-withdrawals.md#create-an-address-on-another-chain)). | | `supported_tokens` | The tokens you can deposit on this chain, with their contract addresses. | | `token_out` | Present only when deposits are credited as a different token, which it names. | **Watch out:** - The chains and tokens differ by environment and change over time. Read them from this call; don't hard-code them. - A `contract_address` can be empty when Grvt couldn't look it up. Call again before you send that token. - A new account fails with `err_chain_account_not_setup` ("funding account is not set up") until its main account is set up. ### Create an address on another chain **When:** a chain is listed with an empty `deposit_address`. ```sh curl -sS "https://edge.$GRVT_DOMAIN/api/v1/deposit/generate-address" \ -H "X-API-Key: $GRVT_API_KEY" \ -H "Content-Type: application/json" \ --data '{"chain": "SOLANA_TEST"}' ``` It returns one entry in the same shape, with the new `deposit_address`. The chain name is not case-sensitive. An unknown chain fails with `err_deposit_chain_not_supported`, and a chain that isn't open to your account with `err_deposit_chain_not_available`. ### Track deposits A bridged deposit arrives in your main account as a transfer with `transfer_type` `NON_NATIVE_BRIDGE_DEPOSIT`. Find it with [transfer_history](/reference/rpc/transfer_history.md). ## Withdraw to another chain **When:** you send USDT from your main account to a wallet on another chain. Before you start: - The destination address must be in your main account's withdrawal address book. - The signing wallet needs the **External Transfer** (or Admin) permission on the main account ([Permissions](/guides/accounts.md#permissions)). The withdrawal is a transfer to the bridge partner's Grvt account. - The funds must be in the main account. Move them from a sub-account with [transfer](/reference/rpc/transfer.md) first. 1. Read the routes and the bridge partner's account: ```sh curl -sS "https://edge.$GRVT_DOMAIN/api/v1/bridge/withdrawal-info" -H "Cookie: gravity=$GRVT_COOKIE" ``` ```json nocheck { "provider": "RHINO", "funding_address": "0x...", "route": { "USDT": [{"chain": "BASE_SEPOLIA", "chain_id": "84532", "chain_type": "evm", "tokens_out": ["USDT"]}], "USDC": [] } } ``` `route` maps each token you can send (`token_in`) to the chains and tokens it can arrive as. Only USDT can be withdrawn this way today. 2. Get a quote. Nothing moves yet. ```sh curl -sS "https://edge.$GRVT_DOMAIN/api/v1/bridge/withdrawal-quote" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "Content-Type: application/json" \ --data '{"to_address": "0x...", "chain": "BASE_SEPOLIA", "token_in": "USDT", "token_out": "USDT", "amount": "100"}' ``` The reply has `quote_id`, `pay_amount` (what leaves your main account), `receive_amount` (what arrives), `fee` (in `token_in`), `fee_usd`, `speed` and `expires_at`. All amounts are decimal strings. 3. Sign a [Transfer](/reference/signing/Transfer.md) from your main account to the bridge partner, with the quote's amount: | Field | Value | |---|---| | `fromAccount` | your main account ID | | `fromSubAccount` | `0` | | `toAccount` | `funding_address` from step 1 | | `toSubAccount` | `0` | | `tokenCurrency` | the `id` of USDT from [get_currency](/reference/rpc/get_currency.md) | | `numTokens` | `pay_amount` × 10^`balance_decimals` of USDT | | `nonce`, `expiration` | a random uint32; unix nanoseconds, at most 30 days ahead | [Signing](/guides/signing.md) explains the domain and the hashing. 4. Send the quote ID and the signature before `expires_at`: ```sh curl -sS "https://edge.$GRVT_DOMAIN/api/v1/bridge/withdraw" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "Content-Type: application/json" \ --data @- <<'EOF' { "quote_id": "...", "signature": {"signer": "0x...", "r": "0x...", "s": "0x...", "v": 28, "expiration": "1767225600000000000", "nonce": 1002, "chain_id": 326} } EOF ``` Here `chain_id` is a number, not a string as in other signed requests. You can leave it out: Grvt then uses its own chain ID. HTTP 202 means the transfer was sent: `{"quote_id", "tx_id", "state": "SUBMITTED", "receive_amount", "fee", "fee_usd"}`. 5. Check progress until the state is final: ```sh curl -sS "https://edge.$GRVT_DOMAIN/api/v1/bridge/withdrawal-status?quote_id=$QUOTE_ID" \ -H "Cookie: gravity=$GRVT_COOKIE" ``` The reply has `state`, `chain`, `token_out`, `receive_amount` and, once paid, `withdraw_tx_hash` on the destination chain. | State | Meaning | |---|---| | `CREATED` | Quoted, not sent. | | `SUBMITTED` | Sent to the bridge partner; payout not started. | | `SENDING` | The bridge partner is paying out. | | `COMPLETED` | Paid out. Final. | | `REFUNDED` | Not paid out; the funds were returned. Final. | | `FAILED` | Not paid out. Final. | **Watch out:** - If step 4 times out or returns a 5xx, the withdrawal may still go through. Check the status, or send the same request again with the same signature: if it went through, you get the first reply back. A quote can be sent only once, so retrying it can't withdraw twice. - Don't get a new quote and sign again until the status of the first one is final, or you may withdraw twice. - A quote past `expires_at` fails with `err_withdrawal_quote_expired` (HTTP 410). Get a new one.
Errors | Status | Code | Cause | |---|---|---| | 404 | `err_withdrawal_address_not_in_address_book` | `to_address` isn't in the withdrawal address book for this chain type. | | 422 | `err_withdrawal_token_not_supported` | `token_in` isn't USDT. | | 422 | `err_withdrawal_route_not_supported` | This chain and `token_out` aren't a route right now. | | 422 | `err_withdrawal_amount_below_fee` | The amount doesn't cover the fee. | | 422 | `err_withdrawal_limit_exceeded` | A daily limit or the bridge's available funds would be exceeded. | | 422 | `err_withdrawal_insufficient_balance` | The main account doesn't hold `pay_amount`. | | 400 | `err_withdrawal_signature_invalid` | The signature doesn't match the quote, or has expired. | | 403 | `err_withdrawal_address_rejected` | The destination failed screening or can't be used. | | 403 | `err_user_has_insufficient_permissions` | The signing wallet lacks External Transfer. | | 409 | `err_withdrawal_already_executed` | This quote was already sent. | | 410 | `err_withdrawal_quote_expired` | Get a new quote. | | 404 | `err_withdrawal_not_found` | No withdrawal with this `quote_id` for your account. |
===== reference/signing/AddIsolatedPositionMargin.md # AddIsolatedPositionMargin (signed message) Signed by [`add_position_margin`](/reference/rpc/add_position_margin.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text AddIsolatedPositionMargin(uint64 subAccountID,uint256 asset,int64 amount,uint32 nonce,int64 expiration) ``` Type hash `0xb6e7c8dc8d7d9fb71fb62ec71807f9a293291545d20d0123cba70b443af79010`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `subAccountID` | `uint64` | `sub_account_id` | `copy` | | `asset` | `uint256` | `instrument` | `assetKey`: the instrument's `instrument_hash` as uint256 | | `amount` | `int64` | `amount` | `scaled`: decimal × 10^`quote_decimals` of the instrument | | `nonce` | `uint32` | `signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `signature.expiration` | `sig.expiration` | | domain `chainId` | `uint256` | `signature.chain_id` | `sig.chainId` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `add_position_margin` — Add 250.5 USDT of isolated margin to the BTC_USDT_Perp position; amount uses the quote currency's decimals. Digest `0xb777923ee34033655e0f98d30dc6b5c2813235be0173fd88561c7be0b2a14c50`. - `remove_position_margin` — A negative amount removes margin: -100.25 is signed as the int64 -100250000. Digest `0x36780cb75505d0bfdafa27bd962f0436ba813f8f6705a1b53f870f2014225358`. ===== reference/signing/Order.md # Order (signed message) Signed by [`create_order`](/reference/rpc/create_order.md), [`bulk_orders`](/reference/rpc/bulk_orders.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text Order(uint64 subAccountID,bool isMarket,uint8 timeInForce,bool postOnly,bool reduceOnly,OrderLeg[] legs,uint32 nonce,int64 expiration)OrderLeg(uint256 assetID,uint64 contractSize,uint64 limitPrice,bool isBuyingContract) ``` Type hash `0xb4b857ba9641f20a7c4007c73e548a2ee5afb7207744cc41fa7849451419bbb2`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `subAccountID` | `uint64` | `order.sub_account_id` | `copy` | | `isMarket` | `bool` | `order.is_market` | `copy`; absent = `false` | | `timeInForce` | `uint8` | `order.time_in_force` | `enumCode`: integer value of `TimeInForce` | | `postOnly` | `bool` | `order.post_only` | `copy`; absent = `false` | | `reduceOnly` | `bool` | `order.reduce_only` | `copy`; absent = `false` | | `legs` | `OrderLeg[]` | `order.legs` | `each`: map every element as `OrderLeg` | | `nonce` | `uint32` | `order.signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `order.signature.expiration` | `sig.expiration` | | domain `chainId` | `uint256` | `order.signature.chain_id` | `sig.chainId` | Nested `OrderLeg` (paths relative to each list element): | EIP-712 field | Type | From element | Transform | |---|---|---|---| | `assetID` | `uint256` | `instrument` | `assetKey`: the instrument's `instrument_hash` as uint256 | | `contractSize` | `uint64` | `size` | `scaled`: decimal × 10^`base_decimals` of the instrument | | `limitPrice` | `uint64` | `limit_price` | `scaled`: decimal × 10^9; absent = `0` | | `isBuyingContract` | `bool` | `is_buying_asset` | `copy`; absent = `false` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `limit_order` — The standard first order: post-only GTT limit buy of 0.01 BTC_USDT_Perp at 60000 (600 USDT notional), Order type. Digest `0x7f8fecb8997024f85a5a9a44730f79d2cef290688d6a022d8e98e95ccc1f98c9`. - `market_order` — IOC market sell without limit_price (signed as 0). Digest `0xad740bcaef463a9de8c758bd333046188a986979fd9e05594d97d3c699ea28ce`. - `multi_leg_order` — Two legs on different instruments; legs keep their order. Digest `0xb0ae02ef544b7dbccedb1cbb177f99a3803c4d496cde5c29357027e5b8970999`. - `order_max_precision` — size uses all 9 base decimals of BTC and limit_price all 9 price decimals. Digest `0x2cb9842d6774c5a0a8bb183670b06f7fec2ce1376071f6f3d3128f303dc151c4`. - `bulk_orders`, `orders[0]` — Two orders in one bulk call, each signed on its own with its own nonce: a plain Order and an OrderWithBuilderFee, both on BTC_USDT_Perp (the server requires one asset per bulk call). The cancel list and time_to_live_ms are not signed. Digest `0x25418b3c70ba5f56b8756c1fad4d58be1bc1e09f2f57d7c97170b5320a6b9c06`. ===== reference/signing/OrderWithBuilderFee.md # OrderWithBuilderFee (signed message) Signed by [`create_order`](/reference/rpc/create_order.md), [`bulk_orders`](/reference/rpc/bulk_orders.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text OrderWithBuilderFee(uint64 subAccountID,bool isMarket,uint8 timeInForce,bool postOnly,bool reduceOnly,OrderLeg[] legs,address builder,uint32 builderFee,uint32 nonce,int64 expiration)OrderLeg(uint256 assetID,uint64 contractSize,uint64 limitPrice,bool isBuyingContract) ``` Type hash `0x6a59e4932070a97495ccc9de30b7309ec82b07156f8cfcbe516d28d226d11028`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `subAccountID` | `uint64` | `order.sub_account_id` | `copy` | | `isMarket` | `bool` | `order.is_market` | `copy`; absent = `false` | | `timeInForce` | `uint8` | `order.time_in_force` | `enumCode`: integer value of `TimeInForce` | | `postOnly` | `bool` | `order.post_only` | `copy`; absent = `false` | | `reduceOnly` | `bool` | `order.reduce_only` | `copy`; absent = `false` | | `legs` | `OrderLeg[]` | `order.legs` | `each`: map every element as `OrderLeg` | | `builder` | `address` | `order.builder` | `address` | | `builderFee` | `uint32` | `order.builder_fee` | `scaled`: decimal × 10^4; absent = `0` | | `nonce` | `uint32` | `order.signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `order.signature.expiration` | `sig.expiration` | | domain `chainId` | `uint256` | `order.signature.chain_id` | `sig.chainId` | Nested `OrderLeg` (paths relative to each list element): | EIP-712 field | Type | From element | Transform | |---|---|---|---| | `assetID` | `uint256` | `instrument` | `assetKey`: the instrument's `instrument_hash` as uint256 | | `contractSize` | `uint64` | `size` | `scaled`: decimal × 10^`base_decimals` of the instrument | | `limitPrice` | `uint64` | `limit_price` | `scaled`: decimal × 10^9; absent = `0` | | `isBuyingContract` | `bool` | `is_buying_asset` | `copy`; absent = `false` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `order_with_builder_fee` — builder set, so the server verifies OrderWithBuilderFee. builder_fee is scaled with 4 decimals. Digest `0x09b6c3c367b5641f38ab3750d2f5dc45325f3e46c15a3b6fe03e92b3ca7942af`. - `bulk_orders`, `orders[1]` — Two orders in one bulk call, each signed on its own with its own nonce: a plain Order and an OrderWithBuilderFee, both on BTC_USDT_Perp (the server requires one asset per bulk call). The cancel list and time_to_live_ms are not signed. Digest `0xd37d1ca9d12be0de22990d2a0e74fce73e6c4fb47b2a262b259208acc9dd6481`. ===== reference/signing/SetDeriskToMaintenanceMarginRatio.md # SetDeriskToMaintenanceMarginRatio (signed message) Signed by [`set_derisk_mm_ratio`](/reference/rpc/set_derisk_mm_ratio.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text SetDeriskToMaintenanceMarginRatio(uint64 subAccountID,uint32 deriskToMaintenanceMarginRatio,uint32 nonce,int64 expiration) ``` Type hash `0xacb6c1dcd395d10eb0681463bdc0d7dd0a0db302012781039cb1821ab326ed26`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `subAccountID` | `uint64` | `sub_account_id` | `copy` | | `deriskToMaintenanceMarginRatio` | `uint32` | `ratio` | `scaled`: decimal × 10^6 | | `nonce` | `uint32` | `signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `signature.expiration` | `sig.expiration` | | domain `chainId` | `uint256` | `signature.chain_id` | `sig.chainId` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `set_derisk_mm_ratio` — Derisk at 1.5x the maintenance margin; ratio has 6 decimals. Only risk checks this signature. Digest `0xcdf7cf83641d491b4bf66fe060fa7c308040762a7422ca26e7a78ada1c20c24b`. ===== reference/signing/SetSubAccountPositionMarginConfig.md # SetSubAccountPositionMarginConfig (signed message) Signed by [`set_position_config`](/reference/rpc/set_position_config.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text SetSubAccountPositionMarginConfig(uint64 subAccountID,uint256 asset,uint8 marginType,int32 leverage,uint32 nonce,int64 expiration) ``` Type hash `0x75673028b3d75e3ec43589ed8a9291dbea56da6886c45d05efafc68a4ae51395`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `subAccountID` | `uint64` | `sub_account_id` | `copy` | | `asset` | `uint256` | `instrument` | `assetKey`: the instrument's `instrument_hash` as uint256 | | `marginType` | `uint8` | `margin_type` | `enumCode`: integer value of `PositionMarginType` | | `leverage` | `int32` | `leverage` | `scaled`: decimal × 10^6 | | `nonce` | `uint32` | `signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `signature.expiration` | `sig.expiration` | | domain `chainId` | `uint256` | `signature.chain_id` | `sig.chainId` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `set_position_config` — Isolated margin at 10x leverage on BTC_USDT_Perp; leverage has 6 decimals. Digest `0x33634cb8359ac37c5c6d24e8763dfd3c97a26cde9351ea384bbf45f1c0394cb0`. ===== reference/signing/Transfer.md # Transfer (signed message) Signed by [`transfer`](/reference/rpc/transfer.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text Transfer(address fromAccount,uint64 fromSubAccount,address toAccount,uint64 toSubAccount,uint8 tokenCurrency,uint64 numTokens,uint32 nonce,int64 expiration) ``` Type hash `0xc68fcd68f79304f334c57a50cc1680546fa88e6147d97b3a1b18ac97a0c6b9f7`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `fromAccount` | `address` | `from_account_id` | `address` | | `fromSubAccount` | `uint64` | `from_sub_account_id` | `copy`; absent = `0` | | `toAccount` | `address` | `to_account_id` | `address` | | `toSubAccount` | `uint64` | `to_sub_account_id` | `copy`; absent = `0` | | `tokenCurrency` | `uint8` | `currency` | `currencyId`: `id` of the currency (get_currency) | | `numTokens` | `uint64` | `num_tokens` | `scaled`: decimal × 10^`balance_decimals` of the currency | | `nonce` | `uint32` | `signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `signature.expiration` | `sig.expiration` | | domain `chainId` | `uint256` | `signature.chain_id` | `sig.chainId` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `transfer` — Main account to sub account, no wallet types, so the Transfer type. Digest `0xf17ba792652522b4285c6c96b89d4aeb3eeffc817f7037cb89fa4f2a655a7781`. ===== reference/signing/TransferV2.md # TransferV2 (signed message) Signed by [`transfer`](/reference/rpc/transfer.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text TransferV2(address fromAccount,uint64 fromSubAccount,address toAccount,uint64 toSubAccount,uint8 tokenCurrency,uint64 numTokens,uint32 nonce,int64 expiration,uint8 fromWalletType,uint8 toWalletType) ``` Type hash `0x4c1e946de7758ace7db774b2ec9d3041167bf569933969a6c2aa121c6f02f5ff`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `fromAccount` | `address` | `from_account_id` | `address` | | `fromSubAccount` | `uint64` | `from_sub_account_id` | `copy`; absent = `0` | | `toAccount` | `address` | `to_account_id` | `address` | | `toSubAccount` | `uint64` | `to_sub_account_id` | `copy`; absent = `0` | | `tokenCurrency` | `uint8` | `currency` | `currencyId`: `id` of the currency (get_currency) | | `numTokens` | `uint64` | `num_tokens` | `scaled`: decimal × 10^`balance_decimals` of the currency | | `nonce` | `uint32` | `signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `signature.expiration` | `sig.expiration` | | `fromWalletType` | `uint8` | `from_wallet_type` | `enumCode`: integer value of `WalletType` | | `toWalletType` | `uint8` | `to_wallet_type` | `enumCode`: integer value of `WalletType` | | domain `chainId` | `uint256` | `signature.chain_id` | `sig.chainId` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `transfer_wallet_types` — Both wallet types set and currency id \<= 255, so TransferV2. Digest `0x9f0d9ae5e2b6aea384d9357b72f0acbcc96547780b73e62cffcbee6692b1a44d`. ===== reference/signing/TransferV3.md # TransferV3 (signed message) Signed by [`transfer`](/reference/rpc/transfer.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text TransferV3(address fromAccount,uint64 fromSubAccount,address toAccount,uint64 toSubAccount,uint16 tokenCurrency,uint64 numTokens,uint32 nonce,int64 expiration,uint8 fromWalletType,uint8 toWalletType) ``` Type hash `0xe4b142f35f6fa4dda9a3c282f42523d90ccd69b40e130b4207aa644826d8a9e6`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `fromAccount` | `address` | `from_account_id` | `address` | | `fromSubAccount` | `uint64` | `from_sub_account_id` | `copy`; absent = `0` | | `toAccount` | `address` | `to_account_id` | `address` | | `toSubAccount` | `uint64` | `to_sub_account_id` | `copy`; absent = `0` | | `tokenCurrency` | `uint16` | `currency` | `currencyId`: `id` of the currency (get_currency) | | `numTokens` | `uint64` | `num_tokens` | `scaled`: decimal × 10^`balance_decimals` of the currency | | `nonce` | `uint32` | `signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `signature.expiration` | `sig.expiration` | | `fromWalletType` | `uint8` | `from_wallet_type` | `enumCode`: integer value of `WalletType` | | `toWalletType` | `uint8` | `to_wallet_type` | `enumCode`: integer value of `WalletType` | | domain `chainId` | `uint256` | `signature.chain_id` | `sig.chainId` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `transfer_wide_currency` — Currency id 300 (> 255, test-only currency) with wallet types, so TransferV3. Digest `0xe3840019d1d63515d0900b95f816efee8aa6054d582e9caf5a723305748fbc44`. ===== reference/signing/VaultBurnLpToken.md # VaultBurnLpToken (signed message) Signed by [`vault_burn_tokens`](/reference/rpc/vault_burn_tokens.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text VaultBurnLpToken(uint64 vaultID,uint64 numLpTokens,address accountID,uint32 nonce,int64 expiration) ``` Type hash `0xbb9031c385869393ec7675231ae0f5561aafeebcb9530abf72b88b7c848ab64e`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `vaultID` | `uint64` | `vault_id` | `copy` | | `numLpTokens` | `uint64` | `num_tokens` | `scaled`: decimal × 10^6 | | `accountID` | `address` | none: `result.main_account_id` of [`funding_account_summary`](/reference/rpc/funding_account_summary.md) | `mainAccount`: your main account address, fetched once per session | | `nonce` | `uint32` | `signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `signature.expiration` | `sig.expiration` | | domain `chainId` | `uint256` | `signature.chain_id` | `sig.chainId` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `vault_burn_tokens` — A vault manager burns 100.5 shares (6 decimals). accountID is the session's main account; currency is not signed. Digest `0x1dcd849d0fbe437101afc1f2e1976430a2d21dfc6253d55c34e7b28849359477`. ===== reference/signing/VaultInvestV3.md # VaultInvestV3 (signed message) Signed by [`vault_invest`](/reference/rpc/vault_invest.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text VaultInvestV3(uint64 vaultID,address accountID,uint64 fromSubAccountID,uint8 fromWalletType,uint16 fromCurrency,uint64 fromNumTokens,uint16 toCurrency,uint64 exchangeRate,uint32 nonce,int64 expiration) ``` Type hash `0x9310afe005ecc1260bf9be1863d1fde16bed5d7be16ed68926ddf67cd10a736e`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `vaultID` | `uint64` | `vault_id` | `copy` | | `accountID` | `address` | none: `result.main_account_id` of [`funding_account_summary`](/reference/rpc/funding_account_summary.md) | `mainAccount`: your main account address, fetched once per session | | `fromSubAccountID` | `uint64` | `from_sub_account_id` | `copy`; absent = `0` | | `fromWalletType` | `uint8` | `from_wallet_type` | `enumCode`: integer value of `WalletType` | | `fromCurrency` | `uint16` | `from_currency` | `currencyId`: `id` of the currency (get_currency) | | `fromNumTokens` | `uint64` | `from_num_tokens` | `scaled`: decimal × 10^`balance_decimals` of the currency | | `toCurrency` | `uint16` | `to_currency` | `currencyId`: `id` of the currency (get_currency) | | `exchangeRate` | `uint64` | `exchange_rate` | `scaled`: decimal × 10^9 | | `nonce` | `uint32` | `signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `signature.expiration` | `sig.expiration` | | domain `chainId` | `uint256` | `signature.chain_id` | `sig.chainId` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `vault_invest` — Invest 1000.5 USDT from the funding account into a vault whose investment currency is USDC, at 0.9998 USDC per USDT. accountID is the session's main account (metadata main_account_id); from_num_tokens uses USDT's decimals and exchange_rate 9. Digest `0x5e28c5a2d5e01a4b43ef7200c727c0d9864bb5f252ebf484386d5b486f43ba44`. ===== reference/signing/VaultRedeemV3.md # VaultRedeemV3 (signed message) Signed by [`vault_redeem`](/reference/rpc/vault_redeem.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text VaultRedeemV3(uint64 vaultID,address accountID,uint64 numLpTokens,uint16 fromCurrency,uint16 toCurrency,uint64 exchangeRate,uint32 nonce,int64 expiration) ``` Type hash `0x0041a915dd4c05c7c4a826912cfd10269e6dd51bd2d89f24a5b4b575bb118f44`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `vaultID` | `uint64` | `vault_id` | `copy` | | `accountID` | `address` | none: `result.main_account_id` of [`funding_account_summary`](/reference/rpc/funding_account_summary.md) | `mainAccount`: your main account address, fetched once per session | | `numLpTokens` | `uint64` | `num_tokens` | `scaled`: decimal × 10^6 | | `fromCurrency` | `uint16` | `from_currency` | `currencyId`: `id` of the currency (get_currency) | | `toCurrency` | `uint16` | `to_currency` | `currencyId`: `id` of the currency (get_currency) | | `exchangeRate` | `uint64` | `exchange_rate` | `scaled`: decimal × 10^9 | | `nonce` | `uint32` | `signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `signature.expiration` | `sig.expiration` | | domain `chainId` | `uint256` | `signature.chain_id` | `sig.chainId` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `vault_redeem` — Redeem 12.345678 shares (6 decimals) paid in USDT at 1.0001 USDT per USDC. accountID is the session's main account. Digest `0xa4b83096a74185b2cce4262757961859610ca0e54b18548e577014288144c9c2`. ===== reference/signing/WalletLogin.md # WalletLogin (signed message) Signed by [`login_wallet`](/reference/rpc/login_wallet.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text WalletLogin(address signer,uint32 nonce,int64 expiration) ``` Type hash `0x4451fb6c92ff3fc4a27d19a1cb3287041a7cacdd394d0988eca8af8549ace29b`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `signer` | `address` | `address` | `address` | | `nonce` | `uint32` | `signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `signature.expiration` | `sig.expiration` | | domain `chainId` | `uint256` | `signature.chain_id` | `sig.chainId` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `wallet_login` — Edge wallet login. address must equal signature.signer. Digest `0x1522126e0b0e4534911f1b6f21a6dedad8c88a49c6012937d6101fa155aa6e14`. ===== reference/signing/Withdrawal.md # Withdrawal (signed message) Signed by [`withdrawal`](/reference/rpc/withdrawal.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text Withdrawal(address fromAccount,address toEthAddress,uint8 tokenCurrency,uint64 numTokens,uint32 nonce,int64 expiration) ``` Type hash `0x2fdc0a1d89cd65000e141c89522ab3a0aa95182aba37a08842dc72a1992a0c3f`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `fromAccount` | `address` | `from_account_id` | `address` | | `toEthAddress` | `address` | `to_eth_address` | `address` | | `tokenCurrency` | `uint8` | `currency` | `currencyId`: `id` of the currency (get_currency) | | `numTokens` | `uint64` | `num_tokens` | `scaled`: decimal × 10^`balance_decimals` of the currency | | `nonce` | `uint32` | `signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `signature.expiration` | `sig.expiration` | | domain `chainId` | `uint256` | `signature.chain_id` | `sig.chainId` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `withdrawal` — Withdraw USDT to an L1 address, Withdrawal type. Digest `0xa7e3ab08c20d4574f000a953000123ca0611217504d478db4d85b4bf8ac986c4`. ===== reference/signing/WithdrawalV2.md # WithdrawalV2 (signed message) Signed by [`withdrawal`](/reference/rpc/withdrawal.md). Step-by-step walkthrough: [Signing](/guides/signing.md). ```text WithdrawalV2(address fromAccount,address toEthAddress,uint16 tokenCurrency,uint64 numTokens,uint32 nonce,int64 expiration) ``` Type hash `0x95cee98524289377640c5062cf8544d478f523ab193a43fd63cbd38a662657fd`. Domain `{name: "GRVT Exchange", version: "0", chainId}`. ## Fields and where they come from | EIP-712 field | Type | From request | Transform | |---|---|---|---| | `fromAccount` | `address` | `from_account_id` | `address` | | `toEthAddress` | `address` | `to_eth_address` | `address` | | `tokenCurrency` | `uint16` | `currency` | `currencyId`: `id` of the currency (get_currency) | | `numTokens` | `uint64` | `num_tokens` | `scaled`: decimal × 10^`balance_decimals` of the currency | | `nonce` | `uint32` | `signature.nonce` | `sig.nonce` | | `expiration` | `int64` | `signature.expiration` | `sig.expiration` | | domain `chainId` | `uint256` | `signature.chain_id` | `sig.chainId` | ## Signing test cases In [signing.json](/downloads/signing.json), signed by the public test key: - `withdrawal_wide_currency` — Currency id 300 (> 255, test-only currency), so WithdrawalV2. Digest `0x007f18ccb50939a8203edb873f95172d15e006acbe878c9d2673198a9ab08905`. ===== reference/signing/index.md # Signed messages Orders, transfers, withdrawals and wallet login carry a signature from your key (EIP-712). The SDKs sign for you; these pages are for signing by hand or for finding out why a signature is rejected. [Signing](/guides/signing.md) walks through it step by step. ## Which message to sign | Call | Message, and when to use each | |---|---| | [`set_derisk_mm_ratio`](/reference/rpc/set_derisk_mm_ratio.md) | [`SetDeriskToMaintenanceMarginRatio`](/reference/signing/SetDeriskToMaintenanceMarginRatio.md) | | [`login_wallet`](/reference/rpc/login_wallet.md) | [`WalletLogin`](/reference/signing/WalletLogin.md) | | [`bulk_orders`](/reference/rpc/bulk_orders.md) | every element of `orders` separately, with its own nonce and expiration (the field tables' `order.` paths mean that element): [`Order`](/reference/signing/Order.md) / [`OrderWithBuilderFee`](/reference/signing/OrderWithBuilderFee.md). Each order is signed on its own, like create_order: OrderWithBuilderFee when that order's builder is set to a non-zero address, otherwise Order. The cancel lists and time_to_live_ms are not signed. | | [`create_order`](/reference/rpc/create_order.md) | [`Order`](/reference/signing/Order.md) / [`OrderWithBuilderFee`](/reference/signing/OrderWithBuilderFee.md). Use OrderWithBuilderFee when order.builder is set to a non-zero address, otherwise Order. | | [`add_position_margin`](/reference/rpc/add_position_margin.md) | [`AddIsolatedPositionMargin`](/reference/signing/AddIsolatedPositionMargin.md) | | [`set_position_config`](/reference/rpc/set_position_config.md) | [`SetSubAccountPositionMarginConfig`](/reference/signing/SetSubAccountPositionMarginConfig.md) | | [`transfer`](/reference/rpc/transfer.md) | [`Transfer`](/reference/signing/Transfer.md) / [`TransferV2`](/reference/signing/TransferV2.md) / [`TransferV3`](/reference/signing/TransferV3.md). If from_wallet_type and to_wallet_type are both set: TransferV2 when the currency id fits uint8 (\<= 255), else TransferV3. If neither is set: Transfer (only for currency ids \<= 255). Setting only one is rejected. Sign TransferV3 only for currency ids above 255. | | [`withdrawal`](/reference/rpc/withdrawal.md) | [`Withdrawal`](/reference/signing/Withdrawal.md) / [`WithdrawalV2`](/reference/signing/WithdrawalV2.md). Withdrawal when the currency id fits uint8 (\<= 255), else WithdrawalV2. | | [`vault_burn_tokens`](/reference/rpc/vault_burn_tokens.md) | [`VaultBurnLpToken`](/reference/signing/VaultBurnLpToken.md) | | [`vault_invest`](/reference/rpc/vault_invest.md) | [`VaultInvestV3`](/reference/signing/VaultInvestV3.md) | | [`vault_redeem`](/reference/rpc/vault_redeem.md) | [`VaultRedeemV3`](/reference/signing/VaultRedeemV3.md) |