Developers

Signing

How orders, transfers and withdrawals are signed (EIP-712), step by step with a real server signing test case.

On this page

Orders, transfers, withdrawals, wallet login, vault, position margin and qualified maker calls carry an EIP-712 signature made with your signing key.

With an SDK, the SDK signs for you: read only 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: 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); per currency, id and balance_decimals (get_currency) for transfers, withdrawals and strategies; for vault calls, your main account (see Main account).

  3. Map wire fields to the EIP-712 message using the signed type's table (Order). Each field has one transform:

    TransformWhat it doesExample (limit_order)
    copyvalue as is; 64-bit ints arrive as stringssub_account_id "8289849667772468" → 8289849667772468
    enumCodeenum name → its integer (Enums)GOOD_TILL_TIME → 1
    assetKeyinstrument → instrument_hash as uint256BTC_USDT_Perp → 0x030501 = 197889
    scaleddecimal string × 10^decimals, exactsize "0.01" × 10^9 → 10000000; price "60000" × 10^9 → 60000000000000
    sig.nonce, sig.expirationcopied from the signature object1001, 4102444800000000000 (unix ns; the SDKs use now + 1 day)
    sig.chainIddomain chain ID; "0" = the environment's326 (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.

Sign the example in your browser

The code

Runnable as is (pip install coincurve pycryptodome). It prints the intermediate values and checks them against the signing case:

Download this example

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:

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. 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.
  • 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:

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 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_<call> reports that the call needs it, and your app passes it in.

Other signed types

TypeUsed byNotes
Transfer, TransferV2, TransferV3transferV2 when wallet types are set; V3 for currency ids above 255
Withdrawal, WithdrawalV2withdrawalV2 for currency ids above 255
WalletLoginwallet loginexpiration at most 5 minutes ahead
VaultInvestV3vault_investsigns your main account
VaultRedeemV3vault_redeemsigns your main account
VaultBurnLpTokenvault_burn_tokenssigns your main account; currency is not signed
AddIsolatedPositionMarginadd_position_marginnegative amount removes margin
SetSubAccountPositionMarginConfigset_position_config
SetDeriskToMaintenanceMarginRatioset_derisk_mm_ratio

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.

esc

↑ ↓ move↵ open⇧↵ open .mdTry an error code like 2002

Keyboard shortcuts

⌘ K
Search the docs
/
Search
l
Next code language (Python → TypeScript → Go → Rust → curl → WebSocket)
j / k
Next / previous page
t
Light / dark theme
?
This help
Esc
Close dialogs and drawers