From 3499d0fecdb57179cc9f65a0ebc4cdfe98b69a10 Mon Sep 17 00:00:00 2001 From: Shady Khalifa Date: Mon, 21 Oct 2024 20:50:51 +0300 Subject: [PATCH 1/5] chore: update to latest tangle --- Cargo.lock | 6 +- Cargo.toml | 2 +- blueprint-test-utils/src/lib.rs | 6 +- blueprint-test-utils/src/test_ext.rs | 6 +- .../contracts/lib/forge-std | 2 +- .../contracts/lib/forge-std | 2 +- .../contracts/lib/tnt-core | 2 +- .../contracts/src/ERC20Mock.sol | 308 ------------------ .../src/IncredibleSquaringBlueprint.sol | 10 +- flake.lock | 18 +- sdk/src/clients/tangle/services.rs | 2 +- sdk/src/job_runner.rs | 4 +- 12 files changed, 28 insertions(+), 340 deletions(-) delete mode 100644 blueprints/incredible-squaring/contracts/src/ERC20Mock.sol diff --git a/Cargo.lock b/Cargo.lock index 1c652b1d..67dd3568 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8243,7 +8243,7 @@ dependencies = [ "parking_lot", "reqwest 0.12.8", "serde_json", - "sp-core 34.0.0", + "sp-core", "structopt", "subxt-signer", "tokio", @@ -11589,9 +11589,9 @@ dependencies = [ [[package]] name = "tangle-subxt" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6021db4ae4f20114d6ab52365a3dce19c884dbfe1f4aba546639e53ed6ad052" +checksum = "20bf7f8d29cfdb72ea840a6d58d9191b3573dc0309f1b94eee25848498f89c1a" dependencies = [ "parity-scale-codec", "scale-info", diff --git a/Cargo.toml b/Cargo.toml index fd359bf0..258457ca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,7 +57,7 @@ cargo-tangle = { path = "./cli", version = "0.1.2" } cargo_metadata = { version = "0.18.1" } # Tangle-related dependencies -tangle-subxt = { version = "0.3.0", default-features = false } +tangle-subxt = { version = "0.4.0", default-features = false } subxt-signer = { version = "0.37.0", default-features = false } subxt = { version = "0.37.0", default-features = false } subxt-core = { version = "0.37.0", default-features = false } diff --git a/blueprint-test-utils/src/lib.rs b/blueprint-test-utils/src/lib.rs index 5b5a28ad..217253e3 100644 --- a/blueprint-test-utils/src/lib.rs +++ b/blueprint-test-utils/src/lib.rs @@ -3,7 +3,7 @@ use api::services::events::JobResultSubmitted; use blueprint_manager::config::BlueprintManagerConfig; use blueprint_manager::executor::BlueprintManagerHandle; use gadget_io::{GadgetConfig, SupportedChains}; -use gadget_sdk::clients::tangle::runtime::{TangleClient}; +use gadget_sdk::clients::tangle::runtime::TangleClient; use gadget_sdk::tangle_subxt::tangle_testnet_runtime::api; use gadget_sdk::tangle_subxt::tangle_testnet_runtime::api::runtime_types; use gadget_sdk::tangle_subxt::tangle_testnet_runtime::api::services::calls::types::call::{Args, Job}; @@ -20,7 +20,6 @@ use std::error::Error; use std::net::IpAddr; use std::path::{Path, PathBuf}; use std::time::Duration; -use subxt::ext::sp_core::Pair; use subxt::tx::Signer; use subxt::utils::AccountId32; use url::Url; @@ -271,8 +270,9 @@ pub async fn register_service( blueprint_id, test_nodes.clone(), test_nodes, - 1000, Default::default(), + Default::default(), + 1000, ); let res = client .tx() diff --git a/blueprint-test-utils/src/test_ext.rs b/blueprint-test-utils/src/test_ext.rs index 30d1cf77..a329f629 100644 --- a/blueprint-test-utils/src/test_ext.rs +++ b/blueprint-test-utils/src/test_ext.rs @@ -21,8 +21,7 @@ use blueprint_manager::sdk::entry::SendFuture; use cargo_tangle::deploy::Opts; use gadget_sdk::clients::tangle::runtime::TangleClient; use gadget_sdk::tangle_subxt::subxt::OnlineClient; -use gadget_sdk::tangle_subxt::tangle_testnet_runtime::api::runtime_types; -use gadget_sdk::tangle_subxt::tangle_testnet_runtime::api::runtime_types::tangle_primitives::services::{ApprovalPrefrence, PriceTargets}; +use gadget_sdk::tangle_subxt::tangle_testnet_runtime::api::runtime_types::tangle_primitives::services::PriceTargets; use gadget_sdk::tangle_subxt::tangle_testnet_runtime::api::services::calls::types::register::{Preferences, RegistrationArgs}; use libp2p::Multiaddr; use std::collections::HashSet; @@ -154,11 +153,10 @@ pub async fn new_test_ext_blueprint_manager< let task = async move { let keypair = handle.sr25519_id().clone(); - let key = runtime_types::sp_core::ecdsa::Public(handle.ecdsa_id().signer().public().0); + let key = handle.ecdsa_id().signer().public().0; let preferences = Preferences { key, - approval: ApprovalPrefrence::None, price_targets: PriceTargets { cpu: 0, mem: 0, diff --git a/blueprints/incredible-squaring-eigenlayer/contracts/lib/forge-std b/blueprints/incredible-squaring-eigenlayer/contracts/lib/forge-std index 035de35f..1de6eecf 160000 --- a/blueprints/incredible-squaring-eigenlayer/contracts/lib/forge-std +++ b/blueprints/incredible-squaring-eigenlayer/contracts/lib/forge-std @@ -1 +1 @@ -Subproject commit 035de35f5e366c8d6ed142aec4ccb57fe2dd87d4 +Subproject commit 1de6eecf821de7fe2c908cc48d3ab3dced20717f diff --git a/blueprints/incredible-squaring/contracts/lib/forge-std b/blueprints/incredible-squaring/contracts/lib/forge-std index 035de35f..1de6eecf 160000 --- a/blueprints/incredible-squaring/contracts/lib/forge-std +++ b/blueprints/incredible-squaring/contracts/lib/forge-std @@ -1 +1 @@ -Subproject commit 035de35f5e366c8d6ed142aec4ccb57fe2dd87d4 +Subproject commit 1de6eecf821de7fe2c908cc48d3ab3dced20717f diff --git a/blueprints/incredible-squaring/contracts/lib/tnt-core b/blueprints/incredible-squaring/contracts/lib/tnt-core index fad7030f..c1fa9c7c 160000 --- a/blueprints/incredible-squaring/contracts/lib/tnt-core +++ b/blueprints/incredible-squaring/contracts/lib/tnt-core @@ -1 +1 @@ -Subproject commit fad7030fe53ea5d4a7576316880f5416fe656ee9 +Subproject commit c1fa9c7c3c5891aab9bd25002a434d93c54942cd diff --git a/blueprints/incredible-squaring/contracts/src/ERC20Mock.sol b/blueprints/incredible-squaring/contracts/src/ERC20Mock.sol deleted file mode 100644 index 4c6e3a21..00000000 --- a/blueprints/incredible-squaring/contracts/src/ERC20Mock.sol +++ /dev/null @@ -1,308 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol) - -pragma solidity >=0.8.13; - -import "@openzeppelin/contracts/interfaces/IERC20.sol"; -import "@openzeppelin/contracts/utils/Context.sol"; - -/** - * @dev Implementation of the {IERC20} interface. - * - * This implementation is agnostic to the way tokens are created. This means - * that a supply mechanism has to be added in a derived contract using {_mint}. - * For a generic mechanism see {ERC20PresetMinterPauser}. - * - * TIP: For a detailed writeup see our guide - * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How - * to implement supply mechanisms]. - * - * The default value of {decimals} is 18. To change this, you should override - * this function so it returns a different value. - * - * We have followed general OpenZeppelin Contracts guidelines: functions revert - * instead returning `false` on failure. This behavior is nonetheless - * conventional and does not conflict with the expectations of ERC20 - * applications. - * - * Additionally, an {Approval} event is emitted on calls to {transferFrom}. - * This allows applications to reconstruct the allowance for all accounts just - * by listening to said events. Other implementations of the EIP may not emit - * these events, as it isn't required by the specification. - * - * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} - * functions have been added to mitigate the well-known issues around setting - * allowances. See {IERC20-approve}. - */ -contract ERC20Mock is Context, IERC20 { - mapping(address => uint256) private _balances; - - mapping(address => mapping(address => uint256)) private _allowances; - - uint256 private _totalSupply; - - /** - * @dev See {IERC20-totalSupply}. - */ - function totalSupply() public view virtual override returns (uint256) { - return _totalSupply; - } - - /** - * @dev See {IERC20-balanceOf}. - */ - function balanceOf( - address account - ) public view virtual override returns (uint256) { - return _balances[account]; - } - - function mint(address account, uint256 amount) public { - _mint(account, amount); - } - - /** - * @dev See {IERC20-transfer}. - * - * Requirements: - * - * - `to` cannot be the zero address. - * - the caller must have a balance of at least `amount`. - */ - function transfer( - address to, - uint256 amount - ) public virtual override returns (bool) { - address owner = _msgSender(); - _transfer(owner, to, amount); - return true; - } - - /** - * @dev See {IERC20-allowance}. - */ - function allowance( - address owner, - address spender - ) public view virtual override returns (uint256) { - return _allowances[owner][spender]; - } - - /** - * @dev See {IERC20-approve}. - * - * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on - * `transferFrom`. This is semantically equivalent to an infinite approval. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function approve( - address /*spender*/, - uint256 /*amount*/ - ) public virtual override returns (bool) { - return true; - } - - /** - * @dev See {IERC20-transferFrom}. - * - * Emits an {Approval} event indicating the updated allowance. This is not - * required by the EIP. See the note at the beginning of {ERC20}. - * - * NOTE: Does not update the allowance if the current allowance - * is the maximum `uint256`. - * - * Requirements: - * - * - `from` and `to` cannot be the zero address. - * - `from` must have a balance of at least `amount`. - * - the caller must have allowance for ``from``'s tokens of at least - * `amount`. - */ - function transferFrom( - address from, - address to, - uint256 amount - ) public virtual override returns (bool) { - _transfer(from, to, amount); - return true; - } - - /** - * @dev Moves `amount` of tokens from `from` to `to`. - * - * This internal function is equivalent to {transfer}, and can be used to - * e.g. implement automatic token fees, slashing mechanisms, etc. - * - * Emits a {Transfer} event. - * - * Requirements: - * - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - `from` must have a balance of at least `amount`. - */ - function _transfer( - address from, - address to, - uint256 amount - ) internal virtual { - require(from != address(0), "ERC20: transfer from the zero address"); - require(to != address(0), "ERC20: transfer to the zero address"); - - _beforeTokenTransfer(from, to, amount); - - require( - _balances[from] >= amount, - "ERC20: transfer amount exceeds balance" - ); - unchecked { - _balances[from] = _balances[from] - amount; - // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by - // decrementing then incrementing. - _balances[to] += amount; - } - - emit Transfer(from, to, amount); - - _afterTokenTransfer(from, to, amount); - } - - /** @dev Creates `amount` tokens and assigns them to `account`, increasing - * the total supply. - * - * Emits a {Transfer} event with `from` set to the zero address. - * - * Requirements: - * - * - `account` cannot be the zero address. - */ - function _mint(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: mint to the zero address"); - - _totalSupply += amount; - unchecked { - // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. - _balances[account] += amount; - } - emit Transfer(address(0), account, amount); - } - - /** - * @dev Destroys `amount` tokens from `account`, reducing the - * total supply. - * - * Emits a {Transfer} event with `to` set to the zero address. - * - * Requirements: - * - * - `account` cannot be the zero address. - * - `account` must have at least `amount` tokens. - */ - function _burn(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: burn from the zero address"); - - _beforeTokenTransfer(account, address(0), amount); - - uint256 accountBalance = _balances[account]; - require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); - unchecked { - _balances[account] = accountBalance - amount; - // Overflow not possible: amount <= accountBalance <= totalSupply. - _totalSupply -= amount; - } - - emit Transfer(account, address(0), amount); - - _afterTokenTransfer(account, address(0), amount); - } - - /** - * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. - * - * This internal function is equivalent to `approve`, and can be used to - * e.g. set automatic allowances for certain subsystems, etc. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `owner` cannot be the zero address. - * - `spender` cannot be the zero address. - */ - function _approve( - address owner, - address spender, - uint256 amount - ) internal virtual { - require(owner != address(0), "ERC20: approve from the zero address"); - require(spender != address(0), "ERC20: approve to the zero address"); - - _allowances[owner][spender] = amount; - emit Approval(owner, spender, amount); - } - - /** - * @dev Updates `owner` s allowance for `spender` based on spent `amount`. - * - * Does not update the allowance amount in case of infinite allowance. - * Revert if not enough allowance is available. - * - * Might emit an {Approval} event. - */ - function _spendAllowance( - address owner, - address spender, - uint256 amount - ) internal virtual { - uint256 currentAllowance = allowance(owner, spender); - if (currentAllowance != type(uint256).max) { - require( - currentAllowance >= amount, - "ERC20: insufficient allowance" - ); - } - } - - /** - * @dev Hook that is called before any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * will be transferred to `to`. - * - when `from` is zero, `amount` tokens will be minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens will be burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual {} - - /** - * @dev Hook that is called after any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * has been transferred to `to`. - * - when `from` is zero, `amount` tokens have been minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens have been burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _afterTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual {} -} diff --git a/blueprints/incredible-squaring/contracts/src/IncredibleSquaringBlueprint.sol b/blueprints/incredible-squaring/contracts/src/IncredibleSquaringBlueprint.sol index 94b536d9..70071701 100644 --- a/blueprints/incredible-squaring/contracts/src/IncredibleSquaringBlueprint.sol +++ b/blueprints/incredible-squaring/contracts/src/IncredibleSquaringBlueprint.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.19; -import "tnt-core/BlueprintServiceManager.sol"; +import "tnt-core/BlueprintServiceManagerBase.sol"; /** * @title IncredibleSquaringBlueprint @@ -10,7 +10,7 @@ import "tnt-core/BlueprintServiceManager.sol"; * implemented in a service blueprint. */ -contract IncredibleSquaringBlueprint is BlueprintServiceManager { +contract IncredibleSquaringBlueprint is BlueprintServiceManagerBase { /** * @dev A mapping of all service operators registered with the blueprint. * The key is the operator's address and the value is the operator's details. @@ -33,14 +33,14 @@ contract IncredibleSquaringBlueprint is BlueprintServiceManager { * @param _inputs Inputs used for the job execution. * @param _outputs Outputs resulting from the job execution. */ - function onJobCallResult( + function onJobResult( uint64 serviceId, uint8 job, uint64 _jobCallId, bytes calldata participant, bytes calldata _inputs, bytes calldata _outputs - ) public virtual override onlyFromRootChain { + ) public virtual payable override onlyFromRootChain { /* // check that we have this service instance require( serviceInstances[serviceId].length > 0, @@ -80,7 +80,7 @@ contract IncredibleSquaringBlueprint is BlueprintServiceManager { bytes calldata participant, bytes calldata inputs, bytes calldata outputs - ) public view virtual override onlyFromRootChain returns (bool) { + ) public pure returns (bool) { // Someone requested to verify the result of a job call. // We need to check if the output is the square of the input. diff --git a/flake.lock b/flake.lock index 7ded4833..01d277c4 100644 --- a/flake.lock +++ b/flake.lock @@ -28,11 +28,11 @@ ] }, "locked": { - "lastModified": 1725354688, - "narHash": "sha256-KHHFemVt6C/hbGoMzIq7cpxmjdp+KZVZaqbvx02aliY=", + "lastModified": 1728119511, + "narHash": "sha256-kJHt+BoDTc9aYXnmy7X+kQto9cT77lDKHAYp5FyY4OY=", "owner": "shazow", "repo": "foundry.nix", - "rev": "671672bd60a0d2e5f6757638fdf27e806df755a4", + "rev": "c45f6bc1f2110b1d209e116be203648a06a02f80", "type": "github" }, "original": { @@ -44,11 +44,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1726583932, - "narHash": "sha256-zACxiQx8knB3F8+Ze+1BpiYrI+CbhxyWpcSID9kVhkQ=", + "lastModified": 1729265718, + "narHash": "sha256-4HQI+6LsO3kpWTYuVGIzhJs1cetFcwT7quWCk/6rqeo=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "658e7223191d2598641d50ee4e898126768fe847", + "rev": "ccc0c2126893dd20963580b6478d1a10a4512185", "type": "github" }, "original": { @@ -73,11 +73,11 @@ ] }, "locked": { - "lastModified": 1726626348, - "narHash": "sha256-sYV7e1B1yLcxo8/h+/hTwzZYmaju2oObNiy5iRI0C30=", + "lastModified": 1729477859, + "narHash": "sha256-r0VyeJxy4O4CgTB/PNtfQft9fPfN1VuGvnZiCxDArvg=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "6fd52ad8bd88f39efb2c999cc971921c2fb9f3a2", + "rev": "ada8266712449c4c0e6ee6fcbc442b3c217c79e1", "type": "github" }, "original": { diff --git a/sdk/src/clients/tangle/services.rs b/sdk/src/clients/tangle/services.rs index f676934c..0252a126 100644 --- a/sdk/src/clients/tangle/services.rs +++ b/sdk/src/clients/tangle/services.rs @@ -28,7 +28,7 @@ impl ServicesClient { } /// A list of services provided by an operator, along with their blueprint -pub type RpcServicesWithBlueprint = services::RpcServicesWithBlueprint; +pub type RpcServicesWithBlueprint = services::RpcServicesWithBlueprint; impl ServicesClient where diff --git a/sdk/src/job_runner.rs b/sdk/src/job_runner.rs index 5fbb57a1..4f15738f 100644 --- a/sdk/src/job_runner.rs +++ b/sdk/src/job_runner.rs @@ -6,7 +6,6 @@ use sp_core::Pair; use std::future::Future; use std::pin::Pin; use tangle_subxt::tangle_testnet_runtime::api; -use tangle_subxt::tangle_testnet_runtime::api::runtime_types::sp_core::ecdsa; use tangle_subxt::tangle_testnet_runtime::api::runtime_types::tangle_primitives::services; use tangle_subxt::tangle_testnet_runtime::api::runtime_types::tangle_primitives::services::PriceTargets; @@ -207,8 +206,7 @@ async fn tangle_registration( let xt = api::tx().services().register( this.blueprint_id, services::OperatorPreferences { - key: ecdsa::Public(ecdsa_pair.signer().public().0), - approval: services::ApprovalPrefrence::None, + key: ecdsa_pair.signer().public().0, price_targets, }, Default::default(), From 5fb8d6c534588cafe467cb9d692920e9ab01430e Mon Sep 17 00:00:00 2001 From: Shady Khalifa Date: Mon, 21 Oct 2024 21:24:30 +0300 Subject: [PATCH 2/5] refactor: remove old code and start use blueprint manager --- Cargo.lock | 1 + blueprint-metadata/Cargo.toml | 1 + blueprint-metadata/src/lib.rs | 103 +++++++----------- blueprints/incredible-squaring/Cargo.toml | 3 + blueprints/incredible-squaring/src/lib.rs | 1 - cli/src/deploy.rs | 67 +++--------- macros/blueprint-proc-macro-core/src/lib.rs | 43 ++------ .../Cargo.toml | 3 + .../src/lib.rs | 6 +- macros/blueprint-proc-macro/src/hooks.rs | 60 +--------- macros/blueprint-proc-macro/src/job.rs | 41 +------ macros/blueprint-proc-macro/src/lib.rs | 14 +-- 12 files changed, 87 insertions(+), 256 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 67dd3568..a1554833 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1769,6 +1769,7 @@ dependencies = [ "fs2", "gadget-blueprint-proc-macro-core", "rustdoc-types", + "serde", "serde_json", "typed-builder", ] diff --git a/blueprint-metadata/Cargo.toml b/blueprint-metadata/Cargo.toml index df976909..007c2e99 100644 --- a/blueprint-metadata/Cargo.toml +++ b/blueprint-metadata/Cargo.toml @@ -11,6 +11,7 @@ repository.workspace = true [dependencies] typed-builder = { workspace = true } gadget-blueprint-proc-macro-core = { workspace = true } +serde = { workspace = true } serde_json = { workspace = true } rustdoc-types = { workspace = true } cargo_metadata = { workspace = true } diff --git a/blueprint-metadata/src/lib.rs b/blueprint-metadata/src/lib.rs index 78dd7795..7e177459 100644 --- a/blueprint-metadata/src/lib.rs +++ b/blueprint-metadata/src/lib.rs @@ -5,10 +5,10 @@ use std::{ process::{Command, Stdio}, }; +use cargo_metadata::{Metadata, Package}; use gadget_blueprint_proc_macro_core::{ - FieldType, Gadget, GadgetSource, GadgetSourceFetcher, JobDefinition, JobResultVerifier, - NativeGadget, ServiceBlueprint, ServiceMetadata, ServiceRegistrationHook, ServiceRequestHook, - TestFetcher, + BlueprintManager, FieldType, Gadget, GadgetSource, GadgetSourceFetcher, JobDefinition, + NativeGadget, ServiceBlueprint, ServiceMetadata, TestFetcher, }; use rustdoc_types::{Crate, Id, Item, ItemEnum, Module}; @@ -37,7 +37,11 @@ impl Config { let jobs = extract_jobs(&krate); eprintln!("Extracted {} job definitions", jobs.len()); let hooks = extract_hooks(&krate); - let gadget = generate_gadget(); + let metadata = extract_metadata(); + let crate_name = std::env::var("CARGO_PKG_NAME").expect("Failed to get package name"); + let package = find_package(&metadata, &crate_name); + let gadget = generate_gadget(package); + let manager = extract_blueprint_manager(package); eprintln!("Generating blueprint.json to {:?}", output_file); let blueprint = ServiceBlueprint { metadata: ServiceMetadata { @@ -53,13 +57,7 @@ impl Config { license: std::env::var("CARGO_PKG_LICENSE").map(Into::into).ok(), }, jobs, - registration_hook: hooks - .iter() - .find_map(|hook| match hook { - Hook::Registration(hook) => Some(hook.clone()), - _ => None, - }) - .unwrap_or_default(), + manager, registration_params: hooks .iter() .find_map(|hook| match hook { @@ -67,13 +65,6 @@ impl Config { _ => None, }) .unwrap_or_default(), - request_hook: hooks - .iter() - .find_map(|hook| match hook { - Hook::Request(hook) => Some(hook.clone()), - _ => None, - }) - .unwrap_or_default(), request_params: hooks .iter() .find_map(|hook| match hook { @@ -90,9 +81,7 @@ impl Config { } enum Hook { - Registration(ServiceRegistrationHook), RegistrationParams(Vec), - Request(ServiceRequestHook), RequestParams(Vec), } @@ -156,9 +145,6 @@ fn extract_jobs_from_module<'a>( serde_json::from_str(&unescape_json_string(&c.expr)) .expect("Failed to deserialize job definition"); job_def.metadata.description = linked_function.docs.as_ref().map(Into::into); - if let JobResultVerifier::Evm(c) = &mut job_def.verifier { - *c = resolve_evm_contract_path_by_name(c).display().to_string(); - } jobs.push(job_def); } _ => continue, @@ -171,8 +157,6 @@ fn extract_jobs_from_module<'a>( fn extract_hooks_from_module(_root: &Id, index: &HashMap, module: &Module) -> Vec { let mut hooks = vec![]; let automatically_derived: String = String::from("#[automatically_derived]"); - const REGISTRATION_HOOK: &str = "REGISTRATION_HOOK"; - const REQUEST_HOOK: &str = "REQUEST_HOOK"; const REGISTRATION_HOOK_PARAMS: &str = "REGISTRATION_HOOK_PARAMS"; const REQUEST_HOOK_PARAMS: &str = "REQUEST_HOOK_PARAMS"; @@ -182,38 +166,6 @@ fn extract_hooks_from_module(_root: &Id, index: &HashMap, module: &Mod ItemEnum::Module(m) => { hooks.extend(extract_hooks_from_module(_root, index, m)); } - ItemEnum::Constant { const_: c, .. } - if item.attrs.contains(&automatically_derived) - && item - .name - .as_ref() - .map(|v| v.eq(REGISTRATION_HOOK)) - .unwrap_or(false) => - { - let mut value = serde_json::from_str(&unescape_json_string(&c.expr)) - .expect("Failed to deserialize hook"); - if let ServiceRegistrationHook::Evm(c) = &mut value { - *c = resolve_evm_contract_path_by_name(c).display().to_string(); - } - hooks.push(Hook::Registration(value)); - } - - ItemEnum::Constant { const_: c, .. } - if item.attrs.contains(&automatically_derived) - && item - .name - .as_ref() - .map(|v| v.eq(REQUEST_HOOK)) - .unwrap_or(false) => - { - let mut value = serde_json::from_str(&unescape_json_string(&c.expr)) - .expect("Failed to deserialize hook"); - if let ServiceRequestHook::Evm(c) = &mut value { - *c = resolve_evm_contract_path_by_name(c).display().to_string(); - } - hooks.push(Hook::Request(value)); - } - ItemEnum::Constant { const_: c, .. } if item.attrs.contains(&automatically_derived) && item @@ -304,10 +256,8 @@ impl Drop for LockFile { } } -/// Generates the metadata for the gadget. -fn generate_gadget() -> Gadget<'static> { +fn extract_metadata() -> Metadata { let root = std::env::var("CARGO_MANIFEST_DIR").expect("Failed to get manifest directory"); - let crate_name = std::env::var("CARGO_PKG_NAME").expect("Failed to get package name"); let root = Path::new(&root) .canonicalize() .expect("Failed to canonicalize root dir"); @@ -324,8 +274,39 @@ fn generate_gadget() -> Gadget<'static> { .no_deps() .exec() .expect("Failed to get metadata"); + metadata +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +struct BlueprintMetadata { + manager: BlueprintManager, +} + +fn extract_blueprint_manager(package: &Package) -> BlueprintManager { + let Some(blueprint) = package.metadata.get("blueprint") else { + eprintln!("No blueprint metadata found in the Cargo.toml."); + eprintln!("For more information, see:"); + eprintln!(""); + // For now, we just return an empty gadget + return BlueprintManager::Evm(Default::default()); + }; + let metadata: BlueprintMetadata = + serde_json::from_value(blueprint.clone()).expect("Failed to deserialize gadget."); + match metadata.manager { + BlueprintManager::Evm(manager) => { + let path = resolve_evm_contract_path_by_name(&manager); + BlueprintManager::Evm(path.display().to_string()) + } + _ => unreachable!("Unsupported blueprint manager"), + } +} - let package = find_package(&metadata, &crate_name); +/// Generates the metadata for the gadget. +fn generate_gadget(package: &Package) -> Gadget<'static> { + let root = std::env::var("CARGO_MANIFEST_DIR").expect("Failed to get manifest directory"); + let root = Path::new(&root) + .canonicalize() + .expect("Failed to canonicalize root dir"); let Some(gadget) = package.metadata.get("gadget") else { eprintln!("No gadget metadata found in the Cargo.toml."); eprintln!("For more information, see:"); diff --git a/blueprints/incredible-squaring/Cargo.toml b/blueprints/incredible-squaring/Cargo.toml index 56e2a573..17b0a4a2 100644 --- a/blueprints/incredible-squaring/Cargo.toml +++ b/blueprints/incredible-squaring/Cargo.toml @@ -51,3 +51,6 @@ blueprint-metadata = { workspace = true } [features] default = ["std"] std = [] + +[package.metadata.blueprint] +manager = { evm = "IncredibleSquaringBlueprint" } diff --git a/blueprints/incredible-squaring/src/lib.rs b/blueprints/incredible-squaring/src/lib.rs index b3e1fd7e..720c5981 100644 --- a/blueprints/incredible-squaring/src/lib.rs +++ b/blueprints/incredible-squaring/src/lib.rs @@ -10,7 +10,6 @@ use std::convert::Infallible; listener = TangleEventListener, event = JobCalled, ), - verifier(evm = "IncredibleSquaringBlueprint") )] pub fn xsquare(x: u64) -> Result { Ok(x.saturating_pow(2u32)) diff --git a/cli/src/deploy.rs b/cli/src/deploy.rs index 910b13dd..08445303 100644 --- a/cli/src/deploy.rs +++ b/cli/src/deploy.rs @@ -2,9 +2,7 @@ use alloy_provider::network::TransactionBuilder; use alloy_provider::Provider; pub use alloy_signer_local::PrivateKeySigner; use color_eyre::eyre::{self, Context, ContextCompat, OptionExt, Result}; -use gadget_blueprint_proc_macro_core::{ - JobResultVerifier, ServiceBlueprint, ServiceRegistrationHook, ServiceRequestHook, -}; +use gadget_blueprint_proc_macro_core::{BlueprintManager, ServiceBlueprint}; use gadget_sdk::clients::tangle::runtime::TangleConfig; pub use k256; use std::fmt::Debug; @@ -142,33 +140,17 @@ async fn deploy_contracts_to_tangle( signer_evm: Option, ) -> Result<()> { enum ContractKind { - RegistrationHook, - RequestHook, - JobVerifier(usize), + Manager, } let rpc_url = rpc_url.replace("ws", "http").replace("wss", "https"); - let mut contract_paths = Vec::new(); - match blueprint.registration_hook { - ServiceRegistrationHook::None => {} - ServiceRegistrationHook::Evm(ref path) => { - contract_paths.push((ContractKind::RegistrationHook, path)) + let contract_paths = match blueprint.manager { + BlueprintManager::Evm(ref path) => vec![(ContractKind::Manager, path)], + _ => { + eprintln!("Unsupported blueprint manager kind"); + vec![] } }; - match blueprint.request_hook { - ServiceRequestHook::None => {} - ServiceRequestHook::Evm(ref path) => contract_paths.push((ContractKind::RequestHook, path)), - }; - - for (id, job) in blueprint.jobs.iter().enumerate() { - match job.verifier { - JobResultVerifier::None => {} - JobResultVerifier::Evm(ref path) => { - contract_paths.push((ContractKind::JobVerifier(id), path)) - } - }; - } - let abs_contract_paths: Vec<_> = contract_paths .into_iter() .map(|(kind, path)| (kind, resolve_path_relative_to_package(package, path))) @@ -225,16 +207,8 @@ async fn deploy_contracts_to_tangle( alloy_network::ReceiptResponse::contract_address(&receipt).unwrap(); eprintln!("Contract {name} deployed at: {contract_address}"); match kind { - ContractKind::RegistrationHook => { - blueprint.registration_hook = - ServiceRegistrationHook::Evm(contract_address.to_string()); - } - ContractKind::RequestHook => { - blueprint.request_hook = ServiceRequestHook::Evm(contract_address.to_string()); - } - ContractKind::JobVerifier(id) => { - blueprint.jobs[*id].verifier = - JobResultVerifier::Evm(contract_address.to_string()); + ContractKind::Manager => { + blueprint.manager = BlueprintManager::Evm(contract_address.to_string()); } } } else { @@ -250,25 +224,14 @@ fn build_contracts_if_needed( package: &cargo_metadata::Package, blueprint: &ServiceBlueprint, ) -> Result<()> { - let mut pathes_to_check = Vec::new(); - - match blueprint.registration_hook { - ServiceRegistrationHook::None => {} - ServiceRegistrationHook::Evm(ref path) => pathes_to_check.push(path), - }; - - match blueprint.request_hook { - ServiceRequestHook::None => {} - ServiceRequestHook::Evm(ref path) => pathes_to_check.push(path), + let pathes_to_check = match blueprint.manager { + BlueprintManager::Evm(ref path) => vec![path], + _ => { + eprintln!("Unsupported blueprint manager kind"); + vec![] + } }; - for job in blueprint.jobs.iter() { - match job.verifier { - JobResultVerifier::None => {} - JobResultVerifier::Evm(ref path) => pathes_to_check.push(path), - }; - } - let abs_pathes_to_check: Vec<_> = pathes_to_check .into_iter() .map(|path| resolve_path_relative_to_package(package, path)) diff --git a/macros/blueprint-proc-macro-core/src/lib.rs b/macros/blueprint-proc-macro-core/src/lib.rs index 2e8ba907..214ae530 100644 --- a/macros/blueprint-proc-macro-core/src/lib.rs +++ b/macros/blueprint-proc-macro-core/src/lib.rs @@ -58,14 +58,12 @@ pub enum FieldType { pub struct ServiceBlueprint<'a> { /// The metadata of the service. pub metadata: ServiceMetadata<'a>, + /// The blueprint manager that will be used to manage the blueprints lifecycle. + pub manager: BlueprintManager, /// The job definitions that are available in this service. pub jobs: Vec>, - /// The registration hook that will be called before restaker registration. - pub registration_hook: ServiceRegistrationHook, /// The parameters that are required for the service registration. pub registration_params: Vec, - /// The request hook that will be called before creating a service from the service blueprint. - pub request_hook: ServiceRequestHook, /// The parameters that are required for the service request. pub request_params: Vec, /// The gadget that will be executed for the service. @@ -106,8 +104,6 @@ pub struct JobDefinition<'a> { /// These are the result, the return values of this job. /// i.e. the output. pub result: Vec, - /// The verifier of the job result. - pub verifier: JobResultVerifier, } #[derive(Default, Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -118,17 +114,6 @@ pub struct JobMetadata<'a> { pub description: Option>, } -/// A Job Result verifier is a verifier that will verify the result of a job call -/// using different verification methods. -#[derive(Default, Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub enum JobResultVerifier { - /// No verification is needed. - #[default] - None, - /// An EVM Contract Address or path to the contract ABI that will verify the result. - Evm(String), -} - /// Represents the definition of a report, including its metadata, parameters, and result type. #[derive(Default, Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct ReportDefinition<'a> { @@ -190,24 +175,12 @@ pub struct ReportMetadata<'a> { pub description: Option>, } -/// Service Registration hook is a hook that will be called before registering the restaker as -/// an operator for the service. -#[derive(Default, Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub enum ServiceRegistrationHook { - /// No hook is needed, the restaker will be registered immediately. - #[default] - None, - /// A Smart contract that will be called to determine if the restaker will be registered. - Evm(String), -} - -/// Service Request hook is a hook that will be called before creating a service from the service blueprint. -#[derive(Default, Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub enum ServiceRequestHook { - /// No hook is needed, the caller will get the service created immediately. - #[default] - None, - /// A Smart contract that will be called to determine if the caller meets the requirements to create a service. +/// Service Blueprint Manager is a smart contract that will manage the service lifecycle. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +#[non_exhaustive] +pub enum BlueprintManager { + /// A Smart contract that will manage the service lifecycle. Evm(String), } diff --git a/macros/blueprint-proc-macro-playground/Cargo.toml b/macros/blueprint-proc-macro-playground/Cargo.toml index a14cbfd0..e9e44a66 100644 --- a/macros/blueprint-proc-macro-playground/Cargo.toml +++ b/macros/blueprint-proc-macro-playground/Cargo.toml @@ -8,6 +8,9 @@ homepage.workspace = true repository.workspace = true publish = false +[package.metadata.blueprint] +manager = { evm = "" } + [[package.metadata.gadget.Native.sources]] owner = "tangle-network" repo = "incredible-squaring" diff --git a/macros/blueprint-proc-macro-playground/src/lib.rs b/macros/blueprint-proc-macro-playground/src/lib.rs index 823e2f66..e8133c5f 100644 --- a/macros/blueprint-proc-macro-playground/src/lib.rs +++ b/macros/blueprint-proc-macro-playground/src/lib.rs @@ -70,10 +70,10 @@ pub fn say_hello(who: Option) -> Result { // Hooks // ================== -#[registration_hook(evm = "RegistrationContract")] +#[registration_hook] pub fn on_register(pubkey: Vec); -#[request_hook(evm = "RequestContract")] +#[request_hook] pub fn on_request(nft_id: u64); // ================== @@ -134,7 +134,7 @@ mod tests { fn generated_blueprint() { eprintln!("{}", super::KEYGEN_JOB_DEF); assert_eq!(super::KEYGEN_JOB_ID, 0); - eprintln!("{}", super::REGISTRATION_HOOK); + eprintln!("{}", super::REGISTRATION_HOOK_PARAMS); } #[test] diff --git a/macros/blueprint-proc-macro/src/hooks.rs b/macros/blueprint-proc-macro/src/hooks.rs index 7934c155..a4b81299 100644 --- a/macros/blueprint-proc-macro/src/hooks.rs +++ b/macros/blueprint-proc-macro/src/hooks.rs @@ -1,18 +1,10 @@ use std::collections::BTreeMap; -use gadget_blueprint_proc_macro_core::{ServiceRegistrationHook, ServiceRequestHook}; use proc_macro::TokenStream; use quote::quote; -use syn::{parse::Parse, ForeignItemFn, Token}; +use syn::ForeignItemFn; -mod kw { - syn::custom_keyword!(evm); -} - -pub(crate) fn registration_hook_impl( - args: &HookArgs, - input: &ForeignItemFn, -) -> syn::Result { +pub(crate) fn registration_hook_impl(input: &ForeignItemFn) -> syn::Result { let syn::ReturnType::Default = &input.sig.output else { return Err(syn::Error::new_spanned( &input.sig.output, @@ -42,22 +34,11 @@ pub(crate) fn registration_hook_impl( .map(crate::shared::type_to_field_type) .collect::>>()?; - let hook = match args { - HookArgs::Evm(c) => ServiceRegistrationHook::Evm(c.value()), - }; - - let hook_json = serde_json::to_string(&hook).map_err(|err| { - syn::Error::new_spanned(input, format!("failed to serialize hook: {err}")) - })?; let hook_params = serde_json::to_string(¶ms).map_err(|err| { syn::Error::new_spanned(input, format!("failed to serialize hook: {err}")) })?; let gen = quote! { - #[doc(hidden)] - #[doc = "The registration hook for the service"] - #[automatically_derived] - pub const REGISTRATION_HOOK: &str = #hook_json; #[doc(hidden)] #[doc = "The registration hook parameters for the service"] #[automatically_derived] @@ -67,10 +48,7 @@ pub(crate) fn registration_hook_impl( Ok(gen.into()) } -pub(crate) fn request_hook_impl( - args: &HookArgs, - input: &ForeignItemFn, -) -> syn::Result { +pub(crate) fn request_hook_impl(input: &ForeignItemFn) -> syn::Result { let syn::ReturnType::Default = &input.sig.output else { return Err(syn::Error::new_spanned( &input.sig.output, @@ -100,22 +78,11 @@ pub(crate) fn request_hook_impl( .map(crate::shared::type_to_field_type) .collect::>>()?; - let hook = match args { - HookArgs::Evm(c) => ServiceRequestHook::Evm(c.value()), - }; - - let hook_json = serde_json::to_string(&hook).map_err(|err| { - syn::Error::new_spanned(input, format!("failed to serialize hook: {err}")) - })?; let hook_params = serde_json::to_string(¶ms).map_err(|err| { syn::Error::new_spanned(input, format!("failed to serialize hook: {err}")) })?; let gen = quote! { - #[doc(hidden)] - #[doc = "The request hook for the service"] - #[automatically_derived] - pub const REQUEST_HOOK: &str = #hook_json; #[doc(hidden)] #[doc = "The request hook parameters for the service"] #[automatically_derived] @@ -124,24 +91,3 @@ pub(crate) fn request_hook_impl( Ok(gen.into()) } - -pub(crate) enum HookArgs { - Evm(syn::LitStr), -} - -impl Parse for HookArgs { - fn parse(input: syn::parse::ParseStream) -> syn::Result { - let lookahead = input.lookahead1(); - if lookahead.peek(kw::evm) { - let _ = input.parse::()?; - let _ = input.parse::()?; - let evm = input.parse::()?; - return Ok(HookArgs::Evm(evm)); - } - - Err(syn::Error::new( - input.span(), - "expected `evm = \"\"`", - )) - } -} diff --git a/macros/blueprint-proc-macro/src/job.rs b/macros/blueprint-proc-macro/src/job.rs index 2605a659..7605ad57 100644 --- a/macros/blueprint-proc-macro/src/job.rs +++ b/macros/blueprint-proc-macro/src/job.rs @@ -1,21 +1,20 @@ use crate::event_listener::evm::{generate_evm_event_handler, get_evm_instance_data}; use crate::event_listener::tangle::generate_tangle_event_handler; use crate::shared::{pascal_case, type_to_field_type}; -use gadget_blueprint_proc_macro_core::{FieldType, JobDefinition, JobMetadata, JobResultVerifier}; +use gadget_blueprint_proc_macro_core::{FieldType, JobDefinition, JobMetadata}; use indexmap::{IndexMap, IndexSet}; use proc_macro::TokenStream; use quote::{format_ident, quote, ToTokens}; use std::collections::HashSet; use syn::ext::IdentExt; use syn::parse::{Parse, ParseBuffer, ParseStream}; -use syn::{Ident, Index, ItemFn, LitInt, LitStr, Token, Type}; +use syn::{Ident, Index, ItemFn, LitInt, Token, Type}; /// Defines custom keywords for defining Job arguments mod kw { syn::custom_keyword!(id); syn::custom_keyword!(params); syn::custom_keyword!(result); - syn::custom_keyword!(verifier); syn::custom_keyword!(evm); syn::custom_keyword!(event_listener); syn::custom_keyword!(listener); @@ -115,10 +114,6 @@ pub(crate) fn job_impl(args: &JobArgs, input: &ItemFn) -> syn::Result JobResultVerifier::Evm(contract.clone()), - Verifier::None => JobResultVerifier::None, - }, }; // Serialize Job Definition to JSON string @@ -602,9 +597,6 @@ pub(crate) struct JobArgs { /// `#[job(result(u32, u64))]` /// `#[job(result(_))]` result: ResultsKind, - /// Optional: Verifier for the job result, currently only supports EVM verifier. - /// `#[job(verifier(evm = "MyVerifierContract"))]` - verifier: Verifier, /// Optional: Event listener type for the job /// `#[job(event_listener(MyCustomListener))]` event_listener: EventListenerArgs, @@ -620,7 +612,6 @@ impl Parse for JobArgs { let mut params = Vec::new(); let mut result = None; let mut id = None; - let mut verifier = Verifier::None; let mut skip_codegen = false; let mut event_listener = EventListenerArgs { listeners: vec![] }; @@ -636,8 +627,6 @@ impl Parse for JobArgs { } else if lookahead.peek(kw::result) { let Results(r) = input.parse()?; result = Some(r); - } else if lookahead.peek(kw::verifier) { - verifier = input.parse()?; } else if lookahead.peek(kw::skip_codegen) { let _ = input.parse::()?; skip_codegen = true; @@ -668,7 +657,6 @@ impl Parse for JobArgs { id, params, result, - verifier, skip_codegen, event_listener, }) @@ -775,13 +763,6 @@ impl Parse for Results { } } -#[derive(Debug)] -enum Verifier { - None, - /// #[job(verifier(evm = "`MyVerifierContract`"))] - Evm(String), -} - #[derive(Debug)] /// `#[job(event_listener(MyCustomListener, MyCustomListener2)]` /// Accepts an optional argument that specifies the event listener to use that implements EventListener @@ -908,24 +889,6 @@ impl Parse for EventListenerArgs { } } -impl Parse for Verifier { - fn parse(input: ParseStream<'_>) -> syn::Result { - let _ = input.parse::()?; - let content; - let _ = syn::parenthesized!(content in input); - let lookahead = content.lookahead1(); - // parse `(evm = "MyVerifierContract")` - if lookahead.peek(kw::evm) { - let _ = content.parse::()?; - let _ = content.parse::()?; - let contract = content.parse::()?; - Ok(Verifier::Evm(contract.value())) - } else { - Ok(Verifier::None) - } - } -} - #[derive(Debug)] pub(crate) struct EvmArgs { instance: Option, diff --git a/macros/blueprint-proc-macro/src/lib.rs b/macros/blueprint-proc-macro/src/lib.rs index c6dcf932..5f969194 100644 --- a/macros/blueprint-proc-macro/src/lib.rs +++ b/macros/blueprint-proc-macro/src/lib.rs @@ -155,14 +155,13 @@ pub fn report(args: TokenStream, input: TokenStream) -> TokenStream { /// # Example /// ```rust,no_run /// # use gadget_blueprint_proc_macro::registration_hook; -/// #[registration_hook(evm = "MyRegistrationHook")] +/// #[registration_hook] /// pub fn my_registration_hook(); /// ``` #[proc_macro_attribute] -pub fn registration_hook(args: TokenStream, input: TokenStream) -> TokenStream { +pub fn registration_hook(_args: TokenStream, input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as syn::ForeignItemFn); - let args = parse_macro_input!(args as hooks::HookArgs); - match hooks::registration_hook_impl(&args, &input) { + match hooks::registration_hook_impl(&input) { Ok(tokens) => tokens, Err(err) => err.to_compile_error().into(), } @@ -173,14 +172,13 @@ pub fn registration_hook(args: TokenStream, input: TokenStream) -> TokenStream { /// # Example /// ```rust,no_run /// # use gadget_blueprint_proc_macro::request_hook; -/// #[request_hook(evm = "MyRequestHook")] +/// #[request_hook] /// pub fn my_request_hook(); /// ``` #[proc_macro_attribute] -pub fn request_hook(args: TokenStream, input: TokenStream) -> TokenStream { +pub fn request_hook(_args: TokenStream, input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as syn::ForeignItemFn); - let args = parse_macro_input!(args as hooks::HookArgs); - match hooks::request_hook_impl(&args, &input) { + match hooks::request_hook_impl(&input) { Ok(tokens) => tokens, Err(err) => err.to_compile_error().into(), } From 6b95e9c4a8ec163300908218457ba87efdec377b Mon Sep 17 00:00:00 2001 From: Shady Khalifa Date: Tue, 22 Oct 2024 15:48:21 +0300 Subject: [PATCH 3/5] fix: context-derive tests --- macros/context-derive/src/services.rs | 10 +++++++++- sdk/src/ctx.rs | 8 +++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/macros/context-derive/src/services.rs b/macros/context-derive/src/services.rs index 0deb7d45..8f1119c2 100644 --- a/macros/context-derive/src/services.rs +++ b/macros/context-derive/src/services.rs @@ -76,7 +76,15 @@ pub fn generate_context_impl( fn current_service_operators( &self, client: &gadget_sdk::ext::subxt::OnlineClient, - ) -> impl core::future::Future, gadget_sdk::ext::subxt::Error>> { + ) -> impl core::future::Future< + Output = Result< + Vec<( + gadget_sdk::ext::subxt::utils::AccountId32, + gadget_sdk::ext::tangle_subxt::tangle_testnet_runtime::api::runtime_types::sp_arithmetic::per_things::Percent, + )>, + gadget_sdk::ext::subxt::Error + > + > { use gadget_sdk::ext::tangle_subxt::tangle_testnet_runtime::api; use gadget_sdk::ext::subxt; diff --git a/sdk/src/ctx.rs b/sdk/src/ctx.rs index 1eb0c06b..0904acdb 100644 --- a/sdk/src/ctx.rs +++ b/sdk/src/ctx.rs @@ -37,7 +37,9 @@ use core::future::Future; use crate::keystore::backend::GenericKeyStore; // derives pub use gadget_context_derive::*; -use tangle_subxt::tangle_testnet_runtime::api::runtime_types::tangle_primitives::services::ServiceBlueprint; +use tangle_subxt::tangle_testnet_runtime::api::runtime_types::{ + sp_arithmetic::per_things::Percent, tangle_primitives::services::ServiceBlueprint, +}; /// `KeystoreContext` trait provides access to the generic keystore from the context. pub trait KeystoreContext { @@ -86,11 +88,11 @@ pub trait ServicesContext { client: &subxt::OnlineClient, ) -> impl Future>; - /// Get the current service operators from the context. + /// Get the current service operators with their restake exposure from the context. /// This function will return a list of service operators that are selected to run this service /// instance. fn current_service_operators( &self, client: &subxt::OnlineClient, - ) -> impl Future, subxt::Error>>; + ) -> impl Future, subxt::Error>>; } From 6ca7a43f870599e14d56b37c87acca8d1affef43 Mon Sep 17 00:00:00 2001 From: shekohex Date: Tue, 22 Oct 2024 16:11:35 +0300 Subject: [PATCH 4/5] chore: comments --- blueprint-metadata/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/blueprint-metadata/src/lib.rs b/blueprint-metadata/src/lib.rs index 7e177459..528cc591 100644 --- a/blueprint-metadata/src/lib.rs +++ b/blueprint-metadata/src/lib.rs @@ -287,7 +287,8 @@ fn extract_blueprint_manager(package: &Package) -> BlueprintManager { eprintln!("No blueprint metadata found in the Cargo.toml."); eprintln!("For more information, see:"); eprintln!(""); - // For now, we just return an empty gadget + // For now, we just return an empty blueprint manager, this + // will be a hard error in the future. return BlueprintManager::Evm(Default::default()); }; let metadata: BlueprintMetadata = From 970ed55cf3402ae972d1a56227be716b67c766d0 Mon Sep 17 00:00:00 2001 From: shekohex Date: Tue, 22 Oct 2024 18:33:55 +0300 Subject: [PATCH 5/5] chore: Update comments --- blueprint-metadata/src/lib.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/blueprint-metadata/src/lib.rs b/blueprint-metadata/src/lib.rs index 528cc591..5fff780c 100644 --- a/blueprint-metadata/src/lib.rs +++ b/blueprint-metadata/src/lib.rs @@ -287,8 +287,7 @@ fn extract_blueprint_manager(package: &Package) -> BlueprintManager { eprintln!("No blueprint metadata found in the Cargo.toml."); eprintln!("For more information, see:"); eprintln!(""); - // For now, we just return an empty blueprint manager, this - // will be a hard error in the future. + // TODO(@shekohex): make this hard error return BlueprintManager::Evm(Default::default()); }; let metadata: BlueprintMetadata =