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

feat(pop-api): errors #17

Merged
merged 20 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion Cargo.lock

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

10 changes: 5 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ repository = "https://github.com/r0gue-io/pop-node/"

[workspace]
members = [
"node",
"runtime",
"pop-api",
"node",
"runtime",
"pop-api",
]
exclude = [
"contracts"
"contracts"
]

resolver = "2"
Expand All @@ -39,7 +39,7 @@ substrate-build-script-utils = { git = "https://github.com/paritytech/polkadot-s
# Local

pop-runtime = { path = "./runtime" }
pop-api-primitives = { path = "./pop-api/primitives"}
pop-api-primitives = { path = "./pop-api/primitives", default-features = false }

# Substrate
sc-basic-authorship = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.1" }
Expand Down
7 changes: 2 additions & 5 deletions contracts/pop-api-examples/balance-transfer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@ edition = "2021"

[dependencies]
ink = { version = "4.3.0", default-features = false }
pop-api = { path = "../../../pop-api", default-features = false }
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 = "23.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] }
sp-runtime = { version = "24.0.0", default-features = false }

[dev-dependencies]
ink_e2e = "4.3.0"

Expand All @@ -22,10 +20,9 @@ path = "lib.rs"
default = ["std"]
std = [
"ink/std",
"pop-api/std",
"scale/std",
"scale-info/std",
"sp-runtime/std",
"sp-io/std",
]
ink-as-dependency = []
e2e-tests = []
246 changes: 124 additions & 122 deletions contracts/pop-api-examples/balance-transfer/lib.rs
Original file line number Diff line number Diff line change
@@ -1,132 +1,134 @@
#![cfg_attr(not(feature = "std"), no_std, no_main)]

use ink::{
env::Environment,
prelude::vec::Vec,
};

use ink::primitives::AccountId;
use sp_runtime::MultiAddress;
use scale::{Encode, Decode};

#[derive(Encode)]
enum RuntimeCall {
Balances(BalancesCall),
}

#[derive(scale::Encode)]
enum BalancesCall {
#[codec(index = 3)]
TransferKeepAlive {
dest: MultiAddress<AccountId, ()>,
#[codec(compact)]
value: u128,
},
#[codec(index = 8)]
ForceSetBalance {
who: MultiAddress<AccountId, ()>,
#[codec(compact)]
new_free: u128,
},
}
use pop_api::balances;

#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum PopApiError {
TotalSupplyFailed,
}

pub type Result<T> = core::result::Result<T, PopApiError>;

use scale;
impl From<scale::Error> for PopApiError {
fn from(_: scale::Error) -> Self {
panic!("encountered unexpected invalid SCALE encoding")
}
}

#[ink::chain_extension]
pub trait PopApi {
type ErrorCode = PopApiError;

#[ink(extension = 0x0)]
fn dispatch(call: RuntimeCall) -> Result<Vec<u8>>;
}

