Skip to content

Commit

Permalink
Merge pull request #2 from starkbamse/add-metadata
Browse files Browse the repository at this point in the history
Add metadata
  • Loading branch information
saefstroem authored May 16, 2024
2 parents 790a88b + 76a00e5 commit c69d2f9
Show file tree
Hide file tree
Showing 7 changed files with 127 additions and 54 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
rustlink.log
/target
/js
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
name = "rustlink"
version = "0.0.1"
edition = "2021"
license = "MIT OR Apache-2.0"
description = "A lightweight and easy-to-use library for periodically retrieving data from the Chainlink decentralized data feed."
repository = "https://github.com/starkbamse/rustlink"
include = ["**/*.json"]
keywords = ["crypto", "cryptocurrencies","chainlink","prices"]

[dependencies]
log = "0.4.21"
Expand Down
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,37 @@ To use `rustlink` in your project, add the following to your `Cargo.toml` file:
rustlink = "0.0.1"
```

## Build for WASM

1. ### Prerequisites
To build the library for WASM, you need to have the `wasm-pack` tool installed. You can install it by running the following command:

```bash
cargo install wasm-pack
```

You also need the wasm32-unknown-unknown target installed. You can install it by running the following command:

```bash
rustup target add wasm32-unknown-unknown
```

2. ### Building WASM
You can build the library either for the **browser** or for **Node.js**.

**For the browser:**

```bash
./web-build.sh
```

**For Node.js:**

```bash
./node-build.sh
```


## Usage
Here is a simple example of how you can use `rustlink` to retrieve the latest price of a cryptocurrency:

Expand Down Expand Up @@ -67,4 +98,36 @@ loop {
let round_data = receiver.recv().await.unwrap();
println!("Received data: {:#?}", round_data);
}
```

## WASM Usage

```javascript
import init, { RustlinkJS } from '../web/rustlink.js';
async function runWasm() {
await init(); // Initialize the wasm module
// Example data
const rpcUrl = "https://bsc-dataseed1.binance.org/";
const fetchIntervalSeconds = BigInt(1);
const contracts = [
["ETH", "0x9ef1B8c0E4F7dc8bF5719Ea496883DC6401d5b2e"],
["1INCH", "0x9a177Bb9f5b6083E962f9e62bD21d4b5660Aeb03"],
];
async function callback(roundData) {
console.log("Callback received:", roundData);
}
let rustlink = new RustlinkJS(rpcUrl, fetchIntervalSeconds, contracts, callback);
rustlink.start();
console.log("Stopping after 5 seconds");
setTimeout(() => {
rustlink.stop();
}, 5000);
}
runWasm();
```
40 changes: 0 additions & 40 deletions js/index.html

This file was deleted.

4 changes: 2 additions & 2 deletions src/fetcher/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use async_std::stream::StreamExt;
use futures::{select, FutureExt};

use super::interface::{ChainlinkContract, Round};
use crate::config::Reflector::Sender;
use crate::config::{Configuration, Rustlink};
use crate::rustlink::Reflector::Sender;
use crate::rustlink::{Configuration, Rustlink};

