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: spot order contract #40

Closed
wants to merge 3 commits into from
Closed
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
9 changes: 9 additions & 0 deletions pop-api/examples/place-spot-order/.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
28 changes: 28 additions & 0 deletions pop-api/examples/place-spot-order/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
[package]
name = "pop_api_spot_order_example"
version = "0.1.0"
authors = ["[your_name] <[your_email]>"]
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 }

[dev-dependencies]
ink_e2e = "4.3.0"

[lib]
path = "lib.rs"

[features]
default = ["std"]
std = [
"ink/std",
"pop-api/std",
"scale/std",
"scale-info/std",
]
ink-as-dependency = []
e2e-tests = []
67 changes: 67 additions & 0 deletions pop-api/examples/place-spot-order/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#![cfg_attr(not(feature = "std"), no_std, no_main)]

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 {
InvalidCollection,
ItemAlreadyExists,
NftsError(nfts::Error),
NotOwner,
}

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

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

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

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

#[ink(message)]
pub fn place_spot_order(
&mut self,
max_amount: Balance,
para_id: u32,
) -> Result<(), ContractError> {
ink::env::debug_println!(
"Contract::place_spot_order: max_amount {:?} para_id: {:?} ",
max_amount,
para_id,
);

let res = pop_api::cross_chain::coretime::place_spot_order(max_amount, para_id);
ink::env::debug_println!(
"Contract::place_spot_order: res {:?} ",
res,
);

ink::env::debug_println!("Contract::place_spot_order end");
Ok(())
}
}

#[cfg(test)]
mod tests {
use super::*;

#[ink::test]
fn default_works() {
PopApiSpotOrderExample::new();
}
}
}
78 changes: 72 additions & 6 deletions runtime/src/extensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ impl TryFrom<u16> for v0::FuncId {
fn dispatch_call<T, E>(
env: &mut Environment<E, BufInBufOutState>,
call: RuntimeCall,
origin: RuntimeOrigin,
log_prefix: &str,
) -> Result<(), DispatchError>
where
Expand All @@ -118,9 +119,6 @@ where

log::debug!(target:LOG_TARGET, "{} inputted RuntimeCall: {:?}", log_prefix, call);

// contract is the origin by default
let origin: RuntimeOrigin = RawOrigin::Signed(env.ext().address().clone()).into();

match call.dispatch(origin) {
Ok(info) => {
log::debug!(target:LOG_TARGET, "{} success, actual weight: {:?}", log_prefix, info.actual_weight);
Expand Down Expand Up @@ -182,7 +180,10 @@ where
// read the input as RuntimeCall
let call: RuntimeCall = env.read_as_unbounded(len)?;

dispatch_call::<T, E>(&mut env, call, LOG_PREFIX)
// contract is the origin by default
let origin: RuntimeOrigin = RawOrigin::Signed(env.ext().address().clone()).into();

dispatch_call::<T, E>(&mut env, call, origin, LOG_PREFIX)
}

fn read_state<T, E>(env: Environment<E, InitState>) -> Result<(), DispatchError>
Expand Down Expand Up @@ -313,7 +314,7 @@ where
.buy_execution(assets.clone().into(), Unlimited)
.transact(
SovereignAccount,
Weight::from_parts(25_000_000, 10_000),
Weight::from_parts(250_000_000, 10_000),
message.encode().into(),
)
.refund_surplus()
Expand All @@ -323,13 +324,15 @@ where
},
};

let origin: RuntimeOrigin = RawOrigin::Root.into();

// Generate runtime call to dispatch
let call = RuntimeCall::PolkadotXcm(pallet_xcm::Call::send {
dest: Box::new(dest),
message: Box::new(VersionedXcm::V4(message)),
});

dispatch_call::<T, E>(&mut env, call, LOG_PREFIX)
dispatch_call::<T, E>(&mut env, call, origin, LOG_PREFIX)
}

#[cfg(test)]
Expand Down Expand Up @@ -663,4 +666,67 @@ mod tests {
assert!(!result.result.unwrap().did_revert(), "Contract reverted!");
});
}

#[test]
#[ignore]
fn place_spot_order_from_contract_works() {
new_test_ext().execute_with(|| {
let _ = env_logger::try_init();

let (wasm_binary, _) = load_wasm_module::<Runtime>(
"../pop-api/examples/place-spot-order/target/ink/pop_api_spot_order_example.wasm",
)
.unwrap();

let init_value = 100 * UNIT;

let result = Contracts::bare_instantiate(
ALICE,
init_value,
GAS_LIMIT,
None,
Code::Upload(wasm_binary),
function_selector("new"),
vec![],
DEBUG_OUTPUT,
pallet_contracts::CollectEvents::Skip,
)
.result
.unwrap();

assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result);

let addr = result.account_id;

let function = function_selector("place_spot_order");

let max_amount = 1 * UNIT;
let para_id = 2000;

let params = [function, max_amount.encode(), para_id.encode()].concat();

let result = Contracts::bare_call(
ALICE,
addr.clone(),
0,
Weight::from_parts(100_000_000_000, 3 * 1024 * 1024),
None,
params,
DEBUG_OUTPUT,
pallet_contracts::CollectEvents::Skip,
pallet_contracts::Determinism::Enforced,
);

if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug {
log::debug!(
"Contract debug buffer - {:?}",
String::from_utf8(result.debug_message.clone())
);
log::debug!("result: {:?}", result);
}

// check for revert
assert!(!result.result.unwrap().did_revert(), "Contract reverted!");
});
}
}
Loading