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

Add test to cover trading via the Escrow canister #4918

Merged
merged 6 commits into from
Dec 4, 2023
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
1 change: 1 addition & 0 deletions Cargo.lock

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

5 changes: 3 additions & 2 deletions backend/canisters/escrow/api/src/updates/cancel_offer.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use candid::CandidType;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
#[derive(CandidType, Serialize, Deserialize, Debug)]
pub struct Args {
pub offer_id: u32,
}

#[derive(Serialize, Deserialize, Debug)]
#[derive(CandidType, Serialize, Deserialize, Debug)]
pub enum Response {
Success,
OfferAlreadyAccepted,
Expand Down
7 changes: 4 additions & 3 deletions backend/canisters/escrow/api/src/updates/create_offer.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use candid::CandidType;
use serde::{Deserialize, Serialize};
use types::{TimestampMillis, TokenInfo};

#[derive(Serialize, Deserialize, Debug)]
#[derive(CandidType, Serialize, Deserialize, Debug)]
pub struct Args {
pub input_token: TokenInfo,
pub input_amount: u128,
Expand All @@ -10,13 +11,13 @@ pub struct Args {
pub expires_at: TimestampMillis,
}

#[derive(Serialize, Deserialize, Debug)]
#[derive(CandidType, Serialize, Deserialize, Debug)]
pub enum Response {
Success(SuccessResult),
InvalidOffer(String),
}

#[derive(Serialize, Deserialize, Debug)]
#[derive(CandidType, Serialize, Deserialize, Debug)]
pub struct SuccessResult {
pub id: u32,
}
7 changes: 4 additions & 3 deletions backend/canisters/escrow/api/src/updates/notify_deposit.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use candid::CandidType;
use serde::{Deserialize, Serialize};
use types::UserId;

#[derive(Serialize, Deserialize, Debug)]
#[derive(CandidType, Serialize, Deserialize, Debug)]
pub struct Args {
pub offer_id: u32,
pub user_id: Option<UserId>,
}

#[derive(Serialize, Deserialize, Debug)]
#[derive(CandidType, Serialize, Deserialize, Debug)]
pub enum Response {
Success,
BalanceTooLow(BalanceTooLowResult),
Expand All @@ -18,7 +19,7 @@ pub enum Response {
InternalError(String),
}

#[derive(Serialize, Deserialize, Debug)]
#[derive(CandidType, Serialize, Deserialize, Debug)]
pub struct BalanceTooLowResult {
pub balance: u128,
pub balance_required: u128,
Expand Down
4 changes: 2 additions & 2 deletions backend/canisters/escrow/impl/src/updates/cancel_offer.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use crate::{mutate_state, RuntimeState};
use canister_api_macros::update_msgpack;
use canister_api_macros::update_candid_and_msgpack;
use canister_tracing_macros::trace;
use escrow_canister::cancel_offer::{Response::*, *};

#[update_msgpack]
#[update_candid_and_msgpack]
#[trace]
fn cancel_offer(args: Args) -> Response {
mutate_state(|state| cancel_offer_impl(args, state))
Expand Down
4 changes: 2 additions & 2 deletions backend/canisters/escrow/impl/src/updates/create_offer.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use crate::{mutate_state, RuntimeState};
use canister_api_macros::update_msgpack;
use canister_api_macros::update_candid_and_msgpack;
use canister_tracing_macros::trace;
use escrow_canister::create_offer::{Response::*, *};
use types::TimestampMillis;

#[update_msgpack]
#[update_candid_and_msgpack]
#[trace]
fn create_offer(args: Args) -> Response {
mutate_state(|state| create_offer_impl(args, state))
Expand Down
4 changes: 2 additions & 2 deletions backend/canisters/escrow/impl/src/updates/notify_deposit.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use crate::model::pending_payments_queue::{PendingPayment, PendingPaymentReason};
use crate::{mutate_state, RuntimeState};
use canister_api_macros::update_msgpack;
use canister_api_macros::update_candid_and_msgpack;
use canister_tracing_macros::trace;
use escrow_canister::deposit_subaccount;
use escrow_canister::notify_deposit::{Response::*, *};
use icrc_ledger_types::icrc1::account::Account;
use types::{CanisterId, UserId};

#[update_msgpack]
#[update_candid_and_msgpack]
#[trace]
async fn notify_deposit(args: Args) -> Response {
let PrepareResult {
Expand Down
1 change: 1 addition & 0 deletions backend/integration_tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ edition = "2021"
candid = { workspace = true }
community_canister = { path = "../canisters/community/api" }
cycles_dispenser_canister = { path = "../canisters/cycles_dispenser/api" }
escrow_canister = { path = "../canisters/escrow/api" }
group_canister = { path = "../canisters/group/api" }
group_index_canister = { path = "../canisters/group_index/api" }
ic-cdk = { workspace = true }
Expand Down
68 changes: 68 additions & 0 deletions backend/integration_tests/src/client/escrow.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use crate::generate_update_call;
use escrow_canister::*;

// Queries

// Updates
generate_update_call!(create_offer);
generate_update_call!(notify_deposit);

pub mod happy_path {
use candid::Principal;
use pocket_ic::PocketIc;
use types::{CanisterId, Cryptocurrency, TimestampMillis, TokenInfo, UserId};

#[allow(clippy::too_many_arguments)]
pub fn create_offer(
env: &mut PocketIc,
sender: Principal,
escrow_canister_id: CanisterId,
input_token: Cryptocurrency,
input_amount: u128,
output_token: Cryptocurrency,
output_amount: u128,
expires_at: TimestampMillis,
) -> u32 {
let response = super::create_offer(
env,
sender,
escrow_canister_id,
&escrow_canister::create_offer::Args {
input_token: TokenInfo {
token: input_token.clone(),
ledger: input_token.ledger_canister_id().unwrap(),
decimals: input_token.decimals().unwrap(),
fee: input_token.fee().unwrap(),
},
input_amount,
output_token: TokenInfo {
token: output_token.clone(),
ledger: output_token.ledger_canister_id().unwrap(),
decimals: output_token.decimals().unwrap(),
fee: output_token.fee().unwrap(),
},
output_amount,
expires_at,
},
);

match response {
escrow_canister::create_offer::Response::Success(result) => result.id,
response => panic!("'create_offer' error: {response:?}"),
}
}

pub fn notify_deposit(env: &mut PocketIc, user_id: UserId, escrow_canister_id: CanisterId, offer_id: u32) {
let response = super::notify_deposit(
env,
user_id.into(),
escrow_canister_id,
&escrow_canister::notify_deposit::Args { offer_id, user_id: None },
);

match response {
escrow_canister::notify_deposit::Response::Success => {}
response => panic!("'notify_deposit' error: {response:?}"),
}
}
}
33 changes: 12 additions & 21 deletions backend/integration_tests/src/client/icrc1.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{generate_query_call, generate_update_call};
use candid::Nat;
use icrc_ledger_types::icrc1::account::Account;
use icrc_ledger_types::icrc1::transfer::{NumTokens, TransferArg, TransferError};
use icrc_ledger_types::icrc1::transfer::{TransferArg, TransferError};

// Queries
generate_query_call!(icrc1_balance_of);
Expand All @@ -17,7 +17,6 @@ pub mod icrc1_balance_of {
}

pub mod icrc1_transfer {

use super::*;

type Type = TransferArg;
Expand All @@ -36,21 +35,21 @@ pub mod happy_path {
pub fn transfer(
env: &mut PocketIc,
sender: Principal,
icp_ledger_canister_id: CanisterId,
recipient: Principal,
amount_e8s: u64,
ledger_canister_id: CanisterId,
recipient: impl Into<Account>,
amount: u128,
) -> BlockIndex {
icrc1_transfer(
env,
sender,
icp_ledger_canister_id,
ledger_canister_id,
&icrc1_transfer::Args {
from_subaccount: None,
to: Account::from(recipient),
to: recipient.into(),
fee: None,
created_at_time: None,
memo: None,
amount: NumTokens::from(amount_e8s),
amount: amount.into(),
},
)
.unwrap()
Expand All @@ -59,18 +58,10 @@ pub mod happy_path {
.unwrap()
}

pub fn balance_of(env: &PocketIc, icp_ledger_canister_id: CanisterId, principal: Principal) -> u64 {
icrc1_balance_of(
env,
Principal::anonymous(),
icp_ledger_canister_id,
&icrc1_balance_of::Args {
owner: principal,
subaccount: None,
},
)
.0
.try_into()
.unwrap()
pub fn balance_of(env: &PocketIc, ledger_canister_id: CanisterId, account: impl Into<Account>) -> u128 {
icrc1_balance_of(env, Principal::anonymous(), ledger_canister_id, &account.into())
.0
.try_into()
.unwrap()
}
}
9 changes: 2 additions & 7 deletions backend/integration_tests/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ mod macros;

pub mod community;
pub mod cycles_dispenser;
pub mod escrow;
pub mod group;
pub mod group_index;
pub mod icrc1;
Expand Down Expand Up @@ -95,13 +96,7 @@ pub fn register_diamond_user(env: &mut PocketIc, canister_ids: &CanisterIds, con
}

pub fn upgrade_user(user: &User, env: &mut PocketIc, canister_ids: &CanisterIds, controller: Principal) {
icrc1::happy_path::transfer(
env,
controller,
canister_ids.icp_ledger,
user.user_id.into(),
1_000_000_000u64,
);
icrc1::happy_path::transfer(env, controller, canister_ids.icp_ledger, user.user_id, 1_000_000_000);

user_index::happy_path::pay_for_diamond_membership(
env,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::env::ENV;
use crate::rng::random_string;
use crate::{client, CanisterIds, TestEnv, User};
use candid::Principal;
use itertools::Itertools;
use pocket_ic::PocketIc;
use std::ops::Deref;
use types::CommunityId;
Expand Down Expand Up @@ -70,7 +71,10 @@ fn cancel_channel_invites_succeeds() {
client::community::happy_path::cancel_invites(env, user1.principal, community_id, vec![user2.user_id], Some(channel_id));

let community_details = client::community::happy_path::selected_initial(env, &user1, community_id);
assert_eq!(community_details.invited_users, vec![user2.user_id, user3.user_id]);
assert_eq!(
community_details.invited_users.into_iter().sorted().collect_vec(),
vec![user2.user_id, user3.user_id].into_iter().sorted().collect_vec()
);

let channel_details = client::community::happy_path::selected_channel_initial(env, &user1, community_id, channel_id);
assert_eq!(channel_details.invited_users, vec![user3.user_id]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ fn send_crypto_in_channel() {
send_message_result,
user_canister::send_message_with_transfer_to_channel::Response::Success(_)
) {
let user2_balance = balance_of(env, canister_ids.icp_ledger, user2.user_id.into());
let user2_balance = balance_of(env, canister_ids.icp_ledger, user2.user_id);
assert_eq!(user2_balance, 10000);
} else {
panic!("{send_message_result:?}")
Expand All @@ -124,7 +124,7 @@ fn send_prize_in_channel() {
channel_id,
} = init_test_data(env, canister_ids, *controller);

let initial_user1_balance = balance_of(env, canister_ids.icp_ledger, user1.canister()) as u128;
let initial_user1_balance = balance_of(env, canister_ids.icp_ledger, user1.canister());
let fee = 10000;
let prizes = vec![Tokens::from_e8s(100000)];
let total = prizes.iter().map(|t| (t.e8s() as u128) + fee).sum::<u128>();
Expand Down Expand Up @@ -167,19 +167,19 @@ fn send_prize_in_channel() {
send_message_result,
user_canister::send_message_with_transfer_to_channel::Response::Success(_)
) {
let user1_balance_after_sending_prize = balance_of(env, canister_ids.icp_ledger, user1.canister()) as u128;
let user1_balance_after_sending_prize = balance_of(env, canister_ids.icp_ledger, user1.canister());
assert_eq!(user1_balance_after_sending_prize, initial_user1_balance - total - fee);

let community_balance_after_sending_prize = balance_of(env, canister_ids.icp_ledger, community_id.into()) as u128;
let community_balance_after_sending_prize = balance_of(env, canister_ids.icp_ledger, Principal::from(community_id));
assert_eq!(community_balance_after_sending_prize, total);

env.advance_time(Duration::from_secs(2));
tick_many(env, 5);

let user1_balance_after_refund = balance_of(env, canister_ids.icp_ledger, user1.canister()) as u128;
let user1_balance_after_refund = balance_of(env, canister_ids.icp_ledger, user1.canister());
assert_eq!(user1_balance_after_refund, initial_user1_balance - 2 * fee);

let community_balance_after_refund = balance_of(env, canister_ids.icp_ledger, community_id.into()) as u128;
let community_balance_after_refund = balance_of(env, canister_ids.icp_ledger, Principal::from(community_id));
assert_eq!(community_balance_after_refund, 0);
} else {
panic!("{send_message_result:?}")
Expand Down
2 changes: 1 addition & 1 deletion backend/integration_tests/src/cycles_dispenser_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ fn icp_is_burned_into_cycles() {
*controller,
canister_ids.icp_ledger,
canister_ids.cycles_dispenser,
1_000_000_000_000u64,
1_000_000_000_000,
);

let icp_balance_e8s = client::icrc1::happy_path::balance_of(env, canister_ids.icp_ledger, canister_ids.cycles_dispenser);
Expand Down
Loading
Loading