Skip to content

Trading APIs

All requests should be made using the POST HTTP method.

For example:

curl -X POST https://trades.testnet.grvt.io/lite/v1/account_summary -d '{"sa":"12345678"}'

Orders

Create Order

Create an order on the orderbook for this account.

FULL ENDPOINT: full/v1/create_order
LITE ENDPOINT: lite/v1/create_order
ApiCreateOrderRequest
Name Lite Type Description
order o Order The order to create
Order

Order is a typed payload used throughout the GRVT platform to express all orderbook, RFQ, and liquidation orders.
GRVT orders are capable of expressing both single-legged, and multi-legged orders by default.
This increases the learning curve slightly but reduces overall integration load, since the order payload is used across all GRVT trading venues.
Given GRVT's trustless settlement model, the Order payload also carries the signature, required to trade the order on our ZKSync Hyperchain.

All fields in the Order payload (except id, metadata, and state) are trustlessly enforced on our Hyperchain.
This minimizes the amount of trust users have to offer to GRVT

Name Lite Type Description
order_id oi uint128 [Filled by GRVT Backend] A unique 128-bit identifier for the order, deterministically generated within the GRVT backend
sub_account_id sa uint64 The subaccount initiating the order
is_market im bool If the order is a market order
Market Orders do not have a limit price, and are always executed according to the maker order price.
Market Orders must always be taker orders
time_in_force ti TimeInForce Four supported types of orders: GTT, IOC, AON, FOK:

  • PARTIAL EXECUTION = GTT / IOC - allows partial size execution on each leg

  • FULL EXECUTION = AON / FOK - only allows full size execution on all legs

  • TAKER ONLY = IOC / FOK - only allows taker orders

  • MAKER OR TAKER = GTT / AON - allows maker or taker orders

Exchange only supports (GTT, IOC, FOK)
RFQ Maker only supports (GTT, AON), RFQ Taker only supports (FOK)
taker_fee_percentage_cap tf int32 The taker fee percentage cap signed by the order.
This is the maximum taker fee percentage the order sender is willing to pay for the order.
Expressed in 1/100th of a basis point. Eg. 100 = 1bps, 10,000 = 1%
maker_fee_percentage_cap mf int32 Same as TakerFeePercentageCap, but for the maker fee. Negative for maker rebates
post_only po bool If True, Order must be a maker order. It has to fill the orderbook instead of match it.
If False, Order can be either a maker or taker order.

reduce_only ro bool If True, Order must reduce the position size, or be cancelled
legs l [OrderLeg] The legs present in this order
The legs must be sorted by Asset.Instrument/Underlying/Quote/Expiration/StrikePrice
signature s Signature The signature approving this order
metadata m OrderMetadata Order Metadata, ignored by the smart contract, and unsigned by the client
state s1 OrderState [Filled by GRVT Backend] The current state of the order, ignored by the smart contract, and unsigned by the client
TimeInForce
Must Fill All Can Fill Partial
Must Fill Immediately FOK IOC
Can Fill Till Time AON GTC


TimeInForce:

  • GOOD_TILL_TIME = 1: GTT - Remains open until it is cancelled, or expired
  • ALL_OR_NONE = 2: AON - Either fill the whole order or none of it (Block Trades Only)
  • IMMEDIATE_OR_CANCEL = 3: IOC - Fill the order as much as possible, when hitting the orderbook. Then cancel it
  • FILL_OR_KILL = 4: FOK - Both AoN and IoC. Either fill the full order when hitting the orderbook, or cancel it

OrderLeg
Name Lite Type Description
instrument i string The instrument to trade in this leg
size s uint64 The total number of assets to trade in this leg, expressed in underlying asset decimal units.
limit_price lp uint64 The limit price of the order leg, expressed in 9 decimals.
This is the total amount of base currency to pay/receive for all legs.
oco_limit_price ol uint64 If a OCO order is specified, this must contain the other limit price
User must sign both limit prices. Depending on which trigger condition is activated, a different limit price is used
The smart contract will always validate both limit prices, by arranging them in ascending order
is_buying_asset ib bool Specifies if the order leg is a buy or sell
Signature
Name Lite Type Description
signer s uint256 The address (public key) of the wallet signing the payload
r r uint256 Signature R
s s1 uint256 Signature S
v v uint8 Signature V
expiration e Timestamp Timestamp after which this signature expires, expressed in unix nanoseconds. Must be capped at 30 days
nonce n uint32 Users can randomly generate this value, used as a signature deconflicting key.
ie. You can send the same exact instruction twice with different nonces.
When the same nonce is used, the same payload will generate the same signature.
Our system will consider the payload a duplicate, and ignore it.
OrderMetadata

Metadata fields are used to support Backend only operations. These operations are not trustless by nature.
Hence, fields in here are never signed, and is never transmitted to the smart contract.

Name Lite Type Description
client_order_id co uint32 A unique identifier for the active order within a subaccount, specified by the client
This is used to identify the order in the client's system
This field can be used for order amendment/cancellation, but has no bearing on the smart contract layer
This field will not be propagated to the smart contract, and should not be signed by the client
This value must be unique for all active orders in a subaccount, or amendment/cancellation will not work as expected
Gravity UI will generate a random clientOrderID for each order in the range [0, 2^31 - 1]
To prevent any conflicts, client machines should generate a random clientOrderID in the range [2^31, 2^32 - 1]

When GRVT Backend receives an order with an overlapping clientOrderID, we will reject the order with rejectReason set to overlappingClientOrderId
create_time ct Timestamp [Filled by GRVT Backend] Time at which the order was received by GRVT in unix nanoseconds
OrderState
Name Lite Type Description
status s OrderStatus The status of the order
reject_reason rr OrderRejectReason The reason for rejection or cancellation
book_size bs [uint64] The number of assets available for orderbook/RFQ matching. Sorted in same order as Order.Legs
traded_size ts [uint64] The total number of assets traded. Sorted in same order as Order.Legs
update_time ut Timestamp Time at which the order was updated by GRVT, expressed in unix nanoseconds
OrderStatus

OrderStatus:

  • PENDING = 1: Order is waiting for Trigger Condition to be hit
  • OPEN = 2: Order is actively matching on the orderbook, could be unfilled or partially filled
  • FILLED = 3: Order is fully filled and hence closed
  • REJECTED = 4: Order is rejected by GRVT Backend since if fails a particular check (See OrderRejectReason)
  • CANCELLED = 5: Order is cancelled by the user using one of the supported APIs (See OrderRejectReason)

OrderRejectReason

OrderRejectReason:

  • CLIENT_CANCEL = 1: client called a Cancel API
  • CLIENT_BULK_CANCEL = 2: client called a Bulk Cancel API
  • CLIENT_SESSION_END = 3: client called a Session Cancel API, or set the WebSocket connection to 'cancelOrdersOnTerminate'
  • INSTRUMENT_DEACTIVATED = 4: instrument is no longer tradable on Gravity. (typically due to a market halt, or instrument expiry)
  • MM_PROTECTION = 5: market maker protection triggered
  • EXPIRED = 6: the order has expired
  • BELOW_MARGIN = 7: the order will bring the sub account below initial margin requirement
  • LIQUIDATION = 8: the sub account is liquidated (and all open orders are cancelled by Gravity)
  • SYSTEM_FAILOVER = 9: system failover resulting in loss of order state
  • CONFLICTING_SIGNATURE_HASH = 10: a previous order shares the same signature hash as your current order (typically when you submit the same signature twice)
  • OVERLAPPING_CLIENT_ORDER_ID = 11: an active order on your sub account shares the same clientOrderId
  • RFQ_CANCELLED = 12: the RFQ has been cancelled
  • AXE_CANCELLED = 13: the AXE has been cancelled
  • INVALID_ORDER = 14: the order payload contains one or more validation error (Trading Server will reply with a more specific error)
  • UNAUTHORISED = 15: the credentials used (userSession/apiKeySession/walletSignature) is not authorised to perform the action
  • FAIL_POST_ONLY = 16: when post-only order enters orderbook as a taker order
  • FAIL_REDUCE_ONLY = 17: when reduce-only order causes position size to increase
  • INVALID_TRIGGER_PRICE = 18: trigger price is on the wrong side of the trigger condition
  • RFQ_EXPIRED = 19: the RFQ has expired
  • AXE_EXPIRED = 20: the AXE has expired
  • FAIL_FOK = 21: the FOK order could not be fully matched
  • FAIL_AON = 22: the AON order could not be fully matched
  • SELF_MATCHED_SUBACCOUNT = 23: the order matched with another order from the same sub account
  • SIGNATURE_SIZE_EXCEEDED = 24: the signature size exceeds the maximum allowed size
  • SUB_ACCOUNT_NOT_FOUND = 25: the subaccount does not exist
  • BAD_SIGNATURE = 26: the signature is invalid
  • SIZE_NON_ZERO_ON_UNMACHED_LEG = 27: maker order size is non-zero on an unmatched leg
  • TRADE_SAME_SIDE = 28: the order trades with another order on the same side
  • TRADE_PRICE_DOES_NOT_CROSS = 29: the order trades with another order but the price does not cross
  • NO_LEG = 30: the order has no legs
  • MARKET_ORDER_ON_MAKER_SIDE = 31: market order on maker side
  • TIME_IN_FORCE_REQUIRE_TAKER = 32: time in force requires taker
  • ASSET_QUOTE_NOT_MATCHING = 33: asset quote not matching
  • MISSING_MARK_PRICE = 34: missing mark price
  • MISSING_INDEX_PRICE = 35: missing index price
  • SESSION_KEY_EXPIRED = 36: session key expired
  • DUPLICATE_LEG_ASSET = 37: duplicate leg asset
  • CHARGED_FEE_ABOVE_SIGNED_AMOUNT = 38: charged fee above signed amount
  • CHARGED_FEE_BELOW_MIN = 39: charged fee below minimum
  • NO_TRADE_PERMISSION = 40: no trade permission
  • NOT_MATCHED_AGAINS_TAKER_LEGS = 41: a maker order without any leg that is matched (size > 0) against at least 1 taker leg
  • ORDER_NOT_FULLY_MATCHED = 42: AON/FOK order not fully matched
  • ASSET_EXPIRED = 43: asset expired
  • NUM_LEGS_SIZE_MATCHED_MISMATCH = 44: number of legs and number of legs mismatch, eg: 2 legs, but sizeMatched is [1,2,3]

AckResponse

This endpoint only supports ACK responses. See Error code section for more details. This will either return true, or a relevant error code.

Name Lite Type Description
acknowledgement a bool Gravity has acknowledged that the request has been successfully received and it will process it in the backend

Example

