Skip to content

Commit

Permalink
Switch ICDex over to using Pool mode (#5325)
Browse files Browse the repository at this point in the history
  • Loading branch information
hpeebles authored Feb 5, 2024
1 parent c9a2225 commit 64ddf16
Show file tree
Hide file tree
Showing 10 changed files with 122 additions and 45 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

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

6 changes: 6 additions & 0 deletions backend/canisters/market_maker/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

### Changed

- Switch ICDex over to using `Pool` mode ([#5325](https://github.com/open-chat-labs/open-chat/pull/5325))

## [[2.0.1044](https://github.com/open-chat-labs/open-chat/releases/tag/v2.0.1044-market_maker)] - 2024-02-03

### Changed

- Log request params when there is an error ([#5320](https://github.com/open-chat-labs/open-chat/pull/5320))

## [[2.0.1043](https://github.com/open-chat-labs/open-chat/releases/tag/v2.0.1043-market_maker)] - 2024-02-02
Expand Down
2 changes: 2 additions & 0 deletions backend/canisters/market_maker/impl/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ ic-cdk = { workspace = true }
ic-cdk-macros = { workspace = true }
ic-cdk-timers = { workspace = true }
ic-stable-structures = { workspace = true }
icdex_canister = { path = "../../../external_canisters/icdex/api" }
icdex_canister_c2c_client = { path = "../../../external_canisters/icdex/c2c_client" }
icdex_client = { path = "../../../libraries/icdex_client" }
icrc_ledger_canister_c2c_client = { path = "../../../external_canisters/icrc_ledger/c2c_client" }
icrc-ledger-types = { workspace = true }
Expand Down
80 changes: 79 additions & 1 deletion backend/canisters/market_maker/impl/src/exchanges/icdex.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
use crate::exchanges::Exchange;
use crate::read_state;
use async_trait::async_trait;
use ic_cdk::api::call::CallResult;
use icdex_canister::deposit::Token0OrToken1;
use icdex_client::ICDexClient;
use types::{AggregatedOrders, CancelOrderRequest, MakeOrderRequest, Order, TokenInfo};
use icrc_ledger_types::icrc1::account::Account;
use icrc_ledger_types::icrc1::transfer::TransferArg;
use types::{AggregatedOrders, CancelOrderRequest, CanisterId, MakeOrderRequest, Order, TokenInfo};

#[async_trait]
impl<M: Fn(MakeOrderRequest) + Send + Sync, C: Fn(CancelOrderRequest) + Send + Sync> Exchange for ICDexClient<M, C> {
Expand Down Expand Up @@ -40,3 +44,77 @@ impl<M: Fn(MakeOrderRequest) + Send + Sync, C: Fn(CancelOrderRequest) + Send + S
Ok(())
}
}

pub async fn deposit_funds() {
let (chat_ledger_canister_id, icp_ledger_canister_id, this_canister_id, dex_canister_id, test_mode) = read_state(|state| {
(
state.data.chat_ledger_canister_id,
state.data.icp_ledger_canister_id,
state.env.canister_id(),
CanisterId::from_text("52ypw-riaaa-aaaar-qadjq-cai").unwrap(),
state.data.test_mode,
)
});

let subaccount: [u8; 32] = hex::decode(if test_mode {
"d56cc65cb00be8eb9be533b3f67ef41f2d9403cffa38d7218a2ec741db58af3b"
} else {
"005f6dfd2c9c4f5bb7ec67a4a8ae7e93fc97e4518e865c52d8108e6f4f7fe748"
})
.unwrap()
.try_into()
.unwrap();

let to = Account {
owner: dex_canister_id,
subaccount: Some(subaccount),
};

if let Ok(response) =
icrc_ledger_canister_c2c_client::icrc1_balance_of(chat_ledger_canister_id, &Account::from(this_canister_id)).await
{
let amount = u128::try_from(response.0).unwrap().saturating_sub(100_000);

if amount > 0 {
let _ = icrc_ledger_canister_c2c_client::icrc1_transfer(
chat_ledger_canister_id,
&TransferArg {
from_subaccount: None,
to,
fee: None,
created_at_time: None,
memo: None,
amount: amount.into(),
},
)
.await;

let deposit_args = (Token0OrToken1::Token0, amount.saturating_sub(100_000).into(), None);
let _ = icdex_canister_c2c_client::deposit(dex_canister_id, deposit_args).await;
}
}

if let Ok(response) =
icrc_ledger_canister_c2c_client::icrc1_balance_of(icp_ledger_canister_id, &Account::from(this_canister_id)).await
{
let amount = u128::try_from(response.0).unwrap().saturating_sub(10_000);

if amount > 0 {
let _ = icrc_ledger_canister_c2c_client::icrc1_transfer(
icp_ledger_canister_id,
&TransferArg {
from_subaccount: None,
to,
fee: None,
created_at_time: None,
memo: None,
amount: amount.into(),
},
)
.await;

let deposit_args = (Token0OrToken1::Token1, amount.saturating_sub(10_000).into(), None);
let _ = icdex_canister_c2c_client::deposit(dex_canister_id, deposit_args).await;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use crate::lifecycle::{init_env, init_state};
use crate::memory::get_upgrades_memory;
use crate::{mutate_state, Data};
use crate::{exchanges, Data};
use canister_logger::LogEntry;
use canister_tracing_macros::trace;
use ic_cdk_macros::post_upgrade;
use market_maker_canister::post_upgrade::Args;
use market_maker_canister::{ICDEX_EXCHANGE_ID, ICDEX_EXCHANGE_V2_ID};
use stable_memory::get_reader;
use std::time::Duration;
use tracing::info;
use utils::cycles::init_cycles_dispenser_client;

Expand All @@ -26,11 +26,5 @@ fn post_upgrade(args: Args) {

info!(version = %args.wasm_version, "Post-upgrade complete");

// Post release - remove this
mutate_state(|state| {
if let Some(mut config) = state.data.exchange_config.get(&ICDEX_EXCHANGE_ID).cloned() {
config.enabled = false;
state.data.exchange_config.insert(ICDEX_EXCHANGE_V2_ID, config);
}
});
ic_cdk_timers::set_timer(Duration::ZERO, || ic_cdk::spawn(exchanges::icdex::deposit_funds()));
}
11 changes: 11 additions & 0 deletions backend/external_canisters/icdex/api/src/updates/accountConfig.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use candid::CandidType;
use serde::{Deserialize, Serialize};

pub type Args = (Mode, bool, Vec<u8>);
pub type Response = ();

#[derive(CandidType, Serialize, Deserialize)]
pub enum Mode {
PoolMode,
TunnelMode,
}
13 changes: 13 additions & 0 deletions backend/external_canisters/icdex/api/src/updates/deposit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use candid::{CandidType, Nat};
use serde::{Deserialize, Serialize};

pub type Args = (Token0OrToken1, Nat, Option<[u8; 32]>);
pub type Response = ();

#[derive(CandidType, Serialize, Deserialize)]
pub enum Token0OrToken1 {
#[serde(rename = "token0")]
Token0,
#[serde(rename = "token1")]
Token1,
}
3 changes: 3 additions & 0 deletions backend/external_canisters/icdex/api/src/updates/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#[allow(non_snake_case)]
pub mod accountConfig;
#[allow(non_snake_case)]
pub mod cancelByTxid;
pub mod deposit;
pub mod trade;
2 changes: 2 additions & 0 deletions backend/external_canisters/icdex/c2c_client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@ generate_candid_c2c_call_tuple_args!(pending);
generate_candid_c2c_call_tuple_args!(stats);

// Updates
generate_candid_c2c_call_tuple_args!(accountConfig);
generate_candid_c2c_call_tuple_args!(cancelByTxid);
generate_candid_c2c_call_tuple_args!(deposit);
generate_candid_c2c_call_tuple_args!(trade);
36 changes: 1 addition & 35 deletions backend/libraries/icdex_client/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use candid::Nat;
use ic_cdk::api::call::{CallResult, RejectionCode};
use icdex_canister::{ICDexOrderType, MakeOrderResponse, OrderPrice, OrderQuantity, TradingOrder};
use icrc_ledger_types::icrc1::transfer::TransferArg;
use types::{AggregatedOrders, CancelOrderRequest, CanisterId, MakeOrderRequest, Order, OrderType, TokenInfo};

pub struct ICDexClient<M: Fn(MakeOrderRequest), C: Fn(CancelOrderRequest)> {
Expand Down Expand Up @@ -90,47 +89,14 @@ impl<M: Fn(MakeOrderRequest), C: Fn(CancelOrderRequest)> ICDexClient<M, C> {
}

pub async fn make_order(&self, order: MakeOrderRequest) -> CallResult<()> {
let (account, nonce) =
icdex_canister_c2c_client::getTxAccount(self.dex_canister_id, (self.this_canister_id.to_string(),))
.await
.map(|(a, _, n, _)| (a, n))?;

let (ledger_canister_id, amount) = match order.order_type {
OrderType::Bid => (
self.quote_token.ledger,
order.amount * order.price / self.base_token_units_per_whole(),
),
OrderType::Ask => (self.base_token.ledger, order.amount),
};
icrc_ledger_canister_c2c_client::icrc1_transfer(
ledger_canister_id,
&TransferArg {
from_subaccount: None,
to: account,
fee: None,
created_at_time: None,
memo: None,
amount: amount.into(),
},
)
.await?
.map_err(|t| (RejectionCode::Unknown, format!("{t:?}")))?;

let quantity = match order.order_type {
OrderType::Bid => OrderQuantity::Buy(order.amount.into(), 0u32.into()),
OrderType::Ask => OrderQuantity::Sell(order.amount.into()),
};
// Convert the price per whole into the price per `smallest_order_size`
let price = (order.price * self.smallest_order_size / self.base_token_units_per_whole()).into();

let args = (
OrderPrice { price, quantity },
ICDexOrderType::Limit,
None,
Some(nonce),
None,
None,
);
let args = (OrderPrice { price, quantity }, ICDexOrderType::Limit, None, None, None, None);

match icdex_canister_c2c_client::trade(self.dex_canister_id, args.clone()).await?.0 {
MakeOrderResponse::Ok(_) => {
Expand Down

0 comments on commit 64ddf16

Please sign in to comment.