impl ink::env::chain_extension::FromStatusCode for PopApiError {
fn from_status_code(status_code: u32) -> core::result::Result<(), Self> {
match status_code {
0 => Ok(()),
1 => Err(Self::TotalSupplyFailed),
_ => panic!("encountered unknown status code"),
}
}
pub enum ContractError {
BalancesError(balances::Error),
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum CustomEnvironment {}

impl Environment for CustomEnvironment {
const MAX_EVENT_TOPICS: usize =
<ink::env::DefaultEnvironment as Environment>::MAX_EVENT_TOPICS;

type AccountId = <ink::env::DefaultEnvironment as Environment>::AccountId;
type Balance = <ink::env::DefaultEnvironment as Environment>::Balance;
type Hash = <ink::env::DefaultEnvironment as Environment>::Hash;
type BlockNumber = <ink::env::DefaultEnvironment as Environment>::BlockNumber;
type Timestamp = <ink::env::DefaultEnvironment as Environment>::Timestamp;

type ChainExtension = PopApi;
impl From<balances::Error> for ContractError {
fn from(value: balances::Error) -> Self {
ContractError::BalancesError(value)
}
}

#[ink::contract(env = crate::CustomEnvironment)]
#[ink::contract(env = pop_api::Environment)]
mod pop_api_extension_demo {
use crate::{
BalancesCall,
RuntimeCall,
};

use super::PopApiError;

use ink::env::Error as EnvError;

#[ink(storage)]
#[derive(Default)]
pub struct PopApiExtensionDemo;

impl From<EnvError> for PopApiError {
fn from(e: EnvError) -> Self {
match e {
EnvError::CallRuntimeFailed => PopApiError::TotalSupplyFailed,
_ => panic!("Unexpected error from `pallet-contracts`."),
}
}
}

impl PopApiExtensionDemo {
#[ink(constructor, payable)]
pub fn new() -> Self {
ink::env::debug_println!("PopApiExtensionDemo::new");
Default::default()
}

#[ink(message)]
pub fn transfer_through_runtime(
&mut self,
receiver: AccountId,
value: Balance,
) {
ink::env::debug_println!("PopApiExtensionDemo::transfer_through_runtime: \nreceiver: {:?}, \nvalue: {:?}", receiver, value);

let call = RuntimeCall::Balances(BalancesCall::TransferKeepAlive {
dest: receiver.into(),
value: value,
});
self.env().extension().dispatch(call);

ink::env::debug_println!("PopApiExtensionDemo::transfer_through_runtime end");

}
}
}
use super::ContractError;

#[ink(storage)]
#[derive(Default)]
pub struct PopApiExtensionDemo;

impl PopApiExtensionDemo {
#[ink(constructor, payable)]
pub fn new() -> Self {
ink::env::debug_println!("PopApiExtensionDemo::new");
Default::default()
}

#[ink(message)]
pub fn transfer_through_runtime(
&mut self,
receiver: AccountId,
value: Balance,
) -> Result<(), ContractError> {
ink::env::debug_println!(
"PopApiExtensionDemo::transfer_through_runtime: \nreceiver: {:?}, \nvalue: {:?}",
receiver,
value
);

pop_api::balances::transfer_keep_alive(receiver, value)?;

ink::env::debug_println!("PopApiExtensionDemo::transfer_through_runtime end");
Ok(())
}
}

#[cfg(all(test, feature = "e2e-tests"))]
mod e2e_tests {
use super::*;
use ink_e2e::{ChainBackend, ContractsBackend};

use ink::{
env::{test::default_accounts, DefaultEnvironment},
primitives::AccountId,
};

type E2EResult<T> = Result<T, Box<dyn std::error::Error>>;

/// The base number of indivisible units for balances on the
/// `substrate-contracts-node`.
const UNIT: Balance = 1_000_000_000_000;

/// The contract will be given 1000 tokens during instantiation.
const CONTRACT_BALANCE: Balance = 1_000 * UNIT;

/// The receiver will get enough funds to have the required existential deposit.
///
/// If your chain has this threshold higher, increase the transfer value.
const TRANSFER_VALUE: Balance = 1 / 10 * UNIT;

/// An amount that is below the existential deposit, so that a transfer to an
/// empty account fails.
///
/// Must not be zero, because such an operation would be a successful no-op.
const INSUFFICIENT_TRANSFER_VALUE: Balance = 1;

/// Positive case scenario:
/// - the call is valid
/// - the call execution succeeds
#[ink_e2e::test]
async fn transfer_with_call_runtime_works<Client: E2EBackend>(
mut client: Client,
) -> E2EResult<()> {
// given
let mut constructor = RuntimeCallerRef::new();
let contract = client
.instantiate("call-runtime", &ink_e2e::alice(), &mut constructor)
.value(CONTRACT_BALANCE)
.submit()
.await
.expect("instantiate failed");
let mut call_builder = contract.call_builder::<RuntimeCaller>();

let accounts = default_accounts::<DefaultEnvironment>();

let receiver: AccountId = accounts.bob;

let sender_balance_before = client
.free_balance(accounts.alice)
.await
.expect("Failed to get account balance");
let receiver_balance_before =
client.free_balance(receiver).await.expect("Failed to get account balance");

// when
let transfer_message = call_builder.transfer_through_runtime(receiver, TRANSFER_VALUE);

let call_res = client
.call(&ink_e2e::alice(), &transfer_message)
.submit()
.await
.expect("call failed");

assert!(call_res.return_value().is_ok());

// then
let sender_balance_after = client
.free_balance(accounts.alice)
.await
.expect("Failed to get account balance");
let receiver_balance_after =
client.free_balance(receiver).await.expect("Failed to get account balance");

assert_eq!(contract_balance_before, contract_balance_after + TRANSFER_VALUE);
assert_eq!(receiver_balance_before, receiver_balance_after - TRANSFER_VALUE);

Ok(())
}
}
}
6 changes: 1 addition & 5 deletions contracts/pop-api-examples/nfts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ ink = { version = "4.3.0", default-features = false }
pop-api = { path = "../../../pop-api", default-features = false }
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 = "23.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] }
sp-runtime = { version = "24.0.0", default-features = false }

[dev-dependencies]
ink_e2e = "4.3.0"
Expand All @@ -22,11 +20,9 @@ path = "lib.rs"
default = ["std"]
std = [
"ink/std",
"pop-api/std",
"scale/std",
"scale-info/std",
"sp-io/std",
"sp-runtime/std",
"pop-api/std",
]
ink-as-dependency = []
e2e-tests = []
22 changes: 15 additions & 7 deletions contracts/pop-api-examples/nfts/lib.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
#![cfg_attr(not(feature = "std"), no_std, no_main)]

use pop_api::PopApiError;
use pop_api::nfts;

#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum ContractError {
SomeError,
NftsError(nfts::Error),
}

impl From<PopApiError> for ContractError {
fn from(_value: PopApiError) -> Self {
ContractError::SomeError
impl From<nfts::Error> for ContractError {
fn from(value: nfts::Error) -> Self {
ContractError::NftsError(value)
}
}

#[ink::contract(env = pop_api::PopEnv)]
mod pop_api_extension_demo {
use super::ContractError;

Expand All @@ -39,7 +38,16 @@ mod pop_api_extension_demo {
ink::env::debug_println!("PopApiExtensionDemo::mint_through_runtime: collection_id: {:?} \nitem_id {:?} \nreceiver: {:?}, ", collection_id, item_id, receiver);

// simplified API call
pop_api::nfts::mint(collection_id, item_id, receiver)?;
let result = pop_api::nfts::mint(collection_id, item_id, receiver);
ink::env::debug_println!(
"PopApiExtensionDemo::mint_through_runtime result: {result:?}"
);
if let Err(pop_api::nfts::Error::NoConfig) = result {
ink::env::debug_println!(
"PopApiExtensionDemo::mint_through_runtime expected error received"
);
}
result?;

ink::env::debug_println!("PopApiExtensionDemo::mint_through_runtime end");
Ok(())
Expand Down
Loading
Loading