Skip to content

Commit

Permalink
Merge pull request #35 from sideprotocol/ics100
Browse files Browse the repository at this point in the history
Ics100: Add timestamp checks, Migrate, events
  • Loading branch information
amityadav0 authored Aug 23, 2023
2 parents 014013a + 55561ca commit 387c0f2
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 15 deletions.
9 changes: 7 additions & 2 deletions contracts/ics100/src/atomic_swap_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub(crate) fn do_ibc_packet_receive(

pub(crate) fn on_received_make(
deps: DepsMut,
_env: Env,
env: Env,
packet: &IbcPacket,
msg: MakeSwapMsg,
) -> Result<IbcReceiveResponse, ContractError> {
Expand All @@ -86,6 +86,7 @@ pub(crate) fn on_received_make(
cancel_timestamp: None,
complete_timestamp: None,
path: path.clone(),
create_timestamp: env.block.time.seconds()
};

let count_check = ORDER_TO_COUNT.may_load(deps.storage, &order_id)?;
Expand All @@ -97,6 +98,7 @@ pub(crate) fn on_received_make(

let res = IbcReceiveResponse::new()
.set_ack(ack_success())
.add_attribute("order_id", order_id)
.add_attribute("action", "receive")
.add_attribute("success", "true")
.add_attribute("action", "make_swap_received");
Expand Down Expand Up @@ -142,6 +144,7 @@ pub(crate) fn on_received_take(
let res = IbcReceiveResponse::new()
.set_ack(ack_success())
.add_submessages(submsg)
.add_attribute("order_id", order_id)
.add_attribute("action", "receive")
.add_attribute("success", "true");

Expand Down Expand Up @@ -175,6 +178,7 @@ pub(crate) fn on_received_cancel(

let res = IbcReceiveResponse::new()
.set_ack(ack_success())
.add_attribute("order_id", order_id)
.add_attribute("action", "receive")
.add_attribute("success", "true");

Expand All @@ -185,7 +189,7 @@ pub(crate) fn on_received_cancel(
pub(crate) fn on_packet_success(
deps: DepsMut,
packet: IbcPacket,
env: Env
env: Env,
) -> Result<IbcBasicResponse, ContractError> {
let packet_data: AtomicSwapPacketData = from_binary(&packet.data)?;

Expand Down Expand Up @@ -217,6 +221,7 @@ pub(crate) fn on_packet_success(
taker: None,
cancel_timestamp: None,
complete_timestamp: None,
create_timestamp: env.block.time.seconds()
};

append_atomic_order(deps.storage, &order_id, &new_order)?;
Expand Down
70 changes: 57 additions & 13 deletions contracts/ics100/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,29 @@
use cosmwasm_std::entry_point;
use cosmwasm_std::{
to_binary, Binary, Deps, DepsMut, Env, IbcMsg, IbcTimeout, MessageInfo, Order, Response,
StdResult, Timestamp, StdError,
StdResult, StdError,
};

use cw2::set_contract_version;

use crate::error::ContractError;
use crate::msg::{
AtomicSwapPacketData, CancelSwapMsg, DetailsResponse, ExecuteMsg, InstantiateMsg, ListResponse,
MakeSwapMsg, QueryMsg, SwapMessageType, TakeSwapMsg,
MakeSwapMsg, QueryMsg, SwapMessageType, TakeSwapMsg, MigrateMsg,
};
use crate::state::{
AtomicSwapOrder,
Status,
// CHANNEL_INFO,
SWAP_ORDERS, set_atomic_order, get_atomic_order, COUNT,
SWAP_ORDERS, set_atomic_order, get_atomic_order, COUNT, move_order_to_bottom,
};
use crate::utils::extract_source_channel_for_taker_msg;
use cw_storage_plus::Bound;

// Version info, for migration info
const CONTRACT_NAME: &str = "ics100-swap";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
const DEFAULT_TIMEOUT_TIMESTAMP_OFFSET: u64 = 600;

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
Expand All @@ -48,14 +49,24 @@ pub fn execute(
ExecuteMsg::MakeSwap(msg) => execute_make_swap(deps, env, info, msg),
ExecuteMsg::TakeSwap(msg) => execute_take_swap(deps, env, info, msg),
ExecuteMsg::CancelSwap(msg) => execute_cancel_swap(deps, env, info, msg),
// MakeBid,
// - User will bid on make orders
// - Once make is close, delete user bid data structure
// TakeBid
// - User can choose to TakeBid
// - Once make is close delete user bid data structure by returning amounts of all bids
// or maybe let user reclaim their amounts
// - Reclaim amounts ? OR Integrate in make done pool ?
// - integrating can result in more state updates and refund amounts.

}
}

// MakeSwap is called when the maker wants to make atomic swap. The method create new order and lock tokens.
// This is the step 1 (Create order & Lock Token) of the atomic swap: https://github.com/cosmos/ibc/tree/main/spec/app/ics-100-atomic-swap
pub fn execute_make_swap(
_deps: DepsMut,
_env: Env,
env: Env,
info: MessageInfo,
msg: MakeSwapMsg,
) -> Result<Response, ContractError> {
Expand Down Expand Up @@ -84,8 +95,11 @@ pub fn execute_make_swap(
let ibc_msg = IbcMsg::SendPacket {
channel_id: msg.source_channel.clone(),
data: to_binary(&ibc_packet)?,
// timeout: msg.timeout_timestamp.into(),
timeout: IbcTimeout::from(Timestamp::from_nanos(msg.timeout_timestamp)),
timeout: IbcTimeout::from(
env.block
.time
.plus_seconds(DEFAULT_TIMEOUT_TIMESTAMP_OFFSET),
),
};

let res = Response::new()
Expand All @@ -98,7 +112,7 @@ pub fn execute_make_swap(
// This method lock the order (set a value to the field "Taker") and lock Token
pub fn execute_take_swap(
deps: DepsMut,
_env: Env,
env: Env,
info: MessageInfo,
msg: TakeSwapMsg,
) -> Result<Response, ContractError> {
Expand Down Expand Up @@ -129,8 +143,6 @@ pub fn execute_take_swap(

// Checks if the order has already been taken
if let Some(_taker) = order.taker {
// Do Nothing
} else {
return Err(ContractError::OrderTaken);
}

Expand All @@ -139,6 +151,11 @@ pub fn execute_take_swap(
return Err(ContractError::InvalidTakerAddress);
}

if env.block.time.seconds() > order.maker.expiration_timestamp {
move_order_to_bottom(deps.storage, &msg.order_id)?;
return Err(ContractError::Expired);
}

order.taker = Some(msg.clone());

let ibc_packet = AtomicSwapPacketData {
Expand All @@ -152,15 +169,19 @@ pub fn execute_take_swap(
let ibc_msg = IbcMsg::SendPacket {
channel_id: extract_source_channel_for_taker_msg(&order.path)?,
data: to_binary(&ibc_packet)?,
timeout: IbcTimeout::from(Timestamp::from_nanos(msg.timeout_timestamp)),
timeout: IbcTimeout::from(
env.block
.time
.plus_seconds(DEFAULT_TIMEOUT_TIMESTAMP_OFFSET),
),
};

// Save order
set_atomic_order(deps.storage, &order.id, &order)?;
//SWAP_ORDERS.save(deps.storage, &order.id, &order)?;

let res = Response::new()
.add_message(ibc_msg)
.add_attribute("order_id", msg.order_id)
.add_attribute("action", "take_swap")
.add_attribute("order_id", order.id.clone());
return Ok(res);
Expand All @@ -170,7 +191,7 @@ pub fn execute_take_swap(
// It is executed on the Maker chain. Only the maker of the order can cancel the order.
pub fn execute_cancel_swap(
deps: DepsMut,
_env: Env,
env: Env,
info: MessageInfo,
msg: CancelSwapMsg,
) -> Result<Response, ContractError> {
Expand Down Expand Up @@ -202,16 +223,39 @@ pub fn execute_cancel_swap(
let ibc_msg = IbcMsg::SendPacket {
channel_id: order.maker.source_channel,
data: to_binary(&packet)?,
timeout: Timestamp::from_nanos(msg.timeout_timestamp.parse().unwrap()).into(),
timeout: IbcTimeout::from(
env.block
.time
.plus_seconds(DEFAULT_TIMEOUT_TIMESTAMP_OFFSET),
),
};

let res = Response::new()
.add_message(ibc_msg)
.add_attribute("order_id", msg.order_id)
.add_attribute("action", "cancel_swap")
.add_attribute("order_id", order.id.clone());
return Ok(res);
}

#[entry_point]
pub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {
let ver = cw2::get_contract_version(deps.storage)?;
// ensure we are migrating from an allowed contract
if ver.contract != CONTRACT_NAME {
return Err(StdError::generic_err("Can only upgrade from same type").into());
}
// note: better to do proper semver compare, but string compare *usually* works
if ver.version >= CONTRACT_VERSION.to_string() {
return Err(StdError::generic_err("Cannot upgrade from a newer version").into());
}

// set the new version
cw2::set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;

Ok(Response::default())
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
match msg {
Expand Down
4 changes: 4 additions & 0 deletions contracts/ics100/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ pub fn is_valid_name(name: &str) -> bool {
true
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct MigrateMsg {
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub enum SwapMessageType {
#[serde(rename = "TYPE_UNSPECIFIED")]
Expand Down
2 changes: 2 additions & 0 deletions contracts/ics100/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ pub struct AtomicSwapOrder {
// an IBC path, define channel and port on both Maker Chain and Taker Chain
pub path: String,
pub taker: Option<TakeSwapMsg>,
// In seconds
pub create_timestamp: u64,
pub cancel_timestamp: Option<Timestamp>,
pub complete_timestamp: Option<Timestamp>,
}
Expand Down

0 comments on commit 387c0f2

Please sign in to comment.