-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement call-runtime example #1
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
# Ignore build artifacts from the local tests sub-crate. | ||
/target/ | ||
|
||
# Ignore backup files creates by cargo fmt. | ||
**/*.rs.bk | ||
|
||
# Remove Cargo.lock when creating an executable, leave it for libraries | ||
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock | ||
Cargo.lock |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
[package] | ||
name = "call_runtime_template" | ||
version = "0.1.0" | ||
authors = ["InkDevHub"] | ||
edition = "2021" | ||
|
||
[dependencies] | ||
ink = { version = "4.2.0", default-features = false, features = ["call-runtime"] } | ||
|
||
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } | ||
scale-info = { version = "2.6", default-features = false, features = ["derive"], optional = true } | ||
|
||
sp-io = { version = "33.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } | ||
sp-runtime = { version = "34.0.0", default-features = false } | ||
|
||
[lib] | ||
path = "lib.rs" | ||
|
||
[features] | ||
default = ["std"] | ||
std = [ | ||
"ink/std", | ||
"scale/std", | ||
"scale-info/std", | ||
"sp-runtime/std", | ||
"sp-io/std", | ||
] | ||
ink-as-dependency = [] | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
# Call-runtime example | ||
|
||
Call-runtime is currently an unstable feature of pallet-contracts and ink!. This documentation serves as an example for educational purposes only. Functionality and implementation details might change before the feature becomes stable. | ||
|
||
Smart contracts, by themselves, are limited to manipulating their own storage and performing internal computations. Call-runtime allows them to interact with other parts of the blockchain system, provided by the runtime. This enables contracts to leverage functionalities like token transfers (using the Balances pallet), setting account balances (using the Balances pallet), or interacting with on-chain oracles (using a custom pallet). | ||
|
||
Unlike chain extensions, you would not need to write any additional code in pallet-contracts API. That makes this method of calling a pallet's dispatchables more secure and easier on the development side. It does not require additional audition and tests as well. | ||
|
||
## Requirements: | ||
|
||
### Node configuration | ||
|
||
Substrate node configured to run contracts with unstable features. For that, adjust pallet contracts configuration in your runtime with: | ||
|
||
```Rust | ||
// In your node's runtime configuration file (runtime.rs) | ||
impl pallet_contracts::Config for Runtime { | ||
… | ||
// `Everything` or anything that will allow for the `Balances::transfer` extrinsic. | ||
type CallFilter = frame_support::traits::Everything; | ||
type UnsafeUnstableInterface = ConstBool<true>; | ||
… | ||
} | ||
``` | ||
|
||
### Cargo.toml | ||
|
||
In your `Cargo.toml` add the `call-runtime` feature and explicitly disable some of `sp-io` features, to avoid conflicts: | ||
``` | ||
sp-io = { version = "18.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } | ||
sp-runtime = { version = "19.0.0", default-features = false } | ||
``` | ||
Also, enable the `"call-runtime"` feature for `ink!` dependancy. | ||
|
||
### Contract's specifics | ||
|
||
#### RuntimeCall | ||
`RuntimeCall` enum is a part of the runtime dispatchables API. `Ink!` doesn't expose the real enum, so we need a partial definition matching our targets. Find the full definition with `construct_runtime!` macro or tools like `frame_support` crate. | ||
|
||
With the `construct_runtime!`, you can count the index of a pallet, it is zero based. So for `Balances` pallet the index is `4`. | ||
```Rust | ||
construct_runtime!( | ||
pub enum Runtime where | ||
Block = Block, | ||
NodeBlock = opaque::Block, | ||
UncheckedExtrinsic = UncheckedExtrinsic | ||
{ | ||
System: frame_system, | ||
Timestamp: pallet_timestamp, | ||
Aura: pallet_aura, | ||
Grandpa: pallet_grandpa, | ||
Balances: pallet_balances, | ||
TransactionPayment: pallet_transaction_payment, | ||
Sudo: pallet_sudo, | ||
// ... | ||
} | ||
); | ||
``` | ||
|
||
With `frame_support` you can call upon the snippet below, which would output the index: | ||
```Rust | ||
use frame_support::traits::PalletInfoAccess; | ||
|
||
let my_pallet_index = MyPallet::index(); | ||
``` | ||
|
||
#### PalletCall | ||
|
||
`PalletCall` enum is a part of a pallet dispatchables API and is named after a palet. For example, `Balances` pallet's enum would be `BalancesCall`. | ||
|
||
The indexes can be found in your pallet code's `#[pallet::call]` section and check `#[pallet::call_index(x)]` attribute of the call. If these attributes are missing, use source-code order (0-based). | ||
|
||
#### Call-runtime | ||
|
||
The example message `transfer_call_runtime` call will fail if: | ||
- It's called outside the blockchain environment (e.g., during development or testing). | ||
- Blockchain itself doesn't allow the "call-runtime" feature (controlled by a setting called `UnsafeUnstableInterface`). | ||
- Chain restricts contracts from calling the `Balances::transfer` function (enforced by a `CallFilter`). | ||
- Recipient account doesn't have enough funds to cover the existential deposit after the transfer. | ||
- Contract itself doesn't have enough balance to complete the transfer. | ||
|
||
## Chain extensions | ||
|
||
Use chain-extensions instead of call-runtime when you need to: | ||
- Return data. | ||
- Provide functionality exclusively to contracts. | ||
- Provide custom weights. | ||
- Avoid the need to keep the Call data structure stable. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
#![cfg_attr(not(feature = "std"), no_std, no_main)] | ||
|
||
use ink::primitives::AccountId; | ||
use sp_runtime::MultiAddress; | ||
|
||
#[derive(scale::Encode)] | ||
enum RuntimeCall { | ||
#[codec(index = 4)] | ||
Balances(BalancesCall), | ||
} | ||
|
||
#[derive(scale::Encode)] | ||
enum BalancesCall { | ||
#[codec(index = 0)] | ||
Transfer { | ||
dest: MultiAddress<AccountId, ()>, | ||
#[codec(compact)] | ||
value: u128, | ||
}, | ||
} | ||
|
||
#[ink::contract] | ||
mod call_runtime_template { | ||
use crate::{BalancesCall, RuntimeCall}; | ||
|
||
#[ink(storage)] | ||
#[derive(Default)] | ||
pub struct CallRuntimeTemplate {} | ||
|
||
#[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)] | ||
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] | ||
pub enum RuntimeError { | ||
CallRuntimeFailed, | ||
} | ||
|
||
impl CallRuntimeTemplate { | ||
#[ink(constructor, payable)] | ||
pub fn new() -> Self { | ||
Default::default() | ||
} | ||
|
||
/// Tries to transfer `value` from the contract's balance to `receiver`. | ||
/// | ||
/// Returns Error CallRuntimeFailed if the call fails. | ||
#[ink(message)] | ||
pub fn transfer_call_runtime( | ||
&mut self, | ||
receiver: AccountId, | ||
value: Balance, | ||
) -> Result<(), RuntimeError> { | ||
self.env() | ||
.call_runtime(&RuntimeCall::Balances(BalancesCall::Transfer { | ||
dest: receiver.into(), | ||
value, | ||
})) | ||
.map_err(|_| RuntimeError::CallRuntimeFailed) | ||
} | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It is now stable in ink! v5: use-ink/ink#1749
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Removed the statement