Skip to content
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
merged 2 commits into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .gitignore
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
29 changes: 29 additions & 0 deletions Cargo.toml
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 = []

88 changes: 88 additions & 0 deletions README.md
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.

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

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the statement


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.
59 changes: 59 additions & 0 deletions lib.rs
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)
}
}
}