C++ signing core and reference
Use tested C++ signing code and executable reference examples with your own networking and application state.
On this page
Help me with: C++ signing core and reference. Use tested C++ signing code and executable reference examples with your own networking and application state.
Target environment: {environment} (chain ID {chainId}). Recorded signing cases keep their original environment.
{executionGuidance}
Read this first: {origin}/bundle/sdks/cpp.md (~24 KB, plain Markdown: this page plus the AGENTS.md rules, Environments).
Fetch other pages from the index at {origin}/llms.txt only as you need them. {origin}/downloads/contract.json is a machine-readable contract for tools, not for reading.
Rules: follow AGENTS.md; do not send requests without the user asking you to; read credentials from environment variables; never retry writes automatically; show me the code and how to run it. Preview. Any 0.x release can change the API. Pin the commit you build from.
Advanced. The C++ signing core is for apps that already have their own networking and event loop. It signs requests and encodes them as JSON; your code does the rest. For a full client, use another SDK.
| What you get | What you build yourself |
|---|---|
| Exact decimal values | HTTP and WebSocket clients |
| EIP-712 encoding and hashing | Login, session renewal and the cancel-on-disconnect countdown |
| An optional libsecp256k1 signer for private keys in the same process | Timers, streams and order books |
| Executable reference examples | Recovery after lost answers and stream gaps |
| Loading metadata, choosing the environment, nonce and expiration | |
| Business checks: tick size, minimum size, minimum notional |
There is no client and no wrapper for each RPC or stream.
Build the core
Not published as a package yet: build it from source, from its public repository grvt-signing-cpp, and pin the commit you build from.
- Install CMake 3.24+ and GCC or Clang with C++20 or newer, on Linux or macOS. MSVC isn't supported, because
the core uses
__int128arithmetic. - Clone, build and install:
git clone https://github.com/gravity-technologies/grvt-signing-cpp
cd grvt-signing-cpp
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build
cmake --install build --prefix /opt/grvt
- Optional, for private keys in the same process: install libsecp256k1 with its recovery module
(
apt install libsecp256k1-devorbrew install secp256k1). Then configure with-DGRVT_SIGNING_WITH_SECP256K1=ON. The default build doesn't need it. - Link the package from your CMake project:
find_package(grvt_signing REQUIRED)
target_link_libraries(app PRIVATE grvt::signing)
# Also link grvt::signer when using the optional private-key signer.
- Optional: run
ctest --test-dir build --output-on-failure. It checks the signing cases, the installed package (the digest path and the optional signer separately) and the reference. Test your own integration against signing.json too; an installed build has it atshare/grvt_signing/signing.json.
Errors. Every function that can fail returns grvt::Result<T>: the value, or a grvt::Error with a
kind (signing, decode or config) and a message. Encoding and signing failures are returned, not thrown.
Run the reference
When: you want to see the whole signing flow before writing your own transport.
From the source directory, build with examples turned on and run grvt_signing_reference:
cmake -S . -B build -DGRVT_SDK_BUILD_EXAMPLES=ON
cmake --build build --target grvt_signing_reference
./build/grvt_signing_reference
The source below keeps signing separate from the transport, which your code supplies. It uses fixed inputs and made-up host data and makes no network calls, so it doesn't prove that login, networking or order recovery work against the exchange.
// Offline reference. Replace the print callback with your own HTTP transport.
#include <cstdio>
// Published conformance inputs. These are test values, never production credentials.
#include "grvt/grvt.hpp"
namespace reference {
inline auto order() {
grvt::models::OrderLeg leg("BTC_USDT_Perp", *grvt::Decimal::parse("0.01"), true);
leg.limit_price = *grvt::Decimal::parse("60000");
grvt::models::OrderInput input(grvt::enums::TimeInForce::GOOD_TILL_TIME, std::vector<grvt::models::OrderLeg>{leg});
input.sub_account_id = 8289849667772468ULL;
input.is_market = false;
input.post_only = true;
input.reduce_only = false;
input.metadata.emplace();
input.metadata->client_order_id = (1ULL << 63) | 1001; // API client ID range
input.signature.emplace();
input.signature->signer = "0x1267c6181aee40f5ddbd70c56ecf4613117326b5";
input.signature->nonce = 1001;
input.signature->expiration = grvt::timestamp_from_ns(4102444800000000000LL);
input.signature->chain_id = 326;
return grvt::models::ApiCreateOrderRequestInput(std::move(input));
}
inline grvt::SigningMetadata metadata() {
grvt::SigningMetadata meta;
meta.instruments["BTC_USDT_Perp"] = {"0x030501", 9, 6};
return meta;
}
inline constexpr auto test_key = "0xbfe25ff07bd38cb3fbc28a2a296d41aabd68a78c929d257935906489fc9c6d89";
} // namespace reference
#ifdef GRVT_WITH_SIGNER
#include "grvt/signer.hpp"
#endif
// The host owns HTTP, secrets, cookies and account state. Nothing is sent by this example.
using HostPost = void (*)(std::string_view path, std::string_view cookie, std::string_view account_id,
std::string_view body);
void print_wire(std::string_view path, std::string_view cookie, std::string_view account_id, std::string_view body) {
std::printf("POST %.*s\n", int(path.size()), path.data());
if (!cookie.empty()) std::printf("Cookie: %.*s\n", int(cookie.size()), cookie.data());
if (!account_id.empty()) std::printf("X-Grvt-Account-Id: %.*s\n", int(account_id.size()), account_id.data());
std::printf("%.*s\n", int(body.size()), body.data());
}
int main() {
HostPost post = &print_wire;
// API-key login wire shape. Read Set-Cookie gravity and X-Grvt-Account-Id from the
// real response in the host. Never print real keys or cookies in production logs.
post("/auth/api_key/login", {}, {}, R"({"api_key":"REPLACE_IN_HOST"})");
auto order = reference::order();
auto meta = reference::metadata();
grvt::SignContext ctx;
ctx.chain_id = 326; // caller selects the chain; the core has no environment lookup
ctx.metadata = &meta;
auto digest = grvt::signing::digest_order_create_order(order, ctx);
if (!digest) return 1;
std::printf("digest: %s\n", grvt::hex0x(digest->digest).c_str());
#ifdef GRVT_WITH_SIGNER
auto signer = grvt::PrivateKeySigner::from_hex(reference::test_key);
if (!signer) return 2;
ctx.signer = &*signer;
ctx.verify = &grvt::verify_signature;
if (!grvt::signing::sign_order_create_order(order, ctx)) return 3;
post("/full/v1/create_order", "gravity=HOST_COOKIE", "HOST_ACCOUNT_ID", grvt::encode(order));
#endif
// If a write times out after sending, its result is unknown. Keep client_order_id
// and reconcile with get_order/order history. An absent lookup does not prove that
// the order was rejected. Keep the result unknown and never automatically resend.
// A fresh nonce is not a retry guarantee. The host owns this policy and its storage.
std::puts("unknown write: reconcile by client_order_id; absent lookup stays unknown; never automatically resend");
return 0;
}
Watch out: don't submit its recorded request as a new order. It uses fixed test values, not a live nonce or expiration.
Connect a live application
When: you are ready to send real requests. Start on testnet.
- Pick the environment URLs and chain ID for one environment, and use them together.
- Log in with your API key over HTTP (Authentication).
- Save the returned
gravitycookie andX-Grvt-Account-Id. Send both on private requests and on the WebSocket upgrade. - Load current instrument and currency metadata from the API into a
grvt::SigningMetadata(instrument_hash,base_decimalsandquote_decimalsper instrument;idandbalance_decimalsper currency; yourmain_accountfor vault calls), and pointSignContext::metadataat it.grvt::signing::needs_<call>says which entries a request needs. - Set these yourself, and use exact decimal text for every price, size and amount:
- Chain ID:
SignContext::chain_id. A request whosesignature.chain_idis"0"(the environment's) is signed with it; a call fails with aconfigerror if both are 0. - Nonce: a fresh uint32 from an OS secure random source, for each new signed action.
- Expiration: a future Unix timestamp in nanoseconds, at most 30 days ahead (180 for take-profit and stop-loss orders) (Expiration).
- Client order ID: your own, saved before you send, so you can look the order up if its response is lost.
- Chain ID:
- Sign. Call
grvt::signing::digest_<call>to get a digest for an external signer, orgrvt::signing::sign_<call>with a signer. An order withbuilderset is signed asOrderWithBuilderFee(Builder fee orders). Bulk orders have separate functions to make the digests (digests_order_bulk_orders) and to attach the signatures (attach_order_bulk_orders). - Encode the signed request with
grvt::encode(request), which writes the wire JSON, and send it with your own HTTP or WebSocket client.
Your app also checks stream sequence numbers, reconnects and recovers state (WebSocket, Errors and retries). Signing has the signing details.
Watch out:
- Read credentials from environment variables or your secret store. Keep signing keys out of request bodies and logs.
- Turn off redirects, including during WebSocket handshakes. A followed redirect sends a second request, which can forward your credentials or replay a signed write.
- Keep metadata, chain ID, nonce and expiration consistent with the environment and account you send to. The core doesn't load or choose any of them for you.
attach_order_bulk_ordersrequiresSignContext::verify. Your callback must check that each digest and signature recover to the expected address: returning success without checking proves nothing about the signing key. The optional adapter providesgrvt::verify_signaturefor this.
Guarantees and edge cases
- Inside a
Signercallback,SigningRequest::typed_data()gives you the typed data, for wallets that need it. Digest results and their copies don't keep the typed data. - Before your verifier runs, the core checks the signature shape, low-s (Signing) and the signer field.
- The sign and digest functions only read the
SignContext. Threads can share one while each signs its own request, if yourSigneris safe to call from several threads at once (PrivateKeySigneris) and nothing changes the metadata meanwhile. digest_order_create_order, andsign_order_create_orderwithPrivateKeySigner, allocate no memory after the first few calls when you reuse the same request object. Errors andtyped_data()do allocate.
What the core checks
- It validates encoding inputs and the signing metadata it needs.
- It rejects any value it can't represent exactly at the required scale. It never rounds.
A valid digest doesn't mean the exchange will accept the order.
Not supported yet
- A client. The core has no HTTP, WebSocket, login, session renewal or recovery, on purpose: your application owns them, as the table at the top of this page lists.
- MSVC. The core uses
__int128arithmetic; build with GCC or Clang (Build the core).