Developers

Vault invest

Invest in a vault from your main account or a sub-account, converting currency if needed.

On this page

URLs and generated code samples on this page: Testnet (chain ID 326). Other code on this page doesn't change: it stays on testnet until you switch it in your code. Tutorials, signing cases and live tools always use testnet.

The investor signs VaultInvestV3 over both currencies, the amount and the exchange rate. Without conversion the rate is exactly 1. With conversion it must be at most the rate /vault_conversion_rate returns.

SDKclient.vault_invest(...)
HTTPPOST https://trades.testnet.grvt.io/full/v2/vault_invest, or /lite/v2/vault_invest for lite names (the SDKs' default)
WebSocketmethod v2/vault_invest on wss://trades.testnet.grvt.io/ws/full, or /ws/lite for lite names
AuthSession required (Authentication)
Signedsignature is signed: VaultInvestV3. always VaultInvestV3. (Signing)
RetriesWrite: never retried automatically (why)
Contract idvault.vault_invest (RPCVaultInvestV2)

Request

Body type ApiVaultInvestV2Request. Fields the server fills are left out.

  • vault_idlite name vistring (uint64)required#
    The unique identifier of the vault to invest in.
  • from_sub_account_idlite name fsstring (uint64)required#
    The sub-account to invest from. 0 means the funding account.
  • from_wallet_typelite name fwenum WalletTyperequired#
    FUNDING when fromSubAccountID is 0, otherwise SPOT or FUTURES.
    3 values
    FUNDING, SPOT, FUTURES (details).
  • from_currencylite name fcstringrequired#
    The currency debited from the source wallet.
  • from_num_tokenslite name fnstringrequired#
    The amount debited from the source wallet, in fromCurrency.
  • to_currencylite name tcstringrequired#
    The currency the vault receives. This must be the vault's investment currency.
  • exchange_ratelite name erstringrequired#
    The signed rate, toCurrency per unit of fromCurrency, up to 9 decimal places. Exactly 1 when both currencies are the same.
  • signaturelite name sobject Signaturerequired#
    The VaultInvestV3 signature of the investing account. The signer needs the vault investor permission on the main account and, for a sub-account source, the transfer permission on that sub-account.
    7 fields of Signature
    • signerlite name sstring (uint256)required#
      The address of the wallet that signed (0x + 40 hex characters). That wallet must be allowed to act for the account; for an order, to trade for the sub-account.
    • rlite name rstring (uint256)required#
      The signature's r, as 0x + 64 hex characters. Without the 0x the signature fails to verify.
    • slite name s1string (uint256)required#
      The signature's s, as 0x + 64 hex characters. Without the 0x the signature fails to verify.
    • vlite name vinteger (uint8)required#
      The signature's v, 27 or 28.
    • expirationlite name estring (int64 unix ns)required#
      When the signature stops being valid, in unix nanoseconds, measured on the exchange's clock. At most 30 days ahead (take-profit and stop-loss orders may be accepted up to 180 days ahead); one already past fails with 2001. On an order it is also the order's lifetime: an order still open then is cancelled with reason EXPIRED. The SDKs use now + 24 hours.
    • noncelite name ninteger (uint32)required#
      A number you choose, 0 to 4,294,967,295 (uint32), so that two otherwise identical requests have different signatures. Use a new random one for each request you sign.

      A transfer whose signed fields (nonce and expiration included) exactly repeat an earlier one is rejected, not ignored: it fails with 4007.

      Orders are different. An exact resend of a signed order can be accepted and rest on the book, but the exchange counts fills per signed order, so all copies together never fill more than the signed size, and a resent IMMEDIATE_OR_CANCEL order whose first copy already filled is rejected. An order signed again (new nonce or expiration) is a new order and can fill in full again.

    • chain_idlite name cistring (uint64)required#
      The chain id in the signed EIP-712 domain, as a string. Testnet 326, production 325; "0" means the environment's chain id.

Response

Body type ApiVaultInvestV2Response (the same object is the JSON-RPC result over WebSocket).

  • acklite name aboolrequired#
    Whether the investment was accepted.
  • tx_idlite name tistring (uint64)required#
    The transaction ID of the investment once risk confirmed it. 0 when the investment was queued.
  • enqueuedlite name ebooloptional#
    Cross-exchange vaults only: true when the vault was locked and the investment was queued.

Errors

Errors come back as {"code", "message", "status"} (lite {"c", "m", "s"}) with the HTTP status. Codes this call can return (all error codes):

