From 0b5629962d19df7c8d88222f6c17fc7ba1a3c169 Mon Sep 17 00:00:00 2001 From: i1i1 Date: Sun, 18 Sep 2022 22:10:02 +0300 Subject: [PATCH] Add example --- Cargo.toml | 3 ++ examples/simple.rs | 90 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 examples/simple.rs diff --git a/Cargo.toml b/Cargo.toml index e0f83b11..eeb60bca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,3 +7,6 @@ edition = "2021" [dependencies] libp2p-core = "0.36" + +[dev-dependencies] +tokio = { version = "1.21", features = ["rt-multi-thread", "macros"] } diff --git a/examples/simple.rs b/examples/simple.rs new file mode 100644 index 00000000..0c23ab46 --- /dev/null +++ b/examples/simple.rs @@ -0,0 +1,90 @@ +#![allow(unreachable_code, unused_variables, clippy::diverging_sub_expression)] + +use std::{future::Future, pin::Pin}; + +use subspace_sdk::{ + Farmer, FarmerBuilder, Network, Node, NodeBuilder, NodeMode, PlotDescription, RewardAddress, +}; + +#[tokio::main] +async fn main() { + let mut node: Node = NodeBuilder::new() + .mode(NodeMode::Full) + .network(Network::Gemini2a) + .name("i1i1") + .port(1337) + .directory("node") + .build() + .await + .expect("Failed to init a node"); + + node.sync().await; + + let reward_address: RewardAddress = todo!("Can't construct reward address right now :("); + let mut farmer: Farmer = FarmerBuilder::new() + .node(node.clone()) + .plot(PlotDescription::new("plot", 10 * 1024 * 1024 * 1024)) + .ws_rpc("127.0.0.1:9955".parse().unwrap()) + .listen_on("/ip4/0.0.0.0/tcp/40333".parse().unwrap()) + .reward_address(reward_address) + .build() + .await + .expect("Failed to init a farmer"); + + farmer.sync().await; + + farmer + .on_solution(|solution| { + // Yeah very cumbersome, but rust can't coerce types here. + // TODO: look into https://doc.rust-lang.org/stable/std/ops/trait.CoerceUnsized.html + let fut: Pin>> = Box::pin(async move { + eprintln!("Found solution: {solution:?}"); + }); + fut + }) + .await; + node.on_block(|block| { + let fut: Pin>> = Box::pin(async move { + eprintln!("New block: {block:?}"); + }); + fut + }) + .await; + + farmer.start_farming().await; + + dbg!(node.get_info().await); + dbg!(farmer.get_info().await); + + farmer.stop_farming().await; + farmer.close().await; + node.close().await; + + // Restarting + let mut node = NodeBuilder::new() + .mode(NodeMode::Full) + .network(Network::Gemini2a) + .directory("node") + .build() + .await + .expect("Failed to init a node"); + node.sync().await; + + let mut farmer = FarmerBuilder::new() + .node(node.clone()) + .plot(PlotDescription::new("plot", 10 * 1024 * 1024 * 1024)) + .reward_address(reward_address) + .build() + .await + .expect("Failed to init a farmer"); + + farmer.sync().await; + farmer.start_farming().await; + + // Delete everything + for plot in farmer.plots().await { + plot.delete().await; + } + farmer.wipe().await; + node.wipe().await; +}