Skip to content

Commit

Permalink
chore: update to use new job runner (#16)
Browse files Browse the repository at this point in the history
Co-authored-by: shekohex <[email protected]>
  • Loading branch information
Serial-ATA and shekohex authored Oct 24, 2024
1 parent 7b27edf commit 4a1b73b
Show file tree
Hide file tree
Showing 9 changed files with 1,757 additions and 3,647 deletions.
5,264 changes: 1,665 additions & 3,599 deletions Cargo.lock

Large diffs are not rendered by default.

19 changes: 16 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,17 @@ structopt = "0.3.26"
tokio = { version = "1.39", default-features = false, features = ["full"] }
tracing-subscriber = { version = "0.3", features = ["parking_lot", "env-filter"] }

[features]
default = ["std"]
std = ["gadget-sdk/std"]

[dependencies.gadget-sdk]
version = "0.1.1"
version = "0.2.2"
default-features = false
features = ["std", "getrandom"]
features = ["getrandom"]

[build-dependencies]
blueprint-metadata = "0.1.2"
blueprint-metadata = "0.1.5"

[lib]
path = "src/lib.rs"
Expand All @@ -37,3 +41,12 @@ path = "src/main.rs"

[package.metadata.blueprint]
manager = { evm = "HelloBlueprint" }

[[package.metadata.gadget.Native.sources]]
owner = "{{gh-username}}"
repo = "{{project-name}}"
tag = "0.1.0"
binaries = [
{ arch = "Amd64", os = "Linux", name = "amd64-linux-{{project-name}}-gadget" },
{ arch = "Arm64", os = "Linux", name = "arm64-linux-{{project-name}}-gadget" },
]
6 changes: 3 additions & 3 deletions cargo-generate.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ prompt = "Do you want to use Nix & Nix Flakes?"
default = false

[conditional.'!flakes']
ignore = [ "flake.nix", "flake.lock", ".envrc" ]
ignore = ["flake.nix", "flake.lock", ".envrc"]

[placeholders.docker]
type = "bool"
prompt = "Do you want to generate a Dockerfile for your gadget?"
default = true

[conditional.'!docker']
ignore = [ "Dockerfile", "docker/" ]
ignore = ["Dockerfile", "docker/"]

[conditional.'docker'.placeholders]
base-image = { type = "string", prompt = "What base image should be used?", default = "rustlang/rust:nightly" }
base-image = { type = "string", prompt = "What base image should be used?", default = "rustlang/rust:nightly" }
8 changes: 4 additions & 4 deletions contracts/src/HelloBlueprint.sol
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import "core/BlueprintServiceManagerBase.sol";
/**
* @title HelloBlueprint
* @dev This contract is an example of a service blueprint that provides a single service.
* @note For all supported hooks, check the `BlueprintServiceManagerBase` contract.
* @dev For all supported hooks, check the `BlueprintServiceManagerBase` contract.
*/
contract HelloBlueprint is BlueprintServiceManagerBase {
/**
Expand Down Expand Up @@ -57,16 +57,16 @@ contract HelloBlueprint is BlueprintServiceManagerBase {
bytes calldata participant,
bytes calldata _inputs,
bytes calldata _outputs
) public virtual override onlyFromRootChain {
) public payable virtual override onlyFromRootChain {
// Do something with the job call result
}

/**
* @dev Converts a public key to an operator address.
* @param publicKey The public key to convert.
* @return address The operator address.
* @return operator address The operator address.
*/
function operatorAddressFromPublicKey(bytes calldata publicKey) internal pure returns (address) {
function operatorAddressFromPublicKey(bytes calldata publicKey) internal pure returns (address operator) {
return address(uint160(uint256(keccak256(publicKey))));
}
}
18 changes: 9 additions & 9 deletions flake.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion rust-toolchain.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# 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-09-20"
channel = "nightly-2024-10-13"
components = ["rustfmt", "clippy", "rust-src"]
targets = ["wasm32-unknown-unknown"]
profile = "minimal"
45 changes: 40 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,47 @@
use gadget_sdk as sdk;
use sdk::job;
use gadget_sdk::tangle_subxt::tangle_testnet_runtime::api;
use std::convert::Infallible;

/// Returns "Hello World!" if `who` is `None`, otherwise returns "Hello, <who>!"
#[job(id = 0, params(who), result(_), verifier(evm = "HelloBlueprint"))]
pub fn say_hello(who: Option<String>) -> Result<String, Infallible> {
use api::services::events::JobCalled;
use sdk::event_listener::tangle::{
jobs::{services_post_processor, services_pre_processor},
TangleEventListener,
};

#[derive(Clone)]
pub struct ServiceContext {
pub config: sdk::config::StdGadgetConfiguration,
}

/// Returns "Hello World!" if `who` is `None`, otherwise returns "Hello, {who}!"
#[sdk::job(
id = 0,
params(who),
result(_),
event_listener(
listener = TangleEventListener::<JobCalled, ServiceContext>,
pre_processor = services_pre_processor,
post_processor = services_post_processor,
),
)]
pub fn say_hello(who: Option<String>, context: ServiceContext) -> Result<String, Infallible> {
match who {
Some(who) => Ok(format!("Hello, {}!", who)),
Some(who) => Ok(format!("Hello, {who}!")),
None => Ok("Hello World!".to_string()),
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn it_works() {
let config = sdk::config::StdGadgetConfiguration::default();
let context = ServiceContext { config };
let result = say_hello(None, context).unwrap();
assert_eq!(result, "Hello World!");
let result = say_hello(Some("Alice".to_string()), context).unwrap();
assert_eq!(result, "Hello, Alice!");
}
}
40 changes: 18 additions & 22 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,12 @@
use color_eyre::Result;
use gadget_sdk as sdk;
use {{project-name | snake_case}} as blueprint;
use sdk::{
config::ContextConfig, events_watcher::substrate::SubstrateEventWatcher,
events_watcher::tangle::TangleEventsWatcher, tangle_subxt::*,
};
use structopt::StructOpt;
use gadget_sdk as sdk;
use gadget_sdk::job_runner::MultiJobRunner;
use sdk::tangle_subxt::*;

#[tokio::main]
#[sdk::main(env)]
async fn main() -> Result<()> {
init_logger();
color_eyre::install()?;

// Initialize the environment
let config = ContextConfig::from_args();
let env = sdk::config::load(config)?;
let signer = env.first_sr25519_signer()?;
let client = subxt::OnlineClient::from_url(&env.rpc_endpoint).await?;

Expand All @@ -24,20 +16,24 @@ async fn main() -> Result<()> {

let service_id = env.service_id.expect("should exist");

// Create your service context
// Here you can pass any configuration or context that your service needs.
let context = blueprint::ServiceContext {
config: env.clone(),
};

// Create the event handler from the job
let say_hello_job = blueprint::SayHelloEventHandler { service_id, signer };
let say_hello_job = blueprint::SayHelloEventHandler {
service_id,
client,
signer,
context,
};

tracing::info!("Starting the event watcher ...");
MultiJobRunner::new(env).job(say_hello_job).run().await?;

SubstrateEventWatcher::run(
&TangleEventsWatcher {
span: env.span.clone(),
},
client,
// Add more handler here if we have more functions.
vec![Box::new(say_hello_job)],
)
.await?;
tracing::info!("Exiting...");
Ok(())
}

Expand Down

0 comments on commit 4a1b73b

Please sign in to comment.