Esc

    Integrate

    Rust SDK

    Read prices in a Rust service that verifies every node itself and takes the median.

    oracle-client connects to every node, verifies each signed update, and resolves one price for each feed across the nodes. Use it when your service must not trust one node or one operator. A browser or another language uses the web proxy instead.

    1. Add the crate

    toml
    [dependencies]
    oracle-client = { git = "https://github.com/markoutlabs/oracle-node", tag = "v0.1.0" }
    tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
    • Rust 1.88 or newer, a C compiler, and a Tokio runtime.
    • The signature checks are pure Rust, but the TLS crypto library ring needs a C compiler. The libsecp feature takes the C library libsecp256k1 for the signatures instead, which is about 5 times faster: default-features = false, features = ["libsecp"]. Use it for a client that reads many feeds.
    • The client checks the signatures of each node's frames in that node's own task. On a multi-thread runtime, the frames of the nodes are thus checked on several cores at the same time.
    • The crate re-exports the types its API uses: Fixed, Symbol and InstrumentId at the top level and in oracle_client::types; Signer, Address and Registry at the top level and in oracle_client::wire.

    2. Get a client key

    Nodes serve only listed clients. The key stays on your machine; governance lists its address.

    1. Make a key. The script needs a checkout of the oracle-node repository and Rust:

      bash
      scripts/client-key.sh --out client.key

      It prints the address. The file is hex, mode 0600. Keep it on the machine that runs your service, and use it for nothing else.

    2. Send the address and the expiry date you want to Markout Labs. Never send the file.

    3. Within a minute of the listing, your key can connect.

    3. Connect and read prices

    rust
    use oracle_client::{OracleClient, Signer, Status};
    
    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error>> {
        let key = Signer::from_hex(std::fs::read_to_string("client.key")?.trim())?;
        let mut client = OracleClient::mainnet().await?.client_key(key).build()?;
    
        client.subscribe(&["CRYPTO.BTC/USD"]).await?;
        while let Some(price) = client.next().await {
            match price.status {
                Status::Ok | Status::Degraded => {
                    // Act on `price.conf`, not only on `price.price`.
                    println!("{:?} ± {:?}", price.price, price.conf);
                }
                Status::Halted => println!("halted: {:?}", price.concerns),
            }
        }
        Ok(())
    }

    OracleClient::mainnet() fetches the mainnet registry from its trust root, which the crate knows, and keeps it fresh. For a local network, use OracleClient::builder_from_source with your own source; see Test your integration.

    Keep next() or next_event() in a loop at all times: the client fetches registry updates inside it.

    What a price holds

    Resolved is the price for one feed, resolved across the nodes.

    Field Meaning
    symbol The feed, such as CRYPTO.BTC/USD.
    status Ok, Degraded or Halted.
    price The median of the node prices. None when halted.
    conf The ± band: the larger of the nodes' own bands and half the spread between nodes. None when halted.
    nodes How many nodes contributed.
    concerns Why the status is not Ok, such as insufficient_nodes or node_divergence.
    publish_time_ns The newest node publish time, in unix nanoseconds.
    spread_bps The spread between nodes, in basis points of the median.
    Status What your app does
    Ok Use price and conf.
    Degraded Use price. Size the risk from conf. Read concerns.
    Halted Do not settle or liquidate. Wait for the next event.

    is_usable() is true for Ok and Degraded. Resolved serializes with serde; decimals and times become strings.

    Settings

    The builder takes these. The defaults suit a service on mainnet.

    Method Default Effect
    client_key(Signer) none Your listed key. Necessary to subscribe.
    quorum(usize) 3 The nodes that must agree before you get a price. Below 3 is refused; see below.
    max_age(Duration) 2 s The oldest update that counts. An older node leaves the quorum.
    slow_max_age(Duration) 25 s The same limit for a funding or open interest feed. The nodes publish these feeds every 10 s.
    max_divergence_bps(Fixed) 50 The spread between nodes above which a feed is Degraded.
    max_skew(Duration) 500 ms How far a node clock may run ahead of yours.
    idle_timeout(Duration) 30 s Dial a node again after this long without a message.
    registry_poll_interval(Duration) 60 s How often to look for a new registry version.

    A quorum below 3 gives no protection against one bad node, so build refuses it unless you call i_understand_this_provides_no_protection_against_a_bad_node(). Use that only for local development against one node.

    More streams

    Each subscription takes feed symbols and adds to the wanted set. subscribe_all takes every list in one call.

    Method next_event yields What it is
    subscribe(&[..]) Event::Price(Resolved) The resolved price.
    subscribe_venues(&[..]) Event::Venues(AcceptedVenues) One node's view of each venue of a feed: bid, ask, sizes, mark, index.
    subscribe_books(&[..]) Event::Book(AcceptedBook) One node's book of a venue; read it with client.book().
    subscribe_funding(&[..]) Event::Funding(AcceptedFunding) One node's funding of a perpetual; "*" for all.
    rust
    use oracle_client::{Event, Subscription};
    
    client
        .subscribe_all(Subscription {
            prices: &["CRYPTO.BTC/USD"],
            venues: &["CRYPTO.BTC/USDT"],
            ..Subscription::default()
        })
        .await?;
    
    while let Some(event) = client.next_event().await {
        match event {
            Event::Price(price) if price.is_usable() => { /* size the risk from price.conf */ }
            Event::Price(_) => { /* halted: never settle or liquidate now */ }
            Event::Venues(accepted) => {
                for entry in &accepted.report.entries {
                    println!("{} {}:{} {}", accepted.signer, entry.venue, entry.market, entry.status);
                }
            }
            _ => {}
        }
    }

    You observe state, not transitions: read status on each event, and do not count halts. resolve(&symbol, now_ns) resolves a feed again without a new frame; call it on a timer, so that a silent upstream shows as Halted.

    Monitoring

    • client.stats() counts the frames accepted and rejected, by reason.
    • client.latency() gives the delivery delay of each node, as percentiles.
    • client.nodes(now_ns) gives each node's connection state and the age of each feed.

    Test your integration

    scripts/dev-stack.sh in the oracle-node repository starts the registry canister on a local network, three nodes and one listed client key. When the nodes serve, it writes target/dev-stack/stack.env with CANISTER, GATEWAY, ROOT_KEY, GOVERNANCE and CLIENT_KEY. Build the client from these values:

    rust
    use std::sync::Arc;
    
    use oracle_client::{Address, Certification, HttpRegistrySource, OracleClient, Signer};
    
    /// The arguments are the values in target/dev-stack/stack.env.
    async fn local_client(
        canister: &str,
        gateway: &str,
        root_key: &str,
        governance: &str,
        client_key_file: &str,
    ) -> Result<OracleClient, Box<dyn std::error::Error>> {
        let certification = Certification::new(canister, root_key)?;
        // On a local network, the gateway finds the canister by the query.
        let url = format!("{gateway}/registry.json?canisterId={canister}");
        let source = Arc::new(HttpRegistrySource::new(&url, certification)?);
        let governance: Address = governance.parse()?;
        let key = Signer::from_hex(std::fs::read_to_string(client_key_file)?.trim())?;
        let client = OracleClient::builder_from_source(source, governance)
            .await?
            .client_key(key)
            .build()?;
        Ok(client)
    }

    With NODES=1 scripts/dev-stack.sh, the registry lists one node. Then add .quorum(1) and .i_understand_this_provides_no_protection_against_a_bad_node() before build().

    oracle_client::testing has fakes for unit tests: a registry, signers and signed frames, so that a test needs no network.