Skip to content

Commit

Permalink
feat: update to new sdk (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
Serial-ATA authored Jan 24, 2025
1 parent 68de70d commit 5f46ad5
Show file tree
Hide file tree
Showing 9 changed files with 11,357 additions and 5,086 deletions.
16,221 changes: 11,218 additions & 5,003 deletions Cargo.lock

Large diffs are not rendered by default.

22 changes: 5 additions & 17 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,14 @@ keywords = ["tangle", "blueprint", "avs"]
rust-version = "1.81"

[dependencies]
tracing = "0.1"
async-trait = "0.1"
color-eyre = "0.6"
structopt = "0.3.26"
tokio = { version = "^1", default-features = false, features = ["full"] }
tracing-subscriber = { version = "0.3", features = ["parking_lot", "env-filter"] }

[dependencies.gadget-sdk]
version = "0.4.0"
default-features = false
features = ["getrandom"]
blueprint-sdk = { git = "https://github.com/tangle-network/gadget", features = ["tangle", "macros"] }

[build-dependencies]
blueprint-metadata = "0.1.6"
# TODO: Replace with versioned release
blueprint-build-utils = { git = "https://github.com/tangle-network/gadget" }
blueprint-sdk = { git = "https://github.com/tangle-network/gadget", features = ["build"] }

[features]
default = ["std"]
std = ["gadget-sdk/std"]
[dev-dependencies]
blueprint-sdk = { git = "https://github.com/tangle-network/gadget", features = ["testing", "tangle"] }
color-eyre = "0.6.3"

[lib]
path = "src/lib.rs"
Expand Down
41 changes: 22 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
# <h1 align="center"> A Tangle Blueprint 🌐 </h1>
# <h1 align="center">Hello World Tangle Blueprint 🌐</h1>

**A simple Hello World Blueprint for Tangle**
## 📚 Overview

This Tangle Blueprint provides a simple Hello World job.
Blueprints are specifications for <abbr title="Actively Validated Services">AVS</abbr>s on the Tangle Network. An AVS is
an off-chain service that runs arbitrary computations for a user-specified period of time.

Blueprints provide a useful abstraction, allowing developers to create reusable service infrastructures as if they were
smart contracts. This enables developers to monetize their work and align long-term incentives with the success of their
creations, benefiting proportionally to their Blueprint's usage.

For more details, please refer to the [project documentation](https://docs.tangle.tools/developers/blueprints/introduction).

## 🚀 Features

- Custom greeting messages
- Default "Hello World!" messages
- ...

## 📚 Prerequisites
## 📋 Prerequisites

Before you can run this project, you will need to have the following software installed on your machine:

- [Rust](https://www.rust-lang.org/tools/install)
- [Forge](https://getfoundry.sh)
- [Tangle](https://github.com/tangle-network/tangle?tab=readme-ov-file#-getting-started-)

You will also need to install [cargo-tangle](https://crates.io/crates/cargo-tangle), our CLI tool for creating and
deploying Tangle Blueprints:
Expand All @@ -27,7 +42,7 @@ Or, if you prefer to install the CLI from crates.io:
cargo install cargo-tangle --force # to get the latest version.
```

## 🚀 Getting Started
## Getting Started

Once `cargo-tangle` is installed, you can create a new project with the following command:

Expand All @@ -53,18 +68,6 @@ cargo tangle blueprint deploy

to deploy the blueprint to the Tangle network.

## 📚 Overview

This project is about creating a simple Hello World Blueprint for Tangle and EigenLayer.
Blueprints are specifications for <abbr title="Actively Validated Services">AVS</abbr>s on the Tangle Network. An AVS is
an off-chain service that runs arbitrary computations for a user-specified period of time.

Blueprints provide a useful abstraction, allowing developers to create reusable service infrastructures as if they were
smart contracts. This enables developers to monetize their work and align long-term incentives with the success of their
creations, benefiting proportionally to their Blueprint's usage.

For more details, please refer to the [project documentation](https://docs.tangle.tools/developers/blueprints).

## 📜 License

Licensed under either of
Expand All @@ -79,8 +82,8 @@ at your option.
## 📬 Feedback and Contributions

We welcome feedback and contributions to improve this blueprint.
Please open an issue or submit a pull request on
our [GitHub repository](https://github.com/tangle-network/blueprint-template/issues).
Please open an issue or submit a pull request on our GitHub repository.
Please let us know if you fork this blueprint and extend it too!

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
Expand Down
13 changes: 8 additions & 5 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
fn main() {
println!("cargo:rerun-if-changed=src/main.rs");
blueprint_metadata::generate_json();
use blueprint_sdk::build;

fn main() {
let contract_dirs: Vec<&str> = vec!["./contracts"];
blueprint_build_utils::soldeer_update();
blueprint_build_utils::build_contracts(contract_dirs);
build::utils::soldeer_update();
build::utils::build_contracts(contract_dirs);

println!("cargo:rerun-if-changed=src/lib.rs");
println!("cargo:rerun-if-changed=src/main.rs");
build::blueprint_metadata::generate_json();
}
49 changes: 27 additions & 22 deletions contracts/src/HelloBlueprint.sol
Original file line number Diff line number Diff line change
Expand Up @@ -13,52 +13,57 @@ contract HelloBlueprint is BlueprintServiceManagerBase {
* @dev Hook for service operator registration. Called when a service operator
* attempts to register with the blueprint.
* @param operator The operator's details.
* @param _registrationInputs Inputs required for registration.
* @param registrationInputs Inputs required for registration in bytes format.
*/
function onRegister(
ServiceOperators.OperatorPreferences calldata operator,
bytes calldata _registrationInputs
bytes calldata registrationInputs
)
public
payable
override
onlyFromRootChain
external
payable
virtual
override
onlyFromMaster
{
// Do something with the operator's details
}

/**
* @dev Hook for service instance requests. Called when a user requests a service
* instance from the blueprint.
* @param params The parameters for the service request.
* @dev Hook for service instance requests. Called when a user requests a service
* instance from the blueprint but this does not mean the service is initiated yet.
* To get notified when the service is initiated, implement the `onServiceInitialized` hook.
*
* @param params The parameters for the service request.
*/
function onRequest(ServiceOperators.RequestParams calldata params)
public
payable
override
onlyFromRootChain
function onRequest(ServiceOperators.RequestParams calldata params) external payable virtual override onlyFromMaster
{
// Do something with the service request
}

/**
* @dev Hook for handling job call results. Called when operators send the result
* @dev Hook for handling job result. Called when operators send the result
* of a job execution.
* @param serviceId The ID of the service related to the job.
* @param job The job identifier.
* @param _jobCallId The unique ID for the job call.
* @param jobCallId The unique ID for the job call.
* @param operator The operator sending the result in bytes format.
* @param _inputs Inputs used for the job execution.
* @param _outputs Outputs resulting from the job execution.
* @param inputs Inputs used for the job execution in bytes format.
* @param outputs Outputs resulting from the job execution in bytes format.
*/
function onJobResult(
uint64 serviceId,
uint8 job,
uint64 _jobCallId,
uint64 jobCallId,
ServiceOperators.OperatorPreferences calldata operator,
bytes calldata _inputs,
bytes calldata _outputs
) public payable virtual override onlyFromRootChain {
bytes calldata inputs,
bytes calldata outputs
)
external
payable
virtual
override
onlyFromMaster
{
// Do something with the job call result
}

Expand Down
3 changes: 1 addition & 2 deletions rust-toolchain.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
# Currently we are using this specific nightly version since we rely on the
# rustdoc API which is not yet stabilized. We will keep updating this version
# as we go along.
channel = "nightly-2024-10-13"
channel = "nightly-2025-01-22"
components = ["rustfmt", "clippy", "rust-src"]
targets = ["wasm32-unknown-unknown"]
profile = "minimal"
24 changes: 14 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
use api::services::events::JobCalled;
use gadget_sdk as sdk;
use sdk::event_listener::tangle::{
jobs::{services_post_processor, services_pre_processor},
TangleEventListener,
use blueprint_sdk::config::GadgetConfiguration;
use blueprint_sdk::event_listeners::tangle::events::TangleEventListener;
use blueprint_sdk::event_listeners::tangle::services::{
services_post_processor, services_pre_processor,
};
use sdk::tangle_subxt::tangle_testnet_runtime::api;
use blueprint_sdk::macros::contexts::{ServicesContext, TangleClientContext};
use blueprint_sdk::tangle_subxt::tangle_testnet_runtime::api;

use std::convert::Infallible;

#[derive(Clone)]
#[derive(Clone, TangleClientContext, ServicesContext)]
pub struct ServiceContext {
pub config: sdk::config::StdGadgetConfiguration,
#[config]
pub config: GadgetConfiguration,
#[call_id]
pub call_id: Option<u64>,
}

/// Returns "Hello World!" if `who` is `None`, otherwise returns "Hello, {who}!"
#[sdk::job(
#[blueprint_sdk::job(
id = 0,
params(who),
result(_),
Expand All @@ -37,8 +41,8 @@ mod tests {

#[test]
fn it_works() {
let config = sdk::config::StdGadgetConfiguration::default();
let context = ServiceContext { config };
let config = GadgetConfiguration::default();
let context = ServiceContext { config, call_id: None };
let result = say_hello(None, context.clone()).unwrap();
assert_eq!(result, "Hello World!");
let result = say_hello(Some("Alice".to_string()), context).unwrap();
Expand Down
17 changes: 9 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
use color_eyre::Result;
use blueprint_sdk::logging;
use blueprint_sdk::runners::core::runner::BlueprintRunner;
use blueprint_sdk::runners::tangle::tangle::TangleConfig;
use {{project-name | snake_case}} as blueprint;
use gadget_sdk as sdk;
use sdk::runners::tangle::TangleConfig;
use sdk::runners::BlueprintRunner;

#[sdk::main(env)]
async fn main() -> Result<()> {
#[blueprint_sdk::main(env)]
async fn main() {
// Create your service context
// Here you can pass any configuration or context that your service needs.
let context = blueprint::ServiceContext {
config: env.clone(),
call_id: None,
};

// Create the event handler from the job
let say_hello_job = blueprint::SayHelloEventHandler::new(&env, context).await?;

tracing::info!("Starting the event watcher ...");
logging::info!("Starting the event watcher ...");
let tangle_config = TangleConfig::default();
BlueprintRunner::new(tangle_config, env)
.job(say_hello_job)
.run()
.await?;

tracing::info!("Exiting...");
logging::info!("Exiting...");
Ok(())
}

53 changes: 53 additions & 0 deletions tests/e2e.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use blueprint_sdk::logging;
use blueprint_sdk::testing::tempfile;
use blueprint_sdk::testing::utils::harness::TestHarness;
use blueprint_sdk::testing::utils::runner::TestEnv;
use blueprint_sdk::testing::utils::tangle::blueprint_serde::to_field;
use blueprint_sdk::testing::utils::tangle::TangleTestHarness;
use blueprint_sdk::tokio;
use {{project-name | snake_case}}::{SayHelloEventHandler, ServiceContext};

#[tokio::test]
async fn test_blueprint() -> color_eyre::Result<()> {
logging::setup_log();

// Initialize test harness (node, keys, deployment)
let temp_dir = tempfile::TempDir::new()?;
let harness = TangleTestHarness::setup(temp_dir).await?;
let env = harness.env().clone();

// Create blueprint-specific context
let blueprint_ctx = ServiceContext {
config: env.clone(),
call_id: None,
};

// Initialize event handler
let handler = SayHelloEventHandler::new(&env.clone(), blueprint_ctx)
.await
.unwrap();

// Setup service
let (mut test_env, service_id) = harness.setup_services().await?;
test_env.add_job(handler);

tokio::spawn(async move {
test_env.run_runner().await.unwrap();
});

// Execute job and verify result
let job_inputs = vec![to_field("Alice").unwrap()];
let expected_outputs = vec![to_field("Hello, Alice!").unwrap()];

let results = harness
.execute_job(
service_id,
0,
job_inputs,
expected_outputs,
)
.await?;

assert_eq!(results.service_id, service_id);
Ok(())
}

0 comments on commit 5f46ad5

Please sign in to comment.