/// Retrieves the price of an underlying asset from a particular contract
async fn fetch_round_data_for_contract(
Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pub mod config;
pub mod rustlink;
mod error;
mod fetcher;
mod interface;
Expand All @@ -7,7 +7,7 @@ mod tests {

use async_std::channel::unbounded;

use crate::config::{Reflector, Rustlink};
use crate::rustlink::{Reflector, Rustlink};

#[tokio::test]
async fn ensure_price_is_received() {
Expand Down
64 changes: 54 additions & 10 deletions src/config.rs → src/rustlink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,25 @@ use workflow_rs::core::cfg_if;
use std::str::FromStr;
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
use wasm_bindgen_futures::spawn_local;

/// ## Configuration
/// This struct contains the configuration for Rustlink. It contains the following fields:
/// - `fetch_interval_seconds`: How often to update data points (to prevent RPC rate limitation)
/// - `contracts`: A list of tuples containing a ticker name and its corresponding contract address on the EVM chain
/// - `provider`: The provider to use for fetching data
#[derive(Clone)]
pub struct Configuration {
pub fetch_interval_seconds: u64,
pub contracts: Vec<(String, String)>,
pub provider: RootProvider<Http<Client>>,
}

/// ## Rustlink
/// ## Rustlink instance. This is the main struct that you will interact with.
///
/// Rustlink is a lightweight Rust library that provides your Rust applications with a direct
/// link to the latest cryptocurrency prices. All data is retrieved from Chainlink decentralized
/// price feeds. Just copy the contract addresses for the symbol that you would like to track from:
/// https://data.chain.link/feeds.
///
///
/// Note: Rustlink is designed to be ran on the main thread, in an asynchronous tokio environment
#[derive(Clone)]
pub struct Rustlink {
pub configuration: Configuration,
Expand Down Expand Up @@ -64,7 +67,6 @@ impl Rustlink {
///
/// Expected parameters:
/// - `rpc_url`: The RPC url of your chosen EVM network where Chainlink offers decentralised data feeds.
/// Don't know where? Check https://data.chain.link/feeds.
/// - `fetch_interval_seconds`: How often to update data points in the database (to prevent RPC rate limitation)
/// - `reflector`: How you choose to receive the answer from your provided contracts.
/// - `contracts`: A tuple list containing a ticker name and its corresponding contract address on the
Expand Down Expand Up @@ -98,8 +100,6 @@ impl Rustlink {
/// let round_data = receiver.recv().await.unwrap();
/// println!("Received data: {:#?}", round_data);
/// }
///
///
/// ```
pub fn try_new(
rpc_url: &str,
Expand All @@ -125,21 +125,26 @@ impl Rustlink {
})
}

/// Starts the Rustlink instance.
/// This method will start fetching the latest price data from the Chainlink decentralized data feed.
pub fn start(&self) {
#[cfg(not(target_arch = "wasm32"))]
tokio::task::spawn(fetch_rounds(self.clone()));

#[cfg(target_arch = "wasm32")]
async_std::task::block_on(fetch_rounds(self.clone()));


}

/// Stops the Rustlink instance.
/// This method will stop fetching the latest price data from the Chainlink decentralized data feed.
pub async fn stop(&self) -> Result<(), RecvError> {
self.termination_send.send(()).await.unwrap();
self.shutdown_recv.recv().await
}
}

/// RustlinkJS is a JavaScript wrapper for Rustlink.
/// It allows you to create a Rustlink instance in JavaScript and start fetching data when you use WASM.
#[wasm_bindgen]
pub struct RustlinkJS {
rustlink: Rustlink,
Expand Down Expand Up @@ -174,7 +179,41 @@ extern "C" {

#[wasm_bindgen]
impl RustlinkJS {
/// Creates a new RustlinkJS instance
/// Creates a new RustlinkJS instance.
/// Expected parameters:
/// - `rpc_url`: The RPC url of your chosen EVM network where Chainlink offers decentralised data feeds.
/// - `fetch_interval_seconds`: How often to update data points (to prevent RPC rate limitation)
/// - `contracts`: A list of tuples containing a ticker name and its corresponding contract address on the EVM chain
/// - `callback`: A JavaScript function (async or sync) that will be called every time a new data point is fetched
/// ```javascript
/// import init, { RustlinkJS } from '../web/rustlink.js';
///
/// async function runWasm() {
/// await init(); // Initialize the wasm module
///
/// // Example data
/// const rpcUrl = "https://bsc-dataseed1.binance.org/";
/// const fetchIntervalSeconds = BigInt(1);
/// const contracts = [
/// ["ETH", "0x9ef1B8c0E4F7dc8bF5719Ea496883DC6401d5b2e"],
/// ["1INCH", "0x9a177Bb9f5b6083E962f9e62bD21d4b5660Aeb03"],
/// ];
///
/// async function callback(roundData) {
/// console.log("Callback received:", roundData);
/// }
///
/// let rustlink = new RustlinkJS(rpcUrl, fetchIntervalSeconds, contracts, callback);
///
/// rustlink.start();
/// console.log("Stopping after 5 seconds");
/// setTimeout(() => {
/// rustlink.stop();
/// }, 5000);
/// }
///
/// runWasm();
/// ```
#[wasm_bindgen(constructor)]
pub fn new(
rpc_url: &str,
Expand All @@ -200,6 +239,9 @@ impl RustlinkJS {
receiver,
}
}

/// Starts the RustlinkJS instance.
/// This method will start fetching the latest price data from the Chainlink decentralized data feed.
#[wasm_bindgen]
pub fn start(&self) {
self.rustlink.start();
Expand All @@ -217,6 +259,8 @@ impl RustlinkJS {
});
}

/// Stops the RustlinkJS instance.
/// This method will stop fetching the latest price data from the Chainlink decentralized data feed.
#[wasm_bindgen]
pub async fn stop(&self) -> Result<(), JsValue> {
self.rustlink
Expand Down

0 comments on commit c69d2f9

Please sign in to comment.