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

chore: some changes and TODO requests #51

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
28 changes: 28 additions & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion contracts/ics100/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ serde = { version = "1.0.103", default-features = false, features = ["derive"] }
thiserror = { version = "1.0.23" }
hex = "0.3.1"
sha2 = "0.8.0"

rand = "0.8.5"
[dev-dependencies]
cosmwasm-schema = { version = "1.0.0-beta3" }
56 changes: 16 additions & 40 deletions contracts/ics100/src/atomic_swap_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
use crate::{
error::ContractError,
msg::{AtomicSwapPacketData, CancelSwapMsg, MakeSwapMsg, SwapMessageType, TakeSwapMsg, MakeBidMsg, TakeBidMsg, CancelBidMsg, Height},
state::{AtomicSwapOrder, Status, Side, set_atomic_order, get_atomic_order, ORDER_TO_COUNT, append_atomic_order, move_order_to_bottom, ORDER_TOTAL_COUNT, BID_ORDER_TO_COUNT, Bid, BidStatus, BIDS},
state::{AtomicSwapOrder, Status, Side, set_atomic_order, get_atomic_order, ORDER_TO_COUNT, append_atomic_order, move_order_to_bottom, ORDER_TOTAL_COUNT, BID_ORDER_TO_COUNT, Bid, BidStatus, BIDS, remove_atomic_order},
utils::{
decode_make_swap_msg, decode_take_swap_msg, generate_order_id, order_path, send_tokens,
},
Expand Down Expand Up @@ -39,7 +39,7 @@ pub(crate) fn do_ibc_packet_receive(
packet: &IbcPacket,
) -> Result<IbcReceiveResponse, ContractError> {
let packet_data: AtomicSwapPacketData = from_binary(&packet.data)?;

match packet_data.r#type {
SwapMessageType::Unspecified => {
let res = IbcReceiveResponse::new()
Expand All @@ -50,7 +50,9 @@ pub(crate) fn do_ibc_packet_receive(
}
SwapMessageType::MakeSwap => {
let msg: MakeSwapMsg = decode_make_swap_msg(&packet_data.data.clone());
on_received_make(deps, env, packet, msg)
let order_id = packet_data.order_id.unwrap();
let path = packet_data.path.unwrap();
on_received_make(deps, env, msg, &order_id, &path)
}
SwapMessageType::TakeSwap => {
let msg: TakeSwapMsg = decode_take_swap_msg(&packet_data.data.clone());
Expand Down Expand Up @@ -78,26 +80,20 @@ pub(crate) fn do_ibc_packet_receive(
pub(crate) fn on_received_make(
deps: DepsMut,
env: Env,
packet: &IbcPacket,
msg: MakeSwapMsg,
order_id:&String,
path: &String,
) -> Result<IbcReceiveResponse, ContractError> {
let path = order_path(
msg.source_channel.clone(),
msg.source_port.clone(),
packet.dest.channel_id.clone(),
packet.dest.port_id.clone(),
packet.sequence,
)?;
let order_id = generate_order_id(&path, msg.clone())?;

let swap_order = AtomicSwapOrder {
id: order_id.clone(),
id: order_id.to_string(),
side: Side::Remote,
maker: msg.clone(),
status: Status::Sync,
taker: None,
cancel_timestamp: None,
complete_timestamp: None,
path: path.clone(),
path: path.to_string(),
create_timestamp: env.block.time.seconds()
};

Expand Down Expand Up @@ -339,31 +335,10 @@ pub(crate) fn on_packet_success(
// This logic is executed when Taker chain acknowledge the make swap packet.
SwapMessageType::Unspecified => Ok(IbcBasicResponse::new()),
SwapMessageType::MakeSwap => {
// let msg: MakeSwapMsg = from_binary(&packet_data.data.clone())?;
let msg: MakeSwapMsg = decode_make_swap_msg(&packet_data.data.clone());
let path = order_path(
msg.source_channel.clone(),
msg.source_port.clone(),
packet.dest.channel_id.clone(),
packet.dest.port_id.clone(),
packet.sequence,
)?;
let order_id = generate_order_id(&path, msg.clone())?;

let new_order = AtomicSwapOrder {
id: order_id.clone(),
side: Side::Native,
maker: msg.clone(),
status: Status::Sync,
path: path.clone(),
taker: None,
cancel_timestamp: None,
complete_timestamp: None,
create_timestamp: env.block.time.seconds()
};

append_atomic_order(deps.storage, &order_id, &new_order)?;

let order_id = &packet_data.order_id.unwrap();
let mut order = get_atomic_order(deps.storage, &order_id).unwrap();
order.status = Status::Sync;
let _ = set_atomic_order(deps.storage, order_id, &order);
Ok(IbcBasicResponse::new().add_attributes(attributes))
}
// This is the step 9 (Transfer Take Token & Close order): https://github.com/cosmos/ibc/tree/main/spec/app/ics-100-atomic-swap
Expand Down Expand Up @@ -548,7 +523,8 @@ pub(crate) fn refund_packet_token(
// let swap_order: AtomicSwapOrder = SWAP_ORDERS.load(deps.storage, &order_id)?;
let maker_address: Addr = deps.api.addr_validate(&msg.maker_address)?;
let submsg = send_tokens(&maker_address, msg.sell_token)?;

let order_id = packet.order_id.unwrap();
let _ = remove_atomic_order(deps.storage, &order_id);
Ok(submsg)
}
// This is the step 7.2 (Unlock order and refund) of the atomic swap: https://github.com/cosmos/ibc/tree/main/spec/app/ics-100-atomic-swap
Expand Down
42 changes: 35 additions & 7 deletions contracts/ics100/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ use crate::msg::{
use crate::state::{
AtomicSwapOrder,
Status,
// CHANNEL_INFO,
SWAP_ORDERS, set_atomic_order, get_atomic_order, COUNT, move_order_to_bottom, BID_ORDER_TO_COUNT, Bid, BIDS, INACTIVE_SWAP_ORDERS,
CHANNEL_INFO,
append_atomic_order,
SWAP_ORDERS, set_atomic_order, get_atomic_order, COUNT, move_order_to_bottom, BID_ORDER_TO_COUNT, Bid, BIDS, INACTIVE_SWAP_ORDERS, Side,
};
use crate::utils::extract_source_channel_for_taker_msg;
use crate::utils::{generate_order_id,extract_source_channel_for_taker_msg,order_path};
use cw_storage_plus::Bound;

// Version info, for migration info
Expand Down Expand Up @@ -77,11 +78,38 @@ pub fn execute_make_swap(
))));
}

// TODO: I guess we have add order here with status - Initial.
// This optimistic operation will update user's experiences in frontend code.
// When success update status as a Sync. when failed, we can remove that pool with refund logic.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we don't need to remove it, we can add a status Failed.


let channel_info = CHANNEL_INFO.load(_deps.storage, &msg.source_channel)?;
let path = order_path(
msg.source_channel.clone(),
msg.source_port.clone(),
channel_info.counterparty_endpoint.channel_id,
channel_info.counterparty_endpoint.port_id,
)?;

let order_id = generate_order_id(&path)?;
let new_order = AtomicSwapOrder {
id: order_id.clone(),
side: Side::Native,
maker: msg.clone(),
status: Status::Initial,
path: path.clone(),
taker: None,
cancel_timestamp: None,
complete_timestamp: None,
create_timestamp: env.block.time.seconds()
};

append_atomic_order(_deps.storage, &order_id, &new_order)?;

let ibc_packet = AtomicSwapPacketData {
r#type: SwapMessageType::MakeSwap,
data: to_binary(&msg)?,
order_id: None,
path: None,
order_id: Some(order_id),
path: Some(path),
memo: String::new(),
};

Expand Down Expand Up @@ -803,11 +831,11 @@ mod tests {
source_port.clone(),
destination_channel.clone(),
destination_port.clone(),
sequence.clone(),
//sequence.clone(),
)
.unwrap();

let order_id = generate_order_id(&path, create.clone());
let order_id = generate_order_id(&path);
println!("order_id is {:?}", &order_id);
}

Expand Down
3 changes: 3 additions & 0 deletions contracts/ics100/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ pub enum ContractError {
#[error("Atomic swap already exists")]
AlreadyExists,

#[error("Atomic swap doesn't exist")]
NotFound,

#[error("Order already taken")]
OrderTaken,

Expand Down
1 change: 1 addition & 0 deletions contracts/ics100/src/ibc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ pub fn ibc_channel_connect(
counterparty_endpoint: channel.counterparty_endpoint,
connection_id: channel.connection_id,
};

CHANNEL_INFO.save(deps.storage, &info.id, &info)?;

Ok(IbcBasicResponse::default())
Expand Down
4 changes: 4 additions & 0 deletions contracts/ics100/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ pub struct Bid {
pub bidder: String,
pub bidder_receiver: String,
}
pub struct CounterPartyIBC {
pub channel: String,
pub port: String
}
// Map for order id -> Vec<Bids>
// Order_id + BID_COUNT
pub const BIDS: Map<(&str, &str), Bid> = Map::new("swap_order");
Expand Down
73 changes: 44 additions & 29 deletions contracts/ics100/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,47 +9,62 @@ use crate::{
msg::{Height, HeightOutput, MakeSwapMsg, MakeSwapMsgOutput, TakeSwapMsg, TakeSwapMsgOutput},
ContractError,
};

pub fn generate_order_id(order_path: &str, msg: MakeSwapMsg) -> StdResult<String> {
let prefix = order_path.as_bytes();

let msg_output = MakeSwapMsgOutput {
source_port: msg.source_port.clone(),
source_channel: msg.source_channel.clone(),
sell_token: msg.sell_token.clone(),
buy_token: msg.buy_token.clone(),
maker_address: msg.maker_address.clone(),
maker_receiving_address: msg.maker_receiving_address.clone(),
desired_taker: msg.desired_taker.clone(),
timeout_height: HeightOutput {
revision_number: msg.timeout_height.revision_number.clone().to_string(),
revision_height: msg.timeout_height.revision_height.clone().to_string(),
},
timeout_timestamp: msg.timeout_timestamp.clone().to_string(),
expiration_timestamp: msg.expiration_timestamp.clone().to_string(),
take_bids: msg.take_bids.clone(),
};

let binding_output = to_binary(&msg_output)?;
let msg_bytes = binding_output.as_slice();
let res: Vec<u8> = [prefix.clone(), msg_bytes.clone()].concat();

use rand::Rng;
// Temporary: Disable.
// pub fn generate_order_id(order_path: &str, msg: MakeSwapMsg) -> StdResult<String> {
// let prefix = order_path.as_bytes();

// let msg_output = MakeSwapMsgOutput {
// source_port: msg.source_port.clone(),
// source_channel: msg.source_channel.clone(),
// sell_token: msg.sell_token.clone(),
// buy_token: msg.buy_token.clone(),
// maker_address: msg.maker_address.clone(),
// maker_receiving_address: msg.maker_receiving_address.clone(),
// desired_taker: msg.desired_taker.clone(),
// timeout_height: HeightOutput {
// revision_number: msg.timeout_height.revision_number.clone().to_string(),
// revision_height: msg.timeout_height.revision_height.clone().to_string(),
// },
// timeout_timestamp: msg.timeout_timestamp.clone().to_string(),
// expiration_timestamp: msg.expiration_timestamp.clone().to_string(),
// take_bids: msg.take_bids.clone(),
// };

// let binding_output = to_binary(&msg_output)?;
// let msg_bytes = binding_output.as_slice();
// let res: Vec<u8> = [prefix.clone(), msg_bytes.clone()].concat();

// let hash = Sha256::digest(&res);
// let id = hex::encode(hash);

// Ok(id)
// }
pub fn generate_order_id(order_path: &str) -> StdResult<String> {
// Generate random bytes
let mut rng = rand::thread_rng();
let random_bytes: [u8; 16] = rng.gen();

// Create the ID by combining the order_path and random bytes
let res: Vec<u8> = [order_path.as_bytes(), &random_bytes].concat();

// Hash the result to create a fixed-length ID
let hash = Sha256::digest(&res);
let id = hex::encode(hash);

Ok(id)
}


pub fn order_path(
source_channel: String,
source_port: String,
destination_channel: String,
destination_port: String,
id: u64,
//id: u64,
) -> StdResult<String> {
let path = format!(
"channel/{}/port/{}/channel/{}/port/{}/{}",
source_channel, source_port, destination_channel, destination_port, id,
"channel/{}/port/{}/channel/{}/port/{}",
source_channel, source_port, destination_channel, destination_port,
);
Ok(path)
}
Expand Down
Loading