---
title: "C++ signing core and reference"
description: "Use tested C++ signing code and executable reference examples with your own networking and application state."
order: 24
llms: trading, signing
---

> [!WARNING]
> **Preview.** Any 0.x release can change the API. Pin the commit you build from.

**Advanced.** The C++ signing core is for apps that already have their own networking and event loop. It signs
requests and encodes them as JSON; your code does the rest. For a full client, use another SDK.

| What you get | What you build yourself |
|---|---|
| Exact decimal values | HTTP and WebSocket clients |
| EIP-712 encoding and hashing | Login, session renewal and the cancel-on-disconnect countdown |
| An optional libsecp256k1 signer for private keys in the same process | Timers, streams and order books |
| Executable reference examples | Recovery after lost answers and stream gaps |
| | Loading metadata, choosing the environment, nonce and expiration |
| | Business checks: tick size, minimum size, minimum notional |

There is no client and no wrapper for each RPC or stream.

## Build the core

**Not published as a package yet:** build it from source, from its public repository
[grvt-signing-cpp](https://github.com/gravity-technologies/grvt-signing-cpp), and pin the commit you build from.

1. Install CMake 3.24+ and GCC or Clang with C++20 or newer, on Linux or macOS. MSVC isn't supported, because
   the core uses `__int128` arithmetic.
2. Clone, build and install:

```sh
git clone https://github.com/gravity-technologies/grvt-signing-cpp
cd grvt-signing-cpp
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build
cmake --install build --prefix /opt/grvt
```

3. Optional, for private keys in the same process: install libsecp256k1 with its recovery module
   (`apt install libsecp256k1-dev` or `brew install secp256k1`). Then configure with
   `-DGRVT_SIGNING_WITH_SECP256K1=ON`. The default build doesn't need it.
4. Link the package from your CMake project:

```cmake
find_package(grvt_signing REQUIRED)
target_link_libraries(app PRIVATE grvt::signing)
# Also link grvt::signer when using the optional private-key signer.
```

5. Optional: run `ctest --test-dir build --output-on-failure`. It checks the signing cases, the installed
   package (the digest path and the optional signer separately) and the reference. Test your own integration
   against [signing.json](../downloads/signing.json) too; an installed build has it at
   `share/grvt_signing/signing.json`.

**Errors.** Every function that can fail returns `grvt::Result<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`:

```sh
cmake -S . -B build -DGRVT_SDK_BUILD_EXAMPLES=ON
cmake --build build --target grvt_signing_reference
./build/grvt_signing_reference
```

The source below keeps signing separate from the transport, which your code supplies. It uses fixed inputs and
made-up host data and makes no network calls, so it doesn't prove that login, networking or order recovery
work against the exchange.

[Download this example](../downloads/examples/cpp/examples/reference.cpp)

```cpp
// Offline reference. Replace the print callback with your own HTTP transport.
#include <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.

1. Pick the [environment URLs and chain ID](../guides/environments.md) for one environment, and use them
   together.
2. Log in with your API key over HTTP ([Authentication](../guides/authentication.md#by-hand)).
3. Save the returned `gravity` cookie and `X-Grvt-Account-Id`. Send both on private requests and on the
   WebSocket upgrade.
4. Load current instrument and currency metadata from the API into a `grvt::SigningMetadata`
   (`instrument_hash`, `base_decimals` and `quote_decimals` per instrument; `id` and `balance_decimals` per
   currency; your `main_account` for vault calls), and point `SignContext::metadata` at it.
   `grvt::signing::needs_<call>` says which entries a request needs.
5. Set these yourself, and use exact decimal text for every price, size and amount:
   - Chain ID: `SignContext::chain_id`. A request whose `signature.chain_id` is `"0"` (the environment's) is
     signed with it; a call fails with a `config` error if both are 0.
   - Nonce: a fresh uint32 from an OS secure random source, for each new signed action.
   - Expiration: a future Unix timestamp in nanoseconds, at most 30 days ahead (180 for take-profit and
     stop-loss orders) ([Expiration](../guides/signing.md#rules-that-cause-most-rejections)).
   - Client order ID: your own, saved before you send, so you can
     [look the order up](../guides/errors-and-retries.md#when-a-writes-outcome-is-unknown) if its response is
     lost.
6. Sign. Call `grvt::signing::digest_<call>` to get a digest for an external signer, or
   `grvt::signing::sign_<call>` with a signer. An order with `builder` set is signed as `OrderWithBuilderFee`
   ([Builder fee orders](../guides/signing.md#builder-fee-orders)). Bulk orders have separate functions to make
   the digests (`digests_order_bulk_orders`) and to attach the signatures (`attach_order_bulk_orders`).
7. Encode the signed request with `grvt::encode(request)`, which writes the wire JSON, and send it with your own
   HTTP or WebSocket client.

Your app also checks stream sequence numbers, reconnects and recovers state ([WebSocket](../guides/websocket.md),
[Errors and retries](../guides/errors-and-retries.md)). [Signing](../guides/signing.md) has the signing details.

**Watch out:**

- Read credentials from environment variables or your secret store. Keep signing keys out of request bodies
  and logs.
- Turn off redirects, including during WebSocket handshakes. A followed redirect sends a second request, which
  can forward your credentials or replay a signed write.
- Keep metadata, chain ID, nonce and expiration consistent with the environment and account you send to. The
  core doesn't load or choose any of them for you.
- `attach_order_bulk_orders` requires `SignContext::verify`. Your callback must check that each digest and
  signature recover to the expected address: returning success without checking proves nothing about the
  signing key. The optional adapter provides `grvt::verify_signature` for this.

<details>
<summary>Guarantees and edge cases</summary>

- Inside a `Signer` callback, `SigningRequest::typed_data()` gives you the typed data, for wallets that
  need it. Digest results and their copies don't keep the typed data.
- Before your verifier runs, the core checks the signature shape, low-s
  ([Signing](../guides/signing.md#the-steps)) and the signer field.
- The sign and digest functions only read the `SignContext`. Threads can share one while each signs its own
  request, if your `Signer` is safe to call from several threads at once (`PrivateKeySigner` is) and nothing
  changes the metadata meanwhile.
- `digest_order_create_order`, and `sign_order_create_order` with `PrivateKeySigner`, allocate no memory
  after the first few calls when you reuse the same request object. Errors and `typed_data()` do allocate.

</details>

## What the core checks

- It validates encoding inputs and the signing metadata it needs.
- It rejects any value it can't represent exactly at the required scale. It never rounds.

A valid digest doesn't mean the exchange will accept the order.

## Not supported yet

- **A client.** The core has no HTTP, WebSocket, login, session renewal or recovery, on purpose: your
  application owns them, as the table at the top of this page lists.
- **MSVC.** The core uses `__int128` arithmetic; build with GCC or Clang ([Build the core](#build-the-core)).
