Skip to content

Commit

Permalink
style: formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
evilrobot-01 committed Mar 6, 2024
1 parent e532a0b commit d4c9e32
Show file tree
Hide file tree
Showing 14 changed files with 870 additions and 1,340 deletions.
248 changes: 119 additions & 129 deletions contracts/pop-api-examples/balance-transfer/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,140 +5,130 @@ use pop_api::balances;
#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum ContractError {
BalancesError(balances::Error),
BalancesError(balances::Error),
}

impl From<balances::Error> for ContractError {
fn from(value: balances::Error) -> Self {
ContractError::BalancesError(value)
}
fn from(value: balances::Error) -> Self {
ContractError::BalancesError(value)
}
}

#[ink::contract(env = pop_api::Environment)]
mod pop_api_extension_demo {
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(())
}
}
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(())
}
}
}
4 changes: 2 additions & 2 deletions pop-api/primitives/src/storage_keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ use scale::{Decode, Encode};

#[derive(Encode, Decode, Debug)]
pub enum RuntimeStateKeys {
ParachainSystem(ParachainSystemKeys),
ParachainSystem(ParachainSystemKeys),
}

#[derive(Encode, Decode, Debug)]
pub enum ParachainSystemKeys {
LastRelayChainBlockNumber,
LastRelayChainBlockNumber,
}
72 changes: 36 additions & 36 deletions pop-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,67 +29,67 @@ pub type Result<T> = core::result::Result<T, PopApiError>;
#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum PopApiError {
UnknownStatusCode(u32),
DecodingFailed,
Balances(balances::Error),
Nfts(nfts::Error),
UnknownStatusCode(u32),
DecodingFailed,
Balances(balances::Error),
Nfts(nfts::Error),
}

impl ink::env::chain_extension::FromStatusCode for PopApiError {
fn from_status_code(status_code: u32) -> core::result::Result<(), Self> {
match status_code {
0 => Ok(()),
10_000..=10_999 => Err(Balances((status_code - 10_000).try_into()?)),
50_000..=50_999 => Err(Nfts((status_code - 50_000).try_into()?)),
_ => Err(UnknownStatusCode(status_code)),
}
}
fn from_status_code(status_code: u32) -> core::result::Result<(), Self> {
match status_code {
0 => Ok(()),
10_000..=10_999 => Err(Balances((status_code - 10_000).try_into()?)),
50_000..=50_999 => Err(Nfts((status_code - 50_000).try_into()?)),
_ => Err(UnknownStatusCode(status_code)),
}
}
}

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

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

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

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

type ChainExtension = PopApi;
type ChainExtension = PopApi;
}

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

#[ink(extension = 0)]
#[allow(private_interfaces)]
fn dispatch(call: RuntimeCall) -> Result<()>;
#[ink(extension = 0)]
#[allow(private_interfaces)]
fn dispatch(call: RuntimeCall) -> Result<()>;

#[ink(extension = 1)]
#[allow(private_interfaces)]
fn read_state(key: RuntimeStateKeys) -> Result<Vec<u8>>;
#[ink(extension = 1)]
#[allow(private_interfaces)]
fn read_state(key: RuntimeStateKeys) -> Result<Vec<u8>>;
}

fn dispatch(call: RuntimeCall) -> Result<()> {
<<Environment as ink::env::Environment>::ChainExtension as ChainExtensionInstance>::instantiate(
)
.dispatch(call)
<<Environment as ink::env::Environment>::ChainExtension as ChainExtensionInstance>::instantiate(
)
.dispatch(call)
}

fn read_state(key: RuntimeStateKeys) -> Result<Vec<u8>> {
<<Environment as ink::env::Environment>::ChainExtension as ChainExtensionInstance>::instantiate(
)
.read_state(key)
<<Environment as ink::env::Environment>::ChainExtension as ChainExtensionInstance>::instantiate(
)
.read_state(key)
}
Loading

0 comments on commit d4c9e32

Please sign in to comment.