> For the complete documentation index, see [llms.txt](https://k4k3ru.gitbook.io/k4k3ru-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://k4k3ru.gitbook.io/k4k3ru-docs/api/authentication/sign-request-with-rust.md).

# Sign a Request with Rust

Build an authenticated K4K3RU JSON-RPC request with Rust. This example supports both `hmac-sha256` and `ed25519` credentials.

## Prerequisites

* A current stable Rust toolchain.
* An API credential created with `hmac-sha256` or `ed25519`.
* `K4K3RU_API_KEY`, `K4K3RU_SECRET_KEY`, and `K4K3RU_SIGNATURE_ALGORITHM` set in your environment.

Create a project and add the example dependencies:

```bash
cargo new k4k3ru-signing
cd k4k3ru-signing
cargo add base64 ed25519-dalek hmac rand serde_json sha2
```

## Example

Replace `src/main.rs` with:

```rust
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use ed25519_dalek::{Signer, SigningKey};
use hmac::{Hmac, Mac};
use rand::RngCore;
use serde_json::{json, Map, Value};
use sha2::Sha256;
use std::{env, error::Error, time::{SystemTime, UNIX_EPOCH}};

fn canonicalize(value: Value) -> Value {
    match value {
        Value::Array(values) => Value::Array(values.into_iter().map(canonicalize).collect()),
        Value::Object(values) => {
            let mut entries: Vec<_> = values.into_iter().collect();
            entries.sort_by(|left, right| left.0.cmp(&right.0));
            let mut sorted = Map::new();
            for (key, value) in entries {
                sorted.insert(key, canonicalize(value));
            }
            Value::Object(sorted)
        }
        other => other,
    }
}

fn sign(algorithm: &str, secret: &[u8], payload: &[u8]) -> Result<Vec<u8>, Box<dyn Error>> {
    match algorithm {
        "hmac-sha256" => {
            let mut mac = Hmac::<Sha256>::new_from_slice(secret)?;
            mac.update(payload);
            Ok(mac.finalize().into_bytes().to_vec())
        }
        "ed25519" => {
            if secret.len() != 64 {
                return Err(format!("invalid Ed25519 private key length: {}", secret.len()).into());
            }
            let seed: [u8; 32] = secret[..32].try_into()?;
            Ok(SigningKey::from_bytes(&seed).sign(payload).to_bytes().to_vec())
        }
        _ => Err(format!("unsupported signature algorithm: {algorithm}").into()),
    }
}

fn main() -> Result<(), Box<dyn Error>> {
    let api_key = env::var("K4K3RU_API_KEY")?;
    let secret = URL_SAFE_NO_PAD.decode(env::var("K4K3RU_SECRET_KEY")?)?;
    let algorithm = env::var("K4K3RU_SIGNATURE_ALGORITHM")?;
    let method = "PaymentOnchain.CreateIntent";
    let params = json!({"productName": "usdc-base-mainnet-1"});
    let canonical_params = serde_json::to_string(&canonicalize(params.clone()))?;
    let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
    let mut nonce_bytes = [0_u8; 16];
    rand::thread_rng().fill_bytes(&mut nonce_bytes);
    let nonce = URL_SAFE_NO_PAD.encode(nonce_bytes);
    let payload = format!("{method}\n{timestamp}\n{nonce}\n{canonical_params}");
    let signature = URL_SAFE_NO_PAD.encode(sign(&algorithm, &secret, payload.as_bytes())?);

    let request = json!({
        "id": "1",
        "method": method,
        "params": params,
        "auth": {
            "apiKey": api_key,
            "timestamp": timestamp,
            "nonce": nonce,
            "signature": signature
        }
    });
    println!("{}", serde_json::to_string_pretty(&request)?);
    Ok(())
}
```

Run it with:

```bash
cargo run
```

The program prints a request body that you can send to `https://api.k4k3ru.com/` with `Content-Type: application/json`. Build the canonical payload and request from the same `params` value.

## Next Steps

See [API Request Authentication](/k4k3ru-docs/api/authentication.md) for canonicalization, freshness, replay-protection, and troubleshooting requirements.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://k4k3ru.gitbook.io/k4k3ru-docs/api/authentication/sign-request-with-rust.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