{
    "order_id": "0x0123456789abcdef0123456789abcdef", // uint128 = 32 bytes
    "sub_account_id": 1,
    "is_market": false,
    "time_in_force": "GTT",
    "limit_price": "1000000000", // uint64
    "oco_limit_price": "1100000000", // uint64
    "taker_fee_percentage_cap": 500, // 5bps uint32
    "maker_fee_percentage_cap": 300, // 3bps uint32
    "post_only": true,
    "reduce_only": false,
    "is_paying_base_currency": true,
    "legs": [
        {
            "instrument": "BTC_USDT_Perp",
            "size": 10000000, // uint64
            "limit_price": 1000000, // uint64
            "oco_limit_price": 10000000, // uint64
            "is_buying_asset": true
        }
    ],
    "signature": {
        "r": "0x54730fcf60f37072926ba182d17e55e21104fbc22886d876a7e8b191b2d456f", // uint128 = 64 bytes
        "s": "0x1f32f41a809b2f2b888bddc2bdbf5ef709403a00d4e5e23dbaef09e55130464", // uint128 = 64 bytes
        "v": 27, // uint8
        "expiration": "1689526957000000" // uint64
    },
    "metadata": {
        "client_order_id": 2183798, // uint32
        "type": "OCO_LIMIT",
        "take_profit_trigger_condition": 1, // INDEX uint32
        "stop_loss_trigger_condition": 1, // INDEX uint32
        "take_profit_trigger_price": "1070000000", // uint64
        "stop_loss_trigger_price": "1020000000" // uint64
    },
    "state": {
        "status": 2, // OPEN uint32
        "reject_reason": 0, // NONE uint32
        "num_contracts_left": "500000000", // uint64
        "book_size": [1, 2, 3, 5], // []uint64
        "traded_size": [1, 2, 3, 5], // []uint64
        "update_time": 1000000000
    }
}

Example

{
    "code": 3,
    "msg":"PERMISSION_DENIED"
}
Code Number Description
INVALID_TIME_IN_FORCE 2001 FULL_ORDER_PRICE_IN_LEGS
MARKET_ORDER_WITH_LIMIT_PRICE 2002 Market Order must always be supplied without a limit price
LIMIT_ORDER_WITHOUT_LIMIT_PRICE 2003 Limit Order must always be supplied with a limit price
OCO_ORDER_WITHOUT_OCO_LIMIT_PRICE 2004 One-Cancels-Other Order must always be supplied with an oco limit price
INSUFFICIENT_TAKER_FEE 2005 Signed Taker Fee lower than Account eligibility
INSUFFICIENT_MAKER_FEE 2006 Signed Maker Fee lower than Account eligibility
POST_ONLY_WHEN_TAKER_ORDER 2007 Post Only can only be set to true for GTT/AON orders
LEGS_EMPTY 2008 Order must contain at least one leg
LEGS_NOT_SORTED 2009 Order Legs must be sorted by Derivative.Instrument/Underlying/BaseCurrency/Expiration/StrikePrice
INACTIVE_DERIVATIVE 2010 Order Legs contain one or more inactive derivative
NUM_CONTRACTS_UNDER_MIN_SIZE 2011 Order size smaller than min size
NUM_CONTRACTS_UNDER_MIN_BLOCK_SIZE 2012 Order size smaller than min block size in block trade venue
ORDER_SIGNATURE_UNAUTHORIZED 2013 Order signature is from an unauthorized signer
ORDER_SIGNATURE_EXPIRED 2014 Order signature has expired
ORDER_SIGNATURE_DOES_NOT_MATCH_PAYLOAD 2015 Order signature does not match payload
CLIENT_ORDER_ID_OVERLAPS 2016 Client Order ID overlaps with existing active order
INVALID_TRIGGER_CONDITION 2017 Usage of an invalid trigger condition
INVALID_TRIGGER_PRICE 2018 Usage of an invalid trigger price
FULL_ORDER_PRICE_IN_LEGS 2019 AON/FOK Order must specify price in legs
PARTIAL_ORDER_PRICE_OUTSIDE_LEGS 2020 GTT/IOC Order must specify price outside legs
Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Cancel Order

Cancel an order on the orderbook for this account

FULL ENDPOINT: full/v1/cancel_order
LITE ENDPOINT: lite/v1/cancel_order
ApiCancelOrderRequest
Name Lite Type Description
sub_account_id sa uint64 The subaccount ID cancelling the order
order_id oi uint128 Cancel the order with this order_id
client_order_id co uint32 Cancel the order with this client_order_id
AckResponse

This endpoint only supports ACK responses. See Error code section for more details. This will either return true, or a relevant error code.

Name Lite Type Description
acknowledgement a bool Gravity has acknowledged that the request has been successfully received and it will process it in the backend

Example

{
    "sa": "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", // uint256 = 64 bytes
    "oi": "0x0123456789abcdef0123456789abcdef" // uint128 = 32 bytes
}

Example

{
    "code": 3,
    "msg":"PERMISSION_DENIED"
}
Code Number Description
ORDER_ID_NOT_FOUND 2101 The order_id supplied is not found
CLIENT_ORDER_ID_NOT_FOUND 2102 The client_order_id supplied is not found
Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Cancel All Orders

Cancels all orders for the account. This may not match new orders in flight.

FULL ENDPOINT: full/v1/cancel_all_orders
LITE ENDPOINT: lite/v1/cancel_all_orders
ApiCancelAllOrdersRequest
Name Lite Type Description
sub_account_id sa uint64 The subaccount ID cancelling all orders
ApiCancelAllOrdersResponse
Name Lite Type Description
num_cancelled nc uint32 The number of orders cancelled

Example

{
    "sa": "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" // uint256 = 64 bytes
}

Example

{
    "nc": 42
}
Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Cancel All Session Orders

Cancels all non-persistent orders in the session. This method is allowed only on sessions that were set to cancel_on_disconnect, and has the same result as closing the connection:

  • all non-persistent orders are deleted, including those still in flight, with delete reason session_end.
  • market maker protection groups are reset and must be re-initialised.
FULL ENDPOINT: full/v1/cancel_session_orders
LITE ENDPOINT: lite/v1/cancel_session_orders

This has been marked as a POST-LAUNCH feature

Do reach out to the Gravity Team, if this is an important API for you


Open Orders

Retrieves all open orders for the account. This may not match new orders in flight.

METHOD: GET
FULL ENDPOINT: full/v1/open_orders
LITE ENDPOINT: lite/v1/open_orders
ApiOpenOrdersRequest
Name Lite Type Description
sub_account_id sa uint64 The subaccount ID to filter by
kind k [Kind] The kind filter to apply. If nil, this defaults to all kinds. Otherwise, only entries matching the filter will be returned
underlying u [Currency] The underlying filter to apply. If nil, this defaults to all underlyings. Otherwise, only entries matching the filter will be returned
quote q [Currency] The quote filter to apply. If nil, this defaults to all quotes. Otherwise, only entries matching the filter will be returned
Kind

The list of asset kinds that are supported on the GRVT exchange
Kind:

  • PERPETUAL = 1: the perpetual asset kind
  • FUTURE = 2: the future asset kind
  • CALL = 3: the call option asset kind
  • PUT = 4: the put option asset kind

Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

ApiOpenOrdersResponse
Name Lite Type Description
orders o [Order] The Open Orders matching the request filter
Order

Order is a typed payload used throughout the GRVT platform to express all orderbook, RFQ, and liquidation orders.
GRVT orders are capable of expressing both single-legged, and multi-legged orders by default.
This increases the learning curve slightly but reduces overall integration load, since the order payload is used across all GRVT trading venues.
Given GRVT's trustless settlement model, the Order payload also carries the signature, required to trade the order on our ZKSync Hyperchain.

All fields in the Order payload (except id, metadata, and state) are trustlessly enforced on our Hyperchain.
This minimizes the amount of trust users have to offer to GRVT

Name Lite Type Description
order_id oi uint128 [Filled by GRVT Backend] A unique 128-bit identifier for the order, deterministically generated within the GRVT backend
sub_account_id sa uint64 The subaccount initiating the order
is_market im bool If the order is a market order
Market Orders do not have a limit price, and are always executed according to the maker order price.
Market Orders must always be taker orders
time_in_force ti TimeInForce Four supported types of orders: GTT, IOC, AON, FOK:

  • PARTIAL EXECUTION = GTT / IOC - allows partial size execution on each leg

  • FULL EXECUTION = AON / FOK - only allows full size execution on all legs

  • TAKER ONLY = IOC / FOK - only allows taker orders

  • MAKER OR TAKER = GTT / AON - allows maker or taker orders

Exchange only supports (GTT, IOC, FOK)
RFQ Maker only supports (GTT, AON), RFQ Taker only supports (FOK)
taker_fee_percentage_cap tf int32 The taker fee percentage cap signed by the order.
This is the maximum taker fee percentage the order sender is willing to pay for the order.
Expressed in 1/100th of a basis point. Eg. 100 = 1bps, 10,000 = 1%
maker_fee_percentage_cap mf int32 Same as TakerFeePercentageCap, but for the maker fee. Negative for maker rebates
post_only po bool If True, Order must be a maker order. It has to fill the orderbook instead of match it.
If False, Order can be either a maker or taker order.

reduce_only ro bool If True, Order must reduce the position size, or be cancelled
legs l [OrderLeg] The legs present in this order
The legs must be sorted by Asset.Instrument/Underlying/Quote/Expiration/StrikePrice
signature s Signature The signature approving this order
metadata m OrderMetadata Order Metadata, ignored by the smart contract, and unsigned by the client
state s1 OrderState [Filled by GRVT Backend] The current state of the order, ignored by the smart contract, and unsigned by the client
TimeInForce
Must Fill All Can Fill Partial
Must Fill Immediately FOK IOC
Can Fill Till Time AON GTC


TimeInForce:

  • GOOD_TILL_TIME = 1: GTT - Remains open until it is cancelled, or expired
  • ALL_OR_NONE = 2: AON - Either fill the whole order or none of it (Block Trades Only)
  • IMMEDIATE_OR_CANCEL = 3: IOC - Fill the order as much as possible, when hitting the orderbook. Then cancel it
  • FILL_OR_KILL = 4: FOK - Both AoN and IoC. Either fill the full order when hitting the orderbook, or cancel it

OrderLeg
Name Lite Type Description
instrument i string The instrument to trade in this leg
size s uint64 The total number of assets to trade in this leg, expressed in underlying asset decimal units.
limit_price lp uint64 The limit price of the order leg, expressed in 9 decimals.
This is the total amount of base currency to pay/receive for all legs.
oco_limit_price ol uint64 If a OCO order is specified, this must contain the other limit price
User must sign both limit prices. Depending on which trigger condition is activated, a different limit price is used
The smart contract will always validate both limit prices, by arranging them in ascending order
is_buying_asset ib bool Specifies if the order leg is a buy or sell
Signature
Name Lite Type Description
signer s uint256 The address (public key) of the wallet signing the payload
r r uint256 Signature R
s s1 uint256 Signature S
v v uint8 Signature V
expiration e Timestamp Timestamp after which this signature expires, expressed in unix nanoseconds. Must be capped at 30 days
nonce n uint32 Users can randomly generate this value, used as a signature deconflicting key.
ie. You can send the same exact instruction twice with different nonces.
When the same nonce is used, the same payload will generate the same signature.
Our system will consider the payload a duplicate, and ignore it.
OrderMetadata

Metadata fields are used to support Backend only operations. These operations are not trustless by nature.
Hence, fields in here are never signed, and is never transmitted to the smart contract.

Name Lite Type Description
client_order_id co uint32 A unique identifier for the active order within a subaccount, specified by the client
This is used to identify the order in the client's system
This field can be used for order amendment/cancellation, but has no bearing on the smart contract layer
This field will not be propagated to the smart contract, and should not be signed by the client
This value must be unique for all active orders in a subaccount, or amendment/cancellation will not work as expected
Gravity UI will generate a random clientOrderID for each order in the range [0, 2^31 - 1]
To prevent any conflicts, client machines should generate a random clientOrderID in the range [2^31, 2^32 - 1]

When GRVT Backend receives an order with an overlapping clientOrderID, we will reject the order with rejectReason set to overlappingClientOrderId
create_time ct Timestamp [Filled by GRVT Backend] Time at which the order was received by GRVT in unix nanoseconds
OrderState
Name Lite Type Description
status s OrderStatus The status of the order
reject_reason rr OrderRejectReason The reason for rejection or cancellation
book_size bs [uint64] The number of assets available for orderbook/RFQ matching. Sorted in same order as Order.Legs
traded_size ts [uint64] The total number of assets traded. Sorted in same order as Order.Legs
update_time ut Timestamp Time at which the order was updated by GRVT, expressed in unix nanoseconds
OrderStatus

OrderStatus:

  • PENDING = 1: Order is waiting for Trigger Condition to be hit
  • OPEN = 2: Order is actively matching on the orderbook, could be unfilled or partially filled
  • FILLED = 3: Order is fully filled and hence closed
  • REJECTED = 4: Order is rejected by GRVT Backend since if fails a particular check (See OrderRejectReason)
  • CANCELLED = 5: Order is cancelled by the user using one of the supported APIs (See OrderRejectReason)

OrderRejectReason

OrderRejectReason:

  • CLIENT_CANCEL = 1: client called a Cancel API
  • CLIENT_BULK_CANCEL = 2: client called a Bulk Cancel API
  • CLIENT_SESSION_END = 3: client called a Session Cancel API, or set the WebSocket connection to 'cancelOrdersOnTerminate'
  • INSTRUMENT_DEACTIVATED = 4: instrument is no longer tradable on Gravity. (typically due to a market halt, or instrument expiry)
  • MM_PROTECTION = 5: market maker protection triggered
  • EXPIRED = 6: the order has expired
  • BELOW_MARGIN = 7: the order will bring the sub account below initial margin requirement
  • LIQUIDATION = 8: the sub account is liquidated (and all open orders are cancelled by Gravity)
  • SYSTEM_FAILOVER = 9: system failover resulting in loss of order state
  • CONFLICTING_SIGNATURE_HASH = 10: a previous order shares the same signature hash as your current order (typically when you submit the same signature twice)
  • OVERLAPPING_CLIENT_ORDER_ID = 11: an active order on your sub account shares the same clientOrderId
  • RFQ_CANCELLED = 12: the RFQ has been cancelled
  • AXE_CANCELLED = 13: the AXE has been cancelled
  • INVALID_ORDER = 14: the order payload contains one or more validation error (Trading Server will reply with a more specific error)
  • UNAUTHORISED = 15: the credentials used (userSession/apiKeySession/walletSignature) is not authorised to perform the action
  • FAIL_POST_ONLY = 16: when post-only order enters orderbook as a taker order
  • FAIL_REDUCE_ONLY = 17: when reduce-only order causes position size to increase
  • INVALID_TRIGGER_PRICE = 18: trigger price is on the wrong side of the trigger condition
  • RFQ_EXPIRED = 19: the RFQ has expired
  • AXE_EXPIRED = 20: the AXE has expired
  • FAIL_FOK = 21: the FOK order could not be fully matched
  • FAIL_AON = 22: the AON order could not be fully matched
  • SELF_MATCHED_SUBACCOUNT = 23: the order matched with another order from the same sub account
  • SIGNATURE_SIZE_EXCEEDED = 24: the signature size exceeds the maximum allowed size
  • SUB_ACCOUNT_NOT_FOUND = 25: the subaccount does not exist
  • BAD_SIGNATURE = 26: the signature is invalid
  • SIZE_NON_ZERO_ON_UNMACHED_LEG = 27: maker order size is non-zero on an unmatched leg
  • TRADE_SAME_SIDE = 28: the order trades with another order on the same side
  • TRADE_PRICE_DOES_NOT_CROSS = 29: the order trades with another order but the price does not cross
  • NO_LEG = 30: the order has no legs
  • MARKET_ORDER_ON_MAKER_SIDE = 31: market order on maker side
  • TIME_IN_FORCE_REQUIRE_TAKER = 32: time in force requires taker
  • ASSET_QUOTE_NOT_MATCHING = 33: asset quote not matching
  • MISSING_MARK_PRICE = 34: missing mark price
  • MISSING_INDEX_PRICE = 35: missing index price
  • SESSION_KEY_EXPIRED = 36: session key expired
  • DUPLICATE_LEG_ASSET = 37: duplicate leg asset
  • CHARGED_FEE_ABOVE_SIGNED_AMOUNT = 38: charged fee above signed amount
  • CHARGED_FEE_BELOW_MIN = 39: charged fee below minimum
  • NO_TRADE_PERMISSION = 40: no trade permission
  • NOT_MATCHED_AGAINS_TAKER_LEGS = 41: a maker order without any leg that is matched (size > 0) against at least 1 taker leg
  • ORDER_NOT_FULLY_MATCHED = 42: AON/FOK order not fully matched
  • ASSET_EXPIRED = 43: asset expired
  • NUM_LEGS_SIZE_MATCHED_MISMATCH = 44: number of legs and number of legs mismatch, eg: 2 legs, but sizeMatched is [1,2,3]

Name Lite Type Required Description
sub_account_id a uint256 true The subaccount initiating the request. 256-bit identifier
order_id i uint128 true A unique 128-bit identifier for the order, deterministically generated within the GRVT backend. It is the first 128-bits of keccak256(Order.signature.R, Order.signature.S)
client_order_id c uint32 false A unique identifier for the active order within a subaccount, specified by the client

Returns a list of Orders.

Order

Order is a typed payload used throughout the GRVT platform to express all orderbook, RFQ, and liquidation orders.

GRVT orders are capable of expressing both single-legged, and multi-legged orders by default. This increases the learning curve slightly but reduces customer integration load, since the order payload is used across all GRVT trading venues.

Given GRVT's trustless DeFi settlement model, the Order payload contains all the signatures, and authorizations required to trade the order on DeFi.

In order creation flows, do not supply the following fields, they are generated by GVRT:

  • order_id
  • state

All fields in the Order payload (except metadata, and state) are trustlessly enforced on the smart contract layer. GRVT leverages smart contract enforcement as much as possible to provide users with maximal trustlessness.

Name Lite Type Required Description
order_id i uint128 true A unique 128-bit identifier for the order, deterministically generated within the GRVT backend. It is the first 128-bits of keccak256(Order.signature.R, Order.signature.S)
sub_account_id a uint256 true The subaccount initiating the order. 256-bit identifier
is_market k bool true If the order is a market order
time_in_force f TimeInForce true See nested types below
limit_price l uint64 false Limit price for the limit order. ONLY APPLICABLE WHEN time_in_force = AON / FOK AND is_market = false
oco_limit_price o uint64 false When a one-cancels-other order is specified, this must contain the higher limit price. ONLY APPLICABLE WHEN in orderbook venue AND time_in_force = AON / FOK AND is_market = false
taker_fee t int32 true This is the maximum taker fee percentage the order sender is willing to pay for the order
maker_fee m int32 true This is the maximum maker fee percentage the order sender is willing to pay for the order. Negative for maker rebates
post_only p bool true If true, Order must be a maker order. It has to fill the orderbook instead of match it
reduce_only r bool true If true, Order must reduce the position size, or be cancelled
is_paying_base_currency b bool false A flag to indicate whether the full order is paying base currency or receiving base currency. ONLY APPLICABLE WHEN time_in_force = AON / FOK
legs l [OrderLeg] true The legs present in this order. The legs must be sorted by Derivative.Instrument/Underlying/BaseCurrency/Expiration/StrikePrice
signature g Signature true The signature approving this order
metadata d OrderMetadata false Order Metadata, ignored by the smart contract, and unsigned by the client
state s OrderState true The current state of the order, ignored by the smart contract, and unsigned by the client
TimeInForce

Four supported types of orders:

  • GTT - Good Till Time. Order lasts until it is filled, expired, or cancelled. Specify 0 in order.signature.expiration for GTC (non expiring) orders
  • IOC - Immediate Or Cancel. Order must be filled immediately. Any unfilled portion is immediately cancelled
  • AON - All Or None. Order must be executed in its entirety, or not at all. Otherwise identical to GTT
  • FOK - Fill Or Kill. Order must be executed in its entirety immediately, or immediately cancelled

TimeInForce Support across venues:

  • EXCHANGE - only supports (GTT, IOC, FOK)
  • RFQ - RFQ Maker only supports (GTT, AON), RFQ Taker only supports (FOK)

Smart Contract Guarantees:

  • PARTIAL EXECUTION = GTT / IOC - allows partial size execution on each leg
  • FULL EXECUTION = AON / FOK - only allows full size execution on all legs
  • TAKER ONLY = IOC / FOK - only allows taker orders
  • MAKER OR TAKER = GTT / AON - allows maker or taker orders

OrderLeg

An order can contain one or more legs. Each leg specifies a tradeable derivative instrument.

Name Lite Type Required Description
derivative d Derivative true The derivative contract to trade in this leg
num_contracts n uint64 true The total number of derivative contracts to trade in this leg, expressed in underlying asset decimal units
limit_price l uint64 false Limit price for the limit order. ONLY APPLICABLE WHEN time_in_force = GTT / IOC AND is_market = false
oco_limit_price o uint64 false When a one-cancels-other order is specified, this must contain the higher limit price. ONLY APPLICABLE WHEN time_in_force = GTT / IOC AND is_market = false
is_buying_contract b bool true Specifies if the order leg is a buy or sell
Derivative
Name Lite Type Required Description
instrument i uint8 true The derivative instrument. Values:
  • FUTURES = 1
  • PERPS = 2
  • OPTION_CALL = 3
  • OPTION_PUT = 4
underlying u uint8 true The underlying asset. Values:
  • BTC = 3
  • ETH = 4
quote q uint8 true The quote asset. Values:
  • USDC = 1
expiration e uint32 true Derivative expiration expressed in unix days
strike_price s uint64 true The strike price expressed in quote currency decimal units
Signature

This is an EIP-712 signature that can be used to validate that a specific private key has been used to sign a particular message.

Name Lite Type Required Description
r r uint256 true A (256-bit) number that represents signature r
s s uint256 true A (256-bit) number that represents signature s
v v uint8 true A (8-bit) number that represents signature v
expiration e uint64 true The time at which the signature expires in unix nanoseconds
OrderMetadata

Metadata contains user-supplied order metadata that is never transmitted to the GRVT smart contract. These fields are supported only by the GRVT backend, and the fields are not trustless in nature. Hence, fields in metadata are not required to be signed.