2000SignerUnauthorized403Inspect
Signature is from an unauthorized signer
2001SignatureExpired403Inspect
Signature has expired
2002SignatureDoesNotMatchPayload403Inspect
Signature does not match payload
2004SessionKeySignerExpired403
Signature is from an expired session key
2005SignatureInvalidV403Inspect
Signature V must be 27/28
2006SignatureInvalidRSLength403Inspect
Signature R/S must have exactly 64 characters long without 0x prefix
2007SignatureSIsNotCurveLowerHalf403Inspect
Signature S must be in the lower half of the curve
2008SignatureExpirationTooLong403Inspect
Signature exceeds maximum allowed duration.
4000InsufficientBalanceToTransfer400
Insufficient balance to complete transfer
4008CurrencyNotAllowedInWallet400
Currency is not allowed in the target wallet type
Show 20 more errors for this call
7000InvalidVaultID400
Vault ID provided is invalid and does not belong to any vault
7003VaultNotActive400
This vault has been delisted/closed.
7004InvestmentExceedsCap400
This investment would cause the vault to exceed its valuation cap.
7012InvalidVaultInvestorID400
Vault investor ID provided is invalid.
7013CrossExchangeVaultNotSupported400
Cross-exchange vaults not supported
7014OnlyAllowedToInvestInVaultInvestmentCurrency400
Only allowed to invest in vault's investment currency
7017VaultConversionRateNotAllowed400
The exchange rate is not allowed: it must be exactly 1 when both currencies are the same, and at most the current conversion rate otherwise.
7018VaultInvalidInvestSource400
Invalid invest source: use the funding account with the funding wallet, or a spot or futures wallet of one of your own trading accounts that is not a vault.
7019VaultConversionPriceStale400
A price this conversion needs is stale or not available yet. Please try again later.
7027VaultConversionZeroOutput400
The conversion would pay out nothing: the exchange rate or the amount is too small.
7028VaultInvestAlreadyExecuted400
This signed vault investment has already been executed. Sign a new one to invest again.
7035VaultInvestSourceNeedsSpotTransfers400
Spot transfers are not enabled, so only the funding account or the futures wallet of a trading account, in USDT, can pay this investment.
7101TransferAccountNotFound400
Transfer account not found
7102TransferSubAccountNotFound400
Transfer sub-account not found
7801CurrencyNotConvertible400
This currency is not enabled for stable coin convert.
7802PriceOutOfConvertBand400
The index price of one of the currencies is outside the permitted convert band. Please try again later.
7803MissingIndexPrice400
An index price required for this conversion is unavailable. Please try again later.
7805InexactConversion400
This amount cannot be converted exactly between the two currencies’ decimals. Please adjust the amount.
7811NegativeBalance400
This conversion would leave a negative balance.
7812ValueOverflow400
The convert amount is too large to be represented. Please use a smaller amount.
Plus 10 errors any call can return
1000Unauthorized401
You need to authenticate prior to using this functionality
1001Forbidden403
You are not authorized to access this functionality
1002InternalServer500
Internal Server Error
1003InvalidRequest400
Request could not be processed due to malformed syntax
1006RateLimit429retryable
You have surpassed the allocated rate limit for your tier
1007UnsupportedCurrency404
The currency you are requesting for is not currently supported
1008IPNotWhitelisted401
Your IP has not been whitelisted for access
1009APIEndpointTemporarilyDeactivated503retryable
We are temporarily deactivating this API endpoint, please try again later
1012InvalidSignatureChainID400Inspect
Invalid signature chain ID
1014GatewayTimeout504retryable
Upstream data service timed out, please try again

Example

Example code
import os
from decimal import Decimal

from grvt import Grvt, enums as e, PrivateKeySigner

with Grvt(
    env=os.environ.get("GRVT_ENV", "testnet"),
    api_key=os.environ["GRVT_API_KEY"],
    signer=PrivateKeySigner(os.environ["GRVT_PRIVATE_KEY"]),
) as client:
    resp = client.vault_invest(
        vault_id="4211543862",
        from_sub_account_id="0",
        from_wallet_type=e.WalletType("FUNDING"),
        from_currency="USDT",
        from_num_tokens=Decimal("1000.5"),
        to_currency="USDC",
        exchange_rate=Decimal("0.9998"),
    )
    print(resp)

Raw HTTP (set GRVT_DOMAIN, see Environments; GRVT_COOKIE and GRVT_ACCOUNT_ID come from login):

The body below is the vault_invest signing case: a real signature by the public test key for chain id 326. Build your own with the Signing guide; the server will reject this one (unknown account). signature.expiration is unix nanoseconds: use now + 1 day (the signing case uses 2100-01-01 so it never expires).

With full field names:

curl -sS "https://trades.testnet.grvt.io/full/v2/vault_invest" \
  -H "Content-Type: application/json" \
  -H "Cookie: gravity=$GRVT_COOKIE" \
  -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \
  --data @- <<EOF
{
  "vault_id": "4211543862",
  "from_sub_account_id": "0",
  "from_wallet_type": "FUNDING",
  "from_currency": "USDT",
  "from_num_tokens": "1000.5",
  "to_currency": "USDC",
  "exchange_rate": "0.9998",
  "signature": {
    "signer": "0x1267c6181aee40f5ddbd70c56ecf4613117326b5",
    "expiration": "4102444800000000000",
    "nonce": 6001,
    "chain_id": "326",
    "r": "0xb6b4a3f4e7678087b448e147ac0b63f03f105c8cee6764276ea972484b57c095",
    "s": "0x2ba7a7455cde97674db9bf20b091c9add3ab43d1113e551961f9cf23ab3fb12c",
    "v": 27
  }
}
EOF

With lite field names:

curl -sS "https://trades.testnet.grvt.io/lite/v2/vault_invest" \
  -H "Content-Type: application/json" \
  -H "Cookie: gravity=$GRVT_COOKIE" \
  -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \
  --data @- <<EOF
{
  "vi": "4211543862",
  "fs": "0",
  "fw": "FUNDING",
  "fc": "USDT",
  "fn": "1000.5",
  "tc": "USDC",
  "er": "0.9998",
  "s": {
    "s": "0x1267c6181aee40f5ddbd70c56ecf4613117326b5",
    "e": "4102444800000000000",
    "n": 6001,
    "ci": "326",
    "r": "0xb6b4a3f4e7678087b448e147ac0b63f03f105c8cee6764276ea972484b57c095",
    "s1": "0x2ba7a7455cde97674db9bf20b091c9add3ab43d1113e551961f9cf23ab3fb12c",
    "v": 27
  }
}
EOF
Build & sign locally
esc

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

Keyboard shortcuts

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