Holochain Forum

Making a websocket call to a zome from a RUST program

Hi guys.
I’m building some logic in native RUST and want it to call my zome via websockets.
everything tests and works from JS and I can call my zome functions and retrieve the result, but wanting to replicate the logic and make the same call from my RUST program.
I’ve been playing trying to get it to work using the WS-RS Crate but haven’t been successful.

Wondering are there any crates people might recommend they’ve used before for interacting with dna via websocket from Rust.
And if there is and you’ve done it would you be able to share any code examples from your Rust program?

For my purpose I want to replicate the following JS call that works:

  function set() {
    const price = document.getElementById('price').value;
      holochain_connection.then(({callZome, close}) => {
        callZome('test-instance', 'zome', 'set_price')({
          price: {price: price},
        }).then(result => console.log(result));//show_price(result, 'address_output'));
      });
    }

Lastly; Is there somewhere I should look to add my code snippet when I get it going in case it can help others looking to call a zome over websocket via Rust rather than JS?
Thankyou all.

:):pray:

Well I was actually working on this yesterday :slight_smile:
I used this crate https://crates.io/crates/websocket
This is the file where all the websocket stuff happens.
I wrote this in a few hours so it’s very messy and I wasn’t planning on sharing it yet but it should be helpful.
This is probably the line you care about the most.
Basically just use serde to turn your data into a JSON object, then flatten it into a String, and send over the websocket connect.

Note I’m not handling closing the connection or anything like that yet. I’d check out the sync or async examples for better practices.

1 Like

Thanks Tom.
I got it going :muscle::raised_hands:

I used a different ‘crate’ RS-WD.
Here’s my code:

// Call into HoloChain ZOME to GET Current Figure.
   // websockets need to create some logic that updates the DHT given certain price thresholds..
    fn set_to_dht(_price: String) {
        let json = serde_json::json!(
            {"id": "0",
             "jsonrpc": "2.0",
             "method": "call",
             "params": {"instance_id": "test-instance",
             "zome": "spot_signal",
             "function": "set_price",
             "args": {"price": {"price": _price }}
         }});
        connect("ws://localhost:3401", |out| {
        // call an RPC method with parameters
        out.send(json.to_string()).unwrap();
        move |msg| {
            println!("Got message: {:#?}", msg);
            out.close(CloseCode::Normal)
            }
        }).unwrap();
    }

The serde conversion did the trick! Thanks Tom!

1 Like