create_time should never be supplied directly by the user. This will be overwritten by GRVT backend if supplied.

All of the following fields are relevant in orderbook orders.

Name Lite Type Required Description
client_order_id c uint32 false A unique identifier for the active order within a subaccount, specified by the client
type t string false The order type used exclusively for more backend validation. Enum:
  • MARKET - A market order without a limit price
  • LIMIT - A limit order with a limit price
  • STOP_LOSS_MARKET - A market order with a stop loss trigger
  • STOP_LOSS_LIMIT - A limit order with a stop loss trigger
  • TAKE_PROFIT_MARKET - A market order with a take profit trigger
  • TAKE_PROFIT_LIMIT - A limit order with a take profit trigger
  • OCO_MARKET - A one-cancels-other market order with both stop loss and take profit triggers. The first trigger cancels the other
  • OCO_LIMIT - A one-cancels-other limit order with both stop loss and take profit triggers. The first trigger cancels the other
take_profit_trigger_condition p uint32 false The trigger condition for the take profit order. Enum:
  • INDEX = 1: Order is activated when the index price reaches the trigger price
stop_loss_trigger_condition l uint32 false The trigger condition for the stop loss order. Enum:
  • INDEX = 1: Order is activated when the index price reaches the trigger price
take_profit_trigger_price r uint64 false The trigger price for the take profit order
stop_loss_trigger_price o uint64 false The trigger price for the stop loss order
create_time e uint64 true Time at which the order was received by Gravity in unix nanoseconds
The nested fields have been marked as POST-LAUNCH additions

Do reach out to the Gravity Team, if these fields are important for you.

Name Lite Type Required Description
take_profit_trigger_condition t uint32 false The trigger condition for the take profit order. Enum:
  • INDEX = 1: Order is activated when the index price reaches the trigger price
  • LAST = 2: Order is activated when the last traded price reaches the trigger price
  • MARKET = 3: Order is activated when the mid market price reaches the trigger price
  • MARK = 4: Order is activated when the oracle mark price reaches the trigger price
  • TRAILING = 5: Keep track of the best mid price after purchase. If the mid price moves favourably, the best mid price is updated. Order is activated when mid price trails best mid price by a trailing value, expressed as price
  • TRAILING_PERCENT = 6: Keep track of the best mid price after purchase. If the mid price moves favourably, the best mid price is updated. Order is activated when mid price trails best mid price by X%, expressed as percentage
stop_loss_trigger_condition s uint32 false The trigger condition for the stop loss order. Enum:
  • INDEX = 1: Order is activated when the index price reaches the trigger price
  • LAST = 2: Order is activated when the last traded price reaches the trigger price
  • MARKET = 3: Order is activated when the mid market price reaches the trigger price
  • MARK = 4: Order is activated when the oracle mark price reaches the trigger price
  • TRAILING = 5: Keep track of the best mid price after purchase. If the mid price moves favourably, the best mid price is updated. Order is activated when mid price trails best mid price by a trailing value, expressed as price
  • TRAILING_PERCENT = 6: Keep track of the best mid price after purchase. If the mid price moves favourably, the best mid price is updated. Order is activated when mid price trails best mid price by X%, expressed as percentage
OrderState

State keeps track of the order's execution state. It is supplied by GRVT to help users keep track of order status, and executed size.

Name Lite Type Required Description
status s uint32 true The status of the order. Enum:
  • PENDING = 1 - not yet on the orderbook. Waiting for trigger condition
  • OPEN = 2 - on the orderbook. Could be partially filled
  • FILLED = 3 - fully filled
  • REJECTED = 4 - rejected by GRVT
  • CANCELLED = 5 - cancelled by user
num_contracts_left n [uint64] true The number of contracts available to be filled for each leg. Sorted by order.leg
update_time u uint64 true Time at which the order was updated by Gravity in unix nanoseconds

Example

{
    "sub_account_id": "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", // uint256 = 64 bytes
    "kind": ["PERPETUAL", "FUTURE"],
}

Example

{
    "orders": [
        {
            "order_id": "0x0123456789abcdef0123456789abcdef", // uint128 = 32 bytes
            "sub_account_id": 1,
            "is_market": false,
            "time_in_force": "GTT",
            "limit_price": "1000000000", // uint64
            "oco_limit_price": "1100000000", // uint64
            "taker_fee_percentage_cap": 500, // 5bps uint32
            "maker_fee_percentage_cap": 300, // 3bps uint32
            "post_only": true,
            "reduce_only": false,
            "is_paying_base_currency": true,
            "legs": [
                {
                    "instrument": "BTC_USDT_Perp",
                    "size": 10000000, // uint64
                    "limit_price": 1000000, // uint64
                    "oco_limit_price": 10000000, // uint64
                    "is_buying_asset": true
                }
            ],
            "signature": {
                "r": "0x54730fcf60f37072926ba182d17e55e21104fbc22886d876a7e8b191b2d456f", // uint128 = 64 bytes
                "s": "0x1f32f41a809b2f2b888bddc2bdbf5ef709403a00d4e5e23dbaef09e55130464", // uint128 = 64 bytes
                "v": 27, // uint8
                "expiration": "1689526957000000" // uint64
            },
            "metadata": {
                "client_order_id": 2183798, // uint32
                "type": "OCO_LIMIT",
                "take_profit_trigger_condition": 1, // INDEX uint32
                "stop_loss_trigger_condition": 1, // INDEX uint32
                "take_profit_trigger_price": "1070000000", // uint64
                "stop_loss_trigger_price": "1020000000" // uint64
            },
            "state": {
                "status": 2, // OPEN uint32
                "reject_reason": 0, // NONE uint32
                "num_contracts_left": "500000000", // uint64
                "book_size": [1, 2, 3, 5], // []uint64
                "traded_size": [1, 2, 3, 5], // []uint64
                "update_time": 1000000000
            }
        }
    ]
}
Code Number Description
Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Order History

Retrieves all historical orders for the account, with the below query parameters.

Historical data is served through our DB and may not match new data in flight.

This has been marked as a POST-ALPHA feature

Please bear with us while we make this available

FULL ENDPOINT: full/v1/order_history
LITE ENDPOINT: lite/v1/order_history
ApiOrderHistoryRequest
Name Lite Type Description
sub_account_id sa uint64 The subaccount ID to filter by
kind k [Kind] The kind filter to apply. If nil, this defaults to all kinds. Otherwise, only entries matching the filter will be returned
underlying u [Currency] The underlying filter to apply. If nil, this defaults to all underlyings. Otherwise, only entries matching the filter will be returned
quote q [Currency] The quote filter to apply. If nil, this defaults to all quotes. Otherwise, only entries matching the filter will be returned
expiration e [int64] The expiration time to apply in nanoseconds. If nil, this defaults to all expirations. Otherwise, only entries matching the filter will be returned
strike_price sp [uint64] The strike price to apply. If nil, this defaults to all strike prices. Otherwise, only entries matching the filter will be returned
limit l uint32 The limit to query for. Defaults to 500; Max 1000
cursor c string The cursor to indicate when to start the query from
Kind

The list of asset kinds that are supported on the GRVT exchange
Kind:

  • PERPETUAL = 1: the perpetual asset kind
  • FUTURE = 2: the future asset kind
  • CALL = 3: the call option asset kind
  • PUT = 4: the put option asset kind

Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

ApiOrderHistoryResponse
Name Lite Type Description
total t uint32 The total number of orders matching the request filter
next n string The cursor to indicate when to start the next query from
orders o [Order] The Open Orders matching the request filter
Order

Order is a typed payload used throughout the GRVT platform to express all orderbook, RFQ, and liquidation orders.
GRVT orders are capable of expressing both single-legged, and multi-legged orders by default.
This increases the learning curve slightly but reduces overall integration load, since the order payload is used across all GRVT trading venues.
Given GRVT's trustless settlement model, the Order payload also carries the signature, required to trade the order on our ZKSync Hyperchain.

All fields in the Order payload (except id, metadata, and state) are trustlessly enforced on our Hyperchain.
This minimizes the amount of trust users have to offer to GRVT

Name Lite Type Description
order_id oi uint128 [Filled by GRVT Backend] A unique 128-bit identifier for the order, deterministically generated within the GRVT backend
sub_account_id sa uint64 The subaccount initiating the order
is_market im bool If the order is a market order
Market Orders do not have a limit price, and are always executed according to the maker order price.
Market Orders must always be taker orders
time_in_force ti TimeInForce Four supported types of orders: GTT, IOC, AON, FOK:

  • PARTIAL EXECUTION = GTT / IOC - allows partial size execution on each leg

  • FULL EXECUTION = AON / FOK - only allows full size execution on all legs

  • TAKER ONLY = IOC / FOK - only allows taker orders

  • MAKER OR TAKER = GTT / AON - allows maker or taker orders

Exchange only supports (GTT, IOC, FOK)
RFQ Maker only supports (GTT, AON), RFQ Taker only supports (FOK)
taker_fee_percentage_cap tf int32 The taker fee percentage cap signed by the order.
This is the maximum taker fee percentage the order sender is willing to pay for the order.
Expressed in 1/100th of a basis point. Eg. 100 = 1bps, 10,000 = 1%
maker_fee_percentage_cap mf int32 Same as TakerFeePercentageCap, but for the maker fee. Negative for maker rebates
post_only po bool If True, Order must be a maker order. It has to fill the orderbook instead of match it.
If False, Order can be either a maker or taker order.

reduce_only ro bool If True, Order must reduce the position size, or be cancelled
legs l [OrderLeg] The legs present in this order
The legs must be sorted by Asset.Instrument/Underlying/Quote/Expiration/StrikePrice
signature s Signature The signature approving this order
metadata m OrderMetadata Order Metadata, ignored by the smart contract, and unsigned by the client
state s1 OrderState [Filled by GRVT Backend] The current state of the order, ignored by the smart contract, and unsigned by the client
TimeInForce
Must Fill All Can Fill Partial
Must Fill Immediately FOK IOC
Can Fill Till Time AON GTC


TimeInForce:

  • GOOD_TILL_TIME = 1: GTT - Remains open until it is cancelled, or expired
  • ALL_OR_NONE = 2: AON - Either fill the whole order or none of it (Block Trades Only)
  • IMMEDIATE_OR_CANCEL = 3: IOC - Fill the order as much as possible, when hitting the orderbook. Then cancel it
  • FILL_OR_KILL = 4: FOK - Both AoN and IoC. Either fill the full order when hitting the orderbook, or cancel it

OrderLeg
Name Lite Type Description
instrument i string The instrument to trade in this leg
size s uint64 The total number of assets to trade in this leg, expressed in underlying asset decimal units.
limit_price lp uint64 The limit price of the order leg, expressed in 9 decimals.
This is the total amount of base currency to pay/receive for all legs.
oco_limit_price ol uint64 If a OCO order is specified, this must contain the other limit price
User must sign both limit prices. Depending on which trigger condition is activated, a different limit price is used
The smart contract will always validate both limit prices, by arranging them in ascending order
is_buying_asset ib bool Specifies if the order leg is a buy or sell
Signature
Name Lite Type Description
signer s uint256 The address (public key) of the wallet signing the payload
r r uint256 Signature R
s s1 uint256 Signature S
v v uint8 Signature V
expiration e Timestamp Timestamp after which this signature expires, expressed in unix nanoseconds. Must be capped at 30 days
nonce n uint32 Users can randomly generate this value, used as a signature deconflicting key.
ie. You can send the same exact instruction twice with different nonces.
When the same nonce is used, the same payload will generate the same signature.
Our system will consider the payload a duplicate, and ignore it.
OrderMetadata

Metadata fields are used to support Backend only operations. These operations are not trustless by nature.
Hence, fields in here are never signed, and is never transmitted to the smart contract.

Name Lite Type Description
client_order_id co uint32 A unique identifier for the active order within a subaccount, specified by the client
This is used to identify the order in the client's system
This field can be used for order amendment/cancellation, but has no bearing on the smart contract layer
This field will not be propagated to the smart contract, and should not be signed by the client
This value must be unique for all active orders in a subaccount, or amendment/cancellation will not work as expected
Gravity UI will generate a random clientOrderID for each order in the range [0, 2^31 - 1]
To prevent any conflicts, client machines should generate a random clientOrderID in the range [2^31, 2^32 - 1]

When GRVT Backend receives an order with an overlapping clientOrderID, we will reject the order with rejectReason set to overlappingClientOrderId
create_time ct Timestamp [Filled by GRVT Backend] Time at which the order was received by GRVT in unix nanoseconds
OrderState
Name Lite Type Description
status s OrderStatus The status of the order
reject_reason rr OrderRejectReason The reason for rejection or cancellation
book_size bs [uint64] The number of assets available for orderbook/RFQ matching. Sorted in same order as Order.Legs
traded_size ts [uint64] The total number of assets traded. Sorted in same order as Order.Legs
update_time ut Timestamp Time at which the order was updated by GRVT, expressed in unix nanoseconds
OrderStatus

OrderStatus:

  • PENDING = 1: Order is waiting for Trigger Condition to be hit
  • OPEN = 2: Order is actively matching on the orderbook, could be unfilled or partially filled
  • FILLED = 3: Order is fully filled and hence closed
  • REJECTED = 4: Order is rejected by GRVT Backend since if fails a particular check (See OrderRejectReason)
  • CANCELLED = 5: Order is cancelled by the user using one of the supported APIs (See OrderRejectReason)

OrderRejectReason

OrderRejectReason:

  • CLIENT_CANCEL = 1: client called a Cancel API
  • CLIENT_BULK_CANCEL = 2: client called a Bulk Cancel API
  • CLIENT_SESSION_END = 3: client called a Session Cancel API, or set the WebSocket connection to 'cancelOrdersOnTerminate'
  • INSTRUMENT_DEACTIVATED = 4: instrument is no longer tradable on Gravity. (typically due to a market halt, or instrument expiry)
  • MM_PROTECTION = 5: market maker protection triggered
  • EXPIRED = 6: the order has expired
  • BELOW_MARGIN = 7: the order will bring the sub account below initial margin requirement
  • LIQUIDATION = 8: the sub account is liquidated (and all open orders are cancelled by Gravity)
  • SYSTEM_FAILOVER = 9: system failover resulting in loss of order state
  • CONFLICTING_SIGNATURE_HASH = 10: a previous order shares the same signature hash as your current order (typically when you submit the same signature twice)
  • OVERLAPPING_CLIENT_ORDER_ID = 11: an active order on your sub account shares the same clientOrderId
  • RFQ_CANCELLED = 12: the RFQ has been cancelled
  • AXE_CANCELLED = 13: the AXE has been cancelled
  • INVALID_ORDER = 14: the order payload contains one or more validation error (Trading Server will reply with a more specific error)
  • UNAUTHORISED = 15: the credentials used (userSession/apiKeySession/walletSignature) is not authorised to perform the action
  • FAIL_POST_ONLY = 16: when post-only order enters orderbook as a taker order
  • FAIL_REDUCE_ONLY = 17: when reduce-only order causes position size to increase
  • INVALID_TRIGGER_PRICE = 18: trigger price is on the wrong side of the trigger condition
  • RFQ_EXPIRED = 19: the RFQ has expired
  • AXE_EXPIRED = 20: the AXE has expired
  • FAIL_FOK = 21: the FOK order could not be fully matched
  • FAIL_AON = 22: the AON order could not be fully matched
  • SELF_MATCHED_SUBACCOUNT = 23: the order matched with another order from the same sub account
  • SIGNATURE_SIZE_EXCEEDED = 24: the signature size exceeds the maximum allowed size
  • SUB_ACCOUNT_NOT_FOUND = 25: the subaccount does not exist
  • BAD_SIGNATURE = 26: the signature is invalid
  • SIZE_NON_ZERO_ON_UNMACHED_LEG = 27: maker order size is non-zero on an unmatched leg
  • TRADE_SAME_SIDE = 28: the order trades with another order on the same side
  • TRADE_PRICE_DOES_NOT_CROSS = 29: the order trades with another order but the price does not cross
  • NO_LEG = 30: the order has no legs
  • MARKET_ORDER_ON_MAKER_SIDE = 31: market order on maker side
  • TIME_IN_FORCE_REQUIRE_TAKER = 32: time in force requires taker
  • ASSET_QUOTE_NOT_MATCHING = 33: asset quote not matching
  • MISSING_MARK_PRICE = 34: missing mark price
  • MISSING_INDEX_PRICE = 35: missing index price
  • SESSION_KEY_EXPIRED = 36: session key expired
  • DUPLICATE_LEG_ASSET = 37: duplicate leg asset
  • CHARGED_FEE_ABOVE_SIGNED_AMOUNT = 38: charged fee above signed amount
  • CHARGED_FEE_BELOW_MIN = 39: charged fee below minimum
  • NO_TRADE_PERMISSION = 40: no trade permission
  • NOT_MATCHED_AGAINS_TAKER_LEGS = 41: a maker order without any leg that is matched (size > 0) against at least 1 taker leg
  • ORDER_NOT_FULLY_MATCHED = 42: AON/FOK order not fully matched
  • ASSET_EXPIRED = 43: asset expired
  • NUM_LEGS_SIZE_MATCHED_MISMATCH = 44: number of legs and number of legs mismatch, eg: 2 legs, but sizeMatched is [1,2,3]

Example

{
    "sub_account_id": "1",
    "order_id": "0x0123456789abcdef0123456789abcdef", // uint128 = 32 bytes
    "kind": [], // all kinds
    "underlying": [], // all underlyings
    "quote": [],
    "limit": 1,
    "cursor": "19230913"
}

Example

{
    "orders": [
        {
            "order_id": "0x0123456789abcdef0123456789abcdef", // uint128 = 32 bytes
            "sub_account_id": 1,
            "is_market": false,
            "time_in_force": "GTT",
            "limit_price": "1000000000", // uint64
            "oco_limit_price": "1100000000", // uint64
            "taker_fee_percentage_cap": 500, // 5bps uint32
            "maker_fee_percentage_cap": 300, // 3bps uint32
            "post_only": true,
            "reduce_only": false,
            "is_paying_base_currency": true,
            "legs": [
                {
                    "instrument": "BTC_USDT_Perp",
                    "size": 10000000, // uint64
                    "limit_price": 1000000, // uint64
                    "oco_limit_price": 10000000, // uint64
                    "is_buying_asset": true
                }
            ],
            "signature": {
                "r": "0x54730fcf60f37072926ba182d17e55e21104fbc22886d876a7e8b191b2d456f", // uint128 = 64 bytes
                "s": "0x1f32f41a809b2f2b888bddc2bdbf5ef709403a00d4e5e23dbaef09e55130464", // uint128 = 64 bytes
                "v": 27, // uint8
                "expiration": "1689526957000000" // uint64
            },
            "metadata": {
                "client_order_id": 2183798, // uint32
                "type": "OCO_LIMIT",
                "take_profit_trigger_condition": 1, // INDEX uint32
                "stop_loss_trigger_condition": 1, // INDEX uint32
                "take_profit_trigger_price": "1070000000", // uint64
                "stop_loss_trigger_price": "1020000000" // uint64
            },
            "state": {
                "status": 2, // OPEN uint32
                "reject_reason": 0, // NONE uint32
                "num_contracts_left": "500000000", // uint64
                "book_size": [1, 2, 3, 5], // []uint64
                "traded_size": [1, 2, 3, 5], // []uint64
                "update_time": 1000000000
            }
        }
    ]
}
Code Number Description
INVALID_TIME_RANGE 1002 The time range specified is invalid
INVALID_LIMIT 1004 The limit supplied is out of range
INVALID_CURSOR 1005 The cursor supplied is invalid
ORDER_ID_NOT_FOUND 2101 The order_id supplied is not found
CLIENT_ORDER_ID_NOT_FOUND 2102 The client_order_id supplied is not found
Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Transfers

Deposit

FULL ENDPOINT: full/v1/deposit
LITE ENDPOINT: lite/v1/deposit
ApiDepositRequest

GRVT runs on a ZKSync Hyperchain which settles directly onto Ethereum.
To Deposit funds from your L1 wallet into a GRVT SubAccount, you will be required to submit a deposit transaction directly to Ethereum.
GRVT's bridge verifier will scan Ethereum from time to time. Once it receives proof that your deposit has been confirmed on Ethereum, it will initiate the deposit process.

This current payload is used for alpha testing only.

Name Lite Type Description
to_account_id ta Address The main account to deposit into
token_currency tc Currency The token currency to deposit
num_tokens nt uint64 The number of tokens to deposit, quoted in token_currency decimals
Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

AckResponse

This endpoint only supports ACK responses. See Error code section for more details. This will either return true, or a relevant error code.

Name Lite Type Description
acknowledgement a bool Gravity has acknowledged that the request has been successfully received and it will process it in the backend

Example

{
    "to_account_id": "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", // uint256 = 64 bytes
    "token_currency": "USDT",
    "num_tokens": "2387498374987",
}

Example

{
    "code": 3,
    "msg":"PERMISSION_DENIED"
}

UNDER DEVELOPMENT

Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Deposit History

FULL ENDPOINT: full/v1/deposit_history
LITE ENDPOINT: lite/v1/deposit_history
DepositHistoryRequest

The request to get the historical deposits of an account
The history is returned in reverse chronological order

Name Lite Type Description
limit l uint32 The limit to query for. Defaults to 500; Max 1000
cursor c uint64 The cursor to indicate when to start the query from
token_currency tc [Currency] The token currency to query for, if nil or empty, return all deposits. Otherwise, only entries matching the filter will be returned
start_time st Timestamp The start time to query for in unix nanoseconds
end_time et Timestamp The end time to query for in unix nanoseconds
Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

DepositHistoryResponse
Name Lite Type Description
total t uint32 The total number of deposits matching the request account
next n uint64 The cursor to indicate when to start the next query from
results r [DepositHistory] The deposit history matching the request account
DepositHistory
Name Lite Type Description
tx_id ti uint64 The transaction ID of the deposit
from_eth_address fe uint256 The ethereum address where the deposit originates
to_account_id ta Address The account to deposit into
token_currency tc Currency The token currency to deposit
num_tokens nt uint64 The number of tokens to deposit
signature s Signature The signature of the deposit (supplied on L1 by the user)
event_time et Timestamp The timestamp of the deposit in unix nanoseconds
Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

Signature
Name Lite Type Description
signer s uint256 The address (public key) of the wallet signing the payload
r r uint256 Signature R
s s1 uint256 Signature S
v v uint8 Signature V
expiration e Timestamp Timestamp after which this signature expires, expressed in unix nanoseconds. Must be capped at 30 days
nonce n uint32 Users can randomly generate this value, used as a signature deconflicting key.
ie. You can send the same exact instruction twice with different nonces.
When the same nonce is used, the same payload will generate the same signature.
Our system will consider the payload a duplicate, and ignore it.

Example

{
    "limit": 50,
}

Example

{
    "results": [
        {
           "tx_id": 1,
            "from_eth_address": "0xbeeE570f66116b7350Cd227824941c1d120411DE", // uint256,
            "to_account_id": "0xC0367b2462A518f3270E6F639469f0283231c75E", // uint256,
            "to_sub_account_id": 123124, // uint64
            "token_currency": 3, //usdt
            "signature": {
                "r": "0x54730fcf60f37072926ba182d17e55e21104fbc22886d876a7e8b191b2d456f", // uint128 = 64 bytes
                "s": "0x1f32f41a809b2f2b888bddc2bdbf5ef709403a00d4e5e23dbaef09e55130464", // uint128 = 64 bytes
                "v": 27, // uint8
                "expiration": "1689526957000000" // uint64
            },
            "num_tokens": 100000000000 // uint256,
            "event_time": 1610000000 // uint64,
        }
    ]
}

UNDER DEVELOPMENT

Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Transfer

Transfer base currency asset between any two L2 accounts. See the API Authorizations section on the main page on the various permissions required to use this endpoint.

FULL ENDPOINT: full/v1/transfer
LITE ENDPOINT: lite/v1/transfer
ApiTransferRequest

This API allows you to transfer funds in multiple different ways

  • Between SubAccounts within your Main Account
  • Between your MainAccount and your SubAccounts
  • To other MainAccounts that you have previously allowlisted

Name Lite Type Description
from_account_id fa Address The main account to transfer from
from_sub_account_id fs uint64 The subaccount to transfer from (0 if transferring from main account)
to_account_id ta Address The main account to deposit into
to_sub_account_id ts uint64 The subaccount to transfer to (0 if transferring to main account)
token_currency tc Currency The token currency to transfer
num_tokens nt uint64 The number of tokens to transfer, quoted in tokenCurrency decimal units
signature s Signature The signature of the transfer
Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

Signature
Name Lite Type Description
signer s uint256 The address (public key) of the wallet signing the payload
r r uint256 Signature R
s s1 uint256 Signature S
v v uint8 Signature V
expiration e Timestamp Timestamp after which this signature expires, expressed in unix nanoseconds. Must be capped at 30 days
nonce n uint32 Users can randomly generate this value, used as a signature deconflicting key.
ie. You can send the same exact instruction twice with different nonces.
When the same nonce is used, the same payload will generate the same signature.
Our system will consider the payload a duplicate, and ignore it.
AckResponse

This endpoint only supports ACK responses. See Error code section for more details. This will either return true, or a relevant error code.

Name Lite Type Description
acknowledgement a bool Gravity has acknowledged that the request has been successfully received and it will process it in the backend

Example

{
    "from_account_id": "0x42a9616dd84637635f1bd07b8723008a0b83a0b4b0da4f5a50c55562009d253",
    "from_sub_account_id": "9309829342914403545",
    "to_account_id": "0x42a9616dd84637635f1bd07b8723008a0b83a0b4b0da4f5a50c55562009d253",
    "to_sub_account_id": "6091063652223914538",
    "token_currency": "USTC",
    "num_tokens": "7758176404715800194",
    "signature": {
        "r": "0x31e04b05b5090882a8e17ed91371ea267547dddecde98f8821e5ca65ab76451",
        "s": "0x342f351e4253945f76b9de058d92e18fc4e47e37515ad9ac750cbe046e921c2",
        "v": 27,
    },
}

Example

{
    "code": 3,
    "msg":"PERMISSION_DENIED"
}

UNDER DEVELOPMENT

Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Transfer History

FULL ENDPOINT: full/v1/transfer_history
LITE ENDPOINT: lite/v1/transfer_history
TransferHistoryRequest

The request to get the historical transfers of an account
The history is returned in reverse chronological order

Name Lite Type Description
limit l uint32 The limit to query for. Defaults to 500; Max 1000
cursor c uint64 The cursor to indicate when to start the query from
token_currency tc [Currency] The token currency to query for, if nil or empty, return all transfers. Otherwise, only entries matching the filter will be returned
start_time st Timestamp The start time to query for in unix nanoseconds
end_time et Timestamp The end time to query for in unix nanoseconds
Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

TransferHistoryResponse
Name Lite Type Description
total t uint32 The total number of transfers matching the request account
next n uint64 The cursor to indicate when to start the next query from
results r [TransferHistory] The transfer history matching the request account
TransferHistory
Name Lite Type Description
tx_id ti uint64 The transaction ID of the transfer
from_account_id fa Address The account to transfer from
from_sub_account_id fs uint64 The subaccount to transfer from (0 if transferring from main account)
to_account_id ta Address The account to deposit into
to_sub_account_id ts uint64 The subaccount to transfer to (0 if transferring to main account)
token_currency tc Currency The token currency to transfer
num_tokens nt uint64 The number of tokens to transfer
signature s Signature The signature of the transfer
event_time et Timestamp The timestamp of the transfer in unix nanoseconds
Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

Signature
Name Lite Type Description
signer s uint256 The address (public key) of the wallet signing the payload
r r uint256 Signature R
s s1 uint256 Signature S
v v uint8 Signature V
expiration e Timestamp Timestamp after which this signature expires, expressed in unix nanoseconds. Must be capped at 30 days
nonce n uint32 Users can randomly generate this value, used as a signature deconflicting key.
ie. You can send the same exact instruction twice with different nonces.
When the same nonce is used, the same payload will generate the same signature.
Our system will consider the payload a duplicate, and ignore it.

Example

{
    "limit": 50,
}

Example

{
    "total": 1,
    "results": [
        {
          "tx_id": 1,
          "from_eth_address": "0xbeeE570f66116b7350Cd227824941c1d120411DE", // uint256,
          "from_sub_account_id": 123123, // uint64
          "to_account_id": "0xC0367b2462A518f3270E6F639469f0283231c75E", // uint256,
          "to_sub_account_id": 123124, // uint64
          "token_currency": 3, //usdt
          "signature": {
              "r": "0x54730fcf60f37072926ba182d17e55e21104fbc22886d876a7e8b191b2d456f", // uint128 = 64 bytes
              "s": "0x1f32f41a809b2f2b888bddc2bdbf5ef709403a00d4e5e23dbaef09e55130464", // uint128 = 64 bytes
              "v": 27, // uint8
              "expiration": "1689526957000000" // uint64
          },
          "num_tokens": 100000000000 // uint256,
        }
    ]
}

UNDER DEVELOPMENT

Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Withdrawal

If not withdrawing the entirety of your balance, there is a minimum withdrawal amount. Currently that amount is 100 USDC

FULL ENDPOINT: full/v1/withdrawal
LITE ENDPOINT: lite/v1/withdrawal
ApiWithdrawalRequest

Leverage this API to initialize a withdrawal from GRVT's Hyperchain onto Ethereum.
Do take note that the bridging process does take time. The GRVT UI will help you keep track of bridging progress, and notify you once its complete.

If not withdrawing the entirety of your balance, there is a minimum withdrawal amount. Currently that amount is 100 USDC.
Withdrawal fees also apply to cover the cost of the Ethereum transaction.
Note that your funds will always remain in self-custory throughout the withdrawal process. At no stage does GRVT gain control over your funds.

Name Lite Type Description
from_account_id fa Address The main account to withdraw from
to_eth_address te Address The Ethereum wallet to withdraw into
token_currency tc Currency The token currency to withdraw
num_tokens nt uint64 The number of tokens to withdraw, quoted in tokenCurrency decimal units
signature s Signature The signature of the withdrawal
Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

Signature
Name Lite Type Description
signer s uint256 The address (public key) of the wallet signing the payload
r r uint256 Signature R
s s1 uint256 Signature S
v v uint8 Signature V
expiration e Timestamp Timestamp after which this signature expires, expressed in unix nanoseconds. Must be capped at 30 days
nonce n uint32 Users can randomly generate this value, used as a signature deconflicting key.
ie. You can send the same exact instruction twice with different nonces.
When the same nonce is used, the same payload will generate the same signature.
Our system will consider the payload a duplicate, and ignore it.
AckResponse

This endpoint only supports ACK responses. See Error code section for more details. This will either return true, or a relevant error code.

Name Lite Type Description
acknowledgement a bool Gravity has acknowledged that the request has been successfully received and it will process it in the backend

Example

{
    "from_account_id": "0x42a9616dd84637635f1bd07b8723008a0b83a0b4b0da4f5a50c55562009d253",
    "to_eth_address": "0x42a9616dd84637635f1bd07b8723008a0b83a0b4b0da4f5a50c55562009d253",
    "token_currency": "USTC",
    "num_tokens": "7758176404715800194",
    "signature": {
        "r": "0x31e04b05b5090882a8e17ed91371ea267547dddecde98f8821e5ca65ab76451",
        "s": "0x342f351e4253945f76b9de058d92e18fc4e47e37515ad9ac750cbe046e921c2",
        "v": 27,
    },
}

Example

{
    "code": 3,
    "msg":"PERMISSION_DENIED"
}

UNDER DEVELOPMENT

Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Withdrawal History

FULL ENDPOINT: full/v1/withdrawal_history
LITE ENDPOINT: lite/v1/withdrawal_history
WithdrawalHistoryRequest

The request to get the historical withdrawals of an account
The history is returned in reverse chronological order

Name Lite Type Description
limit l uint32 The limit to query for. Defaults to 500; Max 1000
cursor c uint64 The cursor to indicate when to start the query from
token_currency tc [Currency] The token currency to query for, if nil or empty, return all withdrawals. Otherwise, only entries matching the filter will be returned
start_time st Timestamp The start time to query for in unix nanoseconds
end_time et Timestamp The end time to query for in unix nanoseconds
Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

WithdrawalHistoryResponse
Name Lite Type Description
total t uint32 The total number of withdrawals matching the request account
next n uint64 The cursor to indicate when to start the next query from
results r [WithdrawalHistory] The withdrawals history matching the request account
WithdrawalHistory
Name Lite Type Description
tx_id ti uint64 The transaction ID of the withdrawal
from_account_id fa Address The subaccount to withdraw from
to_eth_address te uint256 The ethereum address to withdraw to
token_currency tc Currency The token currency to withdraw
num_tokens nt uint64 The number of tokens to withdraw
signature s Signature The signature of the withdrawal
event_time et Timestamp The timestamp of the withdrawal in unix nanoseconds
Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

Signature
Name Lite Type Description
signer s uint256 The address (public key) of the wallet signing the payload
r r uint256 Signature R
s s1 uint256 Signature S
v v uint8 Signature V
expiration e Timestamp Timestamp after which this signature expires, expressed in unix nanoseconds. Must be capped at 30 days
nonce n uint32 Users can randomly generate this value, used as a signature deconflicting key.
ie. You can send the same exact instruction twice with different nonces.
When the same nonce is used, the same payload will generate the same signature.
Our system will consider the payload a duplicate, and ignore it.

Example

{
    "limit": 50,
}

Example

{
    "results": [
        {
          "tx_id": 1,
          "from_account_id": "0xbeeE570f66116b7350Cd227824941c1d120411DE", // uint256,
          "to_eth_address": "0xC0367b2462A518f3270E6F639469f0283231c75E", // uint256,
          "to_sub_account_id": 123124, // uint64
          "token_currency": 3, //usdt
          "signature": {
              "r": "0x54730fcf60f37072926ba182d17e55e21104fbc22886d876a7e8b191b2d456f", // uint128 = 64 bytes
              "s": "0x1f32f41a809b2f2b888bddc2bdbf5ef709403a00d4e5e23dbaef09e55130464", // uint128 = 64 bytes
              "v": 27, // uint8
              "expiration": "1689526957000000" // uint64
          },
          "num_tokens": 100000000000 // uint256,
          "event_time": 1610000000 // uint64,
        }
    ]
}

UNDER DEVELOPMENT

Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Account

Positions

Query for position details.

FULL ENDPOINT: full/v1/positions
LITE ENDPOINT: lite/v1/positions
ApiPositionsRequest
Name Lite Type Description
sub_account_id sa uint64 The sub account ID to request for
kind k [Kind] The kind filter to apply. If nil, this defaults to all kinds. Otherwise, only entries matching the filter will be returned
underlying u [Currency] The underlying filter to apply. If nil, this defaults to all underlyings. Otherwise, only entries matching the filter will be returned
quote q [Currency] The quote filter to apply. If nil, this defaults to all quotes. Otherwise, only entries matching the filter will be returned
Kind

The list of asset kinds that are supported on the GRVT exchange
Kind:

  • PERPETUAL = 1: the perpetual asset kind
  • FUTURE = 2: the future asset kind
  • CALL = 3: the call option asset kind
  • PUT = 4: the put option asset kind

Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

ApiPositionsResponse
Name Lite Type Description
results r [Positions] The positions matching the request filter
Positions
Name Lite Type Description
event_time et Timestamp Time at which the event was emitted in unix nanoseconds
sub_account_id sa uint64 The sub account ID that participated in the trade
instrument i string The instrument being represented
balance b int64 The balance of the position, expressed in underlying asset decimal units. Negative for short positions
value v int64 The value of the position, negative for short assets, expressed in quote asset decimal units
entry_price ep uint64 The entry price of the position, expressed in 9 decimals
Whenever increasing the balance of a position, the entry price is updated to the new average entry price
newEntryPrice = (oldEntryPrice * oldBalance + tradePrice * tradeBalance) / (oldBalance + tradeBalance)
exit_price ep1 uint64 The exit price of the position, expressed in 9 decimals
Whenever decreasing the balance of a position, the exit price is updated to the new average exit price
newExitPrice = (oldExitPrice * oldExitBalance + tradePrice * tradeBalance) / (oldExitBalance + tradeBalance)
mark_price mp uint64 The mark price of the position, expressed in 9 decimals
unrealized_pnl up int64 The unrealized PnL of the position, expressed in quote asset decimal units
unrealizedPnl = (markPrice - entryPrice) * balance
realized_pnl rp int64 The realized PnL of the position, expressed in quote asset decimal units
realizedPnl = (exitPrice - entryPrice) * exitBalance
pnl p int64 The total PnL of the position, expressed in quote asset decimal units
totalPnl = realizedPnl + unrealizedPnl
roi r float32 The ROI of the position, expressed as a percentage
roi = (pnl / (entryPrice * balance)) * 100

Example

{
    "sa": "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", // uint256 = 64 bytes
}

Example

{
    "result": 
    {
        "sub_account_id": "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", // uint128 = 64 bytes
        "margin_type": 3, // PORTFOLIO_CROSS_MARGIN uint32
        "quote_currency": 1, // USDC uint32
        "pending_deposit": "450000000", // uint64
        "derivative_positions": [
            {
                "derivative": {
                    "instrument": 3, // CALL uint8
                    "underlying": 4, // ETH uint8
                    "quote": 1, // USDC uint8
                    "expiration": "1689526957000000", // uint64
                    "strike_price": "1000000000", // uint64
                },
                "contract_balance": "1000000000", // uint64
                "unrealized_pnl":"4452000000"
            },
            {
                "derivative": {
                    "instrument": 4, // PUT uint8
                    "underlying": 4, // ETH uint8
                    "quote": 1, // USDC uint8
                    "expiration": "1689529888000000", // uint64
                    "strike_price": "1000000000", // uint64
                },
                "contract_balance": "-1000000000", // uint64
                "unrealized_pnl":"1000000000"
            }
        ],
        "unrealized_pnl": "3452000000", // uint64
        "initial_margin": ["1269146471088859254", 0.45],
        "maintanence_margin": ["269146471088859254", 0.08],
        "current_margin": ["1569146471088859254", 0.56],
        "is_under_liquidation": false
    }
}
Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Sub Account Summary

Query for sub-account details, including base currency balance, all derivative positions, margin levels, and unrealized P&L.

FULL ENDPOINT: full/v1/account_summary
LITE ENDPOINT: lite/v1/account_summary
ApiSubAccountSummaryRequest
Name Lite Type Description
sub_account_id sa uint64 The subaccount ID to filter by
ApiSubAccountSummaryResponse
Name Lite Type Description
results r SubAccount The sub account matching the request sub account
SubAccount
Name Lite Type Description
event_time et Timestamp Time at which the event was emitted in unix nanoseconds
sub_account_id sa uint64 The sub account ID this entry refers to
margin_type mt MarginType The type of margin algorithm this subaccount uses
quote_currency qc Currency The Quote Currency that this Sub Account is denominated in
This subaccount can only open derivative positions denominated in this quote currency
All other assets are converted to this quote currency for the purpose of calculating margin
In the future, when users select a Multi-Currency Margin Type, this will be USD
unrealized_pnl up int64 The total unrealized PnL of all positions owned by this subaccount, denominated in quote currency decimal units
total_value tv int64 The total value across all spot assets, or in other words, the current margin
initial_margin im uint64 The initial margin requirement of all positions owned by this vault, denominated in quote currency decimal units
maintanence_margin mm uint64 The maintanence margin requirement of all positions owned by this vault, denominated in quote currency decimal units
available_margin am int64 The margin available for withdrawal, denominated in quote currency decimal units
spot_balances sb [SpotBalance] The list of spot assets owned by this sub account, and their balances
positions p [Positions] The list of positions owned by this sub account
MarginType

MarginType:

  • SIMPLE_CROSS_MARGIN = 2: Simple Cross Margin Mode: all assets have a predictable margin impact, the whole subaccount shares a single margin
  • PORTFOLIO_CROSS_MARGIN = 3: Portfolio Cross Margin Mode: asset margin impact is analysed on portfolio level, the whole subaccount shares a single margin

Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

SpotBalance
Name Lite Type Description
currency c Currency The currency you hold a spot balance in
balance b uint64 The balance of the asset, expressed in underlying asset decimal units
Must take into account the value of all positions with this quote asset
ie. for USDT denominated subaccounts, this is is identical to total balance
Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

Positions
Name Lite Type Description
event_time et Timestamp Time at which the event was emitted in unix nanoseconds
sub_account_id sa uint64 The sub account ID that participated in the trade
instrument i string The instrument being represented
balance b int64 The balance of the position, expressed in underlying asset decimal units. Negative for short positions
value v int64 The value of the position, negative for short assets, expressed in quote asset decimal units
entry_price ep uint64 The entry price of the position, expressed in 9 decimals
Whenever increasing the balance of a position, the entry price is updated to the new average entry price
newEntryPrice = (oldEntryPrice * oldBalance + tradePrice * tradeBalance) / (oldBalance + tradeBalance)
exit_price ep1 uint64 The exit price of the position, expressed in 9 decimals
Whenever decreasing the balance of a position, the exit price is updated to the new average exit price
newExitPrice = (oldExitPrice * oldExitBalance + tradePrice * tradeBalance) / (oldExitBalance + tradeBalance)
mark_price mp uint64 The mark price of the position, expressed in 9 decimals
unrealized_pnl up int64 The unrealized PnL of the position, expressed in quote asset decimal units
unrealizedPnl = (markPrice - entryPrice) * balance
realized_pnl rp int64 The realized PnL of the position, expressed in quote asset decimal units
realizedPnl = (exitPrice - entryPrice) * exitBalance
pnl p int64 The total PnL of the position, expressed in quote asset decimal units
totalPnl = realizedPnl + unrealizedPnl
roi r float32 The ROI of the position, expressed as a percentage
roi = (pnl / (entryPrice * balance)) * 100

Example

{
    "sa": "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", // uint256 = 64 bytes
}

Example

{
    "result": 
    {
        "sub_account_id": "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", // uint128 = 64 bytes
        "margin_type": 3, // PORTFOLIO_CROSS_MARGIN uint32
        "quote_currency": 1, // USDC uint32
        "pending_deposit": "450000000", // uint64
        "derivative_positions": [
            {
                "derivative": {
                    "instrument": 3, // CALL uint8
                    "underlying": 4, // ETH uint8
                    "quote": 1, // USDC uint8
                    "expiration": "1689526957000000", // uint64
                    "strike_price": "1000000000", // uint64
                },
                "contract_balance": "1000000000", // uint64
                "unrealized_pnl":"4452000000"
            },
            {
                "derivative": {
                    "instrument": 4, // PUT uint8
                    "underlying": 4, // ETH uint8
                    "quote": 1, // USDC uint8
                    "expiration": "1689529888000000", // uint64
                    "strike_price": "1000000000", // uint64
                },
                "contract_balance": "-1000000000", // uint64
                "unrealized_pnl":"1000000000"
            }
        ],
        "unrealized_pnl": "3452000000", // uint64
        "initial_margin": ["1269146471088859254", 0.45],
        "maintanence_margin": ["269146471088859254", 0.08],
        "current_margin": ["1569146471088859254", 0.56],
        "is_under_liquidation": false
    }
}
Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Sub Account History

Query for all list of historical sub-account snapshots. Snapshots are taken every 5 minutes.

FULL ENDPOINT: full/v1/account_history
LITE ENDPOINT: lite/v1/account_history
ApiSubAccountHistoryRequest

The request to get the history of a sub account
SubAccount Summary values are snapshotted once every hour
No snapshots are taken if the sub account has no activity in the hourly window
The history is returned in reverse chronological order
History is preserved only for the last 30 days

Name Lite Type Description
sub_account_id sa uint64 The sub account ID to request for
start_time st Timestamp Start time of sub account history in unix nanoseconds
end_time et Timestamp End time of sub account history in unix nanoseconds
cursor c uint64 The cursor to indicate when to start the next query from
ApiSubAccountHistoryResponse
Name Lite Type Description
total t uint32 The total number of sub account snapshots matching the request filter
next n uint64 The cursor to indicate when to start the next query from
results r [SubAccount] The sub account history matching the request sub account
SubAccount
Name Lite Type Description
event_time et Timestamp Time at which the event was emitted in unix nanoseconds
sub_account_id sa uint64 The sub account ID this entry refers to
margin_type mt MarginType The type of margin algorithm this subaccount uses
quote_currency qc Currency The Quote Currency that this Sub Account is denominated in
This subaccount can only open derivative positions denominated in this quote currency
All other assets are converted to this quote currency for the purpose of calculating margin
In the future, when users select a Multi-Currency Margin Type, this will be USD
unrealized_pnl up int64 The total unrealized PnL of all positions owned by this subaccount, denominated in quote currency decimal units
total_value tv int64 The total value across all spot assets, or in other words, the current margin
initial_margin im uint64 The initial margin requirement of all positions owned by this vault, denominated in quote currency decimal units
maintanence_margin mm uint64 The maintanence margin requirement of all positions owned by this vault, denominated in quote currency decimal units
available_margin am int64 The margin available for withdrawal, denominated in quote currency decimal units
spot_balances sb [SpotBalance] The list of spot assets owned by this sub account, and their balances
positions p [Positions] The list of positions owned by this sub account
MarginType

MarginType:

  • SIMPLE_CROSS_MARGIN = 2: Simple Cross Margin Mode: all assets have a predictable margin impact, the whole subaccount shares a single margin
  • PORTFOLIO_CROSS_MARGIN = 3: Portfolio Cross Margin Mode: asset margin impact is analysed on portfolio level, the whole subaccount shares a single margin

Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

SpotBalance
Name Lite Type Description
currency c Currency The currency you hold a spot balance in
balance b uint64 The balance of the asset, expressed in underlying asset decimal units
Must take into account the value of all positions with this quote asset
ie. for USDT denominated subaccounts, this is is identical to total balance
Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

Positions
Name Lite Type Description
event_time et Timestamp Time at which the event was emitted in unix nanoseconds
sub_account_id sa uint64 The sub account ID that participated in the trade
instrument i string The instrument being represented
balance b int64 The balance of the position, expressed in underlying asset decimal units. Negative for short positions
value v int64 The value of the position, negative for short assets, expressed in quote asset decimal units
entry_price ep uint64 The entry price of the position, expressed in 9 decimals
Whenever increasing the balance of a position, the entry price is updated to the new average entry price
newEntryPrice = (oldEntryPrice * oldBalance + tradePrice * tradeBalance) / (oldBalance + tradeBalance)
exit_price ep1 uint64 The exit price of the position, expressed in 9 decimals
Whenever decreasing the balance of a position, the exit price is updated to the new average exit price
newExitPrice = (oldExitPrice * oldExitBalance + tradePrice * tradeBalance) / (oldExitBalance + tradeBalance)
mark_price mp uint64 The mark price of the position, expressed in 9 decimals
unrealized_pnl up int64 The unrealized PnL of the position, expressed in quote asset decimal units
unrealizedPnl = (markPrice - entryPrice) * balance
realized_pnl rp int64 The realized PnL of the position, expressed in quote asset decimal units
realizedPnl = (exitPrice - entryPrice) * exitBalance
pnl p int64 The total PnL of the position, expressed in quote asset decimal units
totalPnl = realizedPnl + unrealizedPnl
roi r float32 The ROI of the position, expressed as a percentage
roi = (pnl / (entryPrice * balance)) * 100

Example

{
    "sub_account_id": "123456",
    "end_time": "1631250830000000",
    "limit": 2
}

Example

{
    "total": 10,
    "next": "123131",
    "results": [
        {
          "event_time": 1707971008,
          "sub_account_id": 1,
          "margin_type": 3, // PORTFOLIO_CROSS_MARGIN uint32
          "quote_currency": 2, // USDC uint32
          "unrealized_pnl": "3452000000", // uint64,
          "total_value": "100000000000000000000", // uint64
          "initial_margin": 1269146471088859254, // uint64
          "maintanence_margin": 269146471088859254, // uint64
          "available_margin": 1569146471088859254, // uint64
          "spot_balances": [
            {
              "currency": 2, // USDC uint32
                "balance": 100000000000000000000 // uint64,
            }
          ],
          "position": [
            {
              "event_time": 1707971008,
              "sub_account_id": 1,
              "instrument": "BTC_USDT_Perp",
              "balance": 100000000000000000000, // uint64
              "value": 100000000000000000000, // uint64
              "entry_price": 100000000000000000000, // uint64
              "exit_price": 100000000000000000000, // uint64
              "mark_price": 100000000000000000000, // uint64
              "unrealized_pnl": 100000000000000000000, // uint64
              "realized_pnl": 100000000000000000000, // uint64
              "pnl": 100000000000000000000, // uint64
              "roi": 100000000000000000000 // uint64
            }
          ]
        }
    ]
}
Code Number Description
INVALID_TIME_RANGE 1002 The time range specified is invalid
INVALID_LIMIT 1004 The limit supplied is out of range
INVALID_CURSOR 1005 The cursor supplied is invalid
Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.

Trade History

Query for all historical trades made by a single account. A single order can be matched multiple times, hence there is no real way to uniquely identify a trade.

FULL ENDPOINT: full/v1/trade_history
LITE ENDPOINT: lite/v1/trade_history
PrivateTradeHistoryRequest
Name Lite Type Description
sub_account_id sa uint64 The sub account ID to request for
kind k [Kind] The kind filter to apply. If nil, this defaults to all kinds. Otherwise, only entries matching the filter will be returned
underlying u [Currency] The underlying filter to apply. If nil, this defaults to all underlyings. Otherwise, only entries matching the filter will be returned
quote q [Currency] The quote filter to apply. If nil, this defaults to all quotes. Otherwise, only entries matching the filter will be returned
expiration e int64 The expiration time to apply in unix nanoseconds. If nil, this defaults to all expirations. Otherwise, only entries matching the filter will be returned
strike_price sp uint64 The strike price to apply. If nil, this defaults to all strike prices. Otherwise, only entries matching the filter will be returned
limit l uint32 The limit to query for. Defaults to 500; Max 1000
cursor c string The cursor to indicate when to start the query from
Kind

The list of asset kinds that are supported on the GRVT exchange
Kind:

  • PERPETUAL = 1: the perpetual asset kind
  • FUTURE = 2: the future asset kind
  • CALL = 3: the call option asset kind
  • PUT = 4: the put option asset kind

Currency

The list of Currencies that are supported on the GRVT exchange
Currency:

  • USDC = 2: the USDC token
  • USDT = 3: the USDT token
  • ETH = 4: the ETH token
  • BTC = 5: the BTC token

PrivateTradeHistoryResponse
Name Lite Type Description
total t uint32 The total number of private trades matching the request filter
next n string The cursor to indicate when to start the next query from
results r [PrivateTrade] The private trades matching the request asset
PrivateTrade
Name Lite Type Description
event_time et Timestamp Time at which the event was emitted in unix nanoseconds
sub_account_id sa uint64 The sub account ID that participated in the trade
instrument i string The instrument being represented
is_buyer ib bool The side that the subaccount took on the trade
is_taker it bool The role that the subaccount took on the trade
size s uint64 The number of assets being traded, expressed in underlying asset decimal units
price p uint64 The traded price, expressed in 9 decimals
mark_price mp uint64 The mark price of the instrument at point of trade, expressed in 9 decimals
index_price ip uint64 The index price of the instrument at point of trade, expressed in 9 decimals
interest_rate ir int32 The interest rate of the underlying at point of trade, expressed in centibeeps (1/100th of a basis point)
forward_price fp uint64 [Options] The forward price of the option at point of trade, expressed in 9 decimals
realized_pnl rp int64 The realized PnL of the trade, expressed in quote asset decimal units (0 if increasing position size)
fee f int64 The fees paid on the trade, expressed in quote asset decimal unit (negative if maker rebate applied)
fee_rate fr int32 The fee rate paid on the trade
trade_id ti uint64 A trade identifier
order_id oi uint128 An order identifier
venue v Venue The venue where the trade occurred
Venue

The list of Trading Venues that are supported on the GRVT exchange
Venue:

  • ORDERBOOK = 1: the trade is cleared on the orderbook venue
  • RFQ = 2: the trade is cleared on the RFQ venue
  • AXE = 3: the trade is cleared on the AXE venue

Example

{
    "sub_account_id": 1,
    "kind": [], //all kind
    "underlying": [], //all underlyings
    "quote": [], //all quotes
    "limit": 1,
    "cursor": 19230913
}

Example

{
    "results": [
        {
            "event_time": 1707971008,
            "sub_account_id": 1,
            "instrument": "BTC_USDT_PERP",
            "is_buyer": true,
            "is_taker": false,
            "price": 10000000,
            "mark_price": 10000000,
            "realized_pnl": 60000,
            "fee": 1000,
            "fee_rate": 10000,
            "trade_id": 1,
            "order_id": "0x0123456789abcdef0123456789abcdef", // uint128 = 32 bytes
            "venue": 2,
            "greeks":
            {
                "underlying_price": 34796430000,
                "risk_free_rate": 5000,
                "delta": 75.3432,
                "gamma": 0.367,
                "iv": 0.234,
                "vega": 60.23425,
                "volga": 6.742,
                "vanna": 0.234,
                "theta": 0.0126,
                "rho": 34.234
            }
        }
    ]
}
Code Number Description
INVALID_INSTRUMENT 1001 The instrument supplied is not supported by our exchange
INVALID_TIME_RANGE 1002 The time range specified is invalid
INVALID_LIMIT 1004 The limit supplied is out of range
INVALID_CURSOR 1005 The cursor supplied is invalid
Generic System Errors

We Adopt the GRPC error code system.

Failed API calls always return an error code. In some APIs, API level error codes will also be returned.

{
    "code": 3,
    "msg":"INVALID_ARGUMENT",
    "api_code": 1001,
    "api_msg": "INVALID_TIME_IN_FORCE"
}
Code Number Description
OK 0 Not an error; returned on success.
CANCELLED 1 The operation was cancelled, typically by the caller.
UNKNOWN 2 Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
INVALID_ARGUMENT 3 The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
DEADLINE_EXCEEDED 4 The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
NOT_FOUND 5 Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
ALREADY_EXISTS 6 The entity that a client attempted to create (e.g., file or directory) already exists.
PERMISSION_DENIED 7 The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
RESOURCE_EXHAUSTED 8 Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
FAILED_PRECONDITION 9 The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
OUT_OF_RANGE 11 The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
UNIMPLEMENTED 12 The operation is not implemented or is not supported/enabled in this service.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
DATA_LOSS 15 Unrecoverable data loss or corruption.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation.