Skip to content

Commit

Permalink
Add top up for native tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
ethanfrey committed Jun 26, 2020
1 parent c054c0b commit 83a2f36
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
33 changes: 33 additions & 0 deletions contracts/cw20-escrow/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub fn handle<S: Storage, A: Api, Q: Querier>(
match msg {
HandleMsg::Create(msg) => try_create(deps, env, msg),
HandleMsg::Approve { id } => try_approve(deps, env, id),
HandleMsg::TopUp { id } => try_top_up(deps, env, id),
HandleMsg::Refund { id } => try_refund(deps, env, id),
}
}
Expand Down Expand Up @@ -64,6 +65,38 @@ pub fn try_create<S: Storage, A: Api, Q: Querier>(
Ok(res)
}

pub fn try_top_up<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
env: Env,
id: String,
) -> StdResult<HandleResponse> {
// this fails is no escrow there
let mut escrow = escrows_read(&deps.storage).load(id.as_bytes())?;

// combine these two
add_tokens(&mut escrow.native_balance, env.message.sent_funds);

let mut res = HandleResponse::default();
res.log = vec![log("action", "top_up"), log("id", id)];
Ok(res)
}

fn add_tokens(store: &mut Vec<Coin>, add: Vec<Coin>) {
for token in add {
let index = store.iter().enumerate().find_map(|(i, exist)| {
if exist.denom == token.denom {
Some(i)
} else {
None
}
});
match index {
Some(idx) => store[idx].amount += token.amount,
None => store.push(token),
}
}
}

pub fn try_approve<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
env: Env,
Expand Down
4 changes: 4 additions & 0 deletions contracts/cw20-escrow/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ pub struct InitMsg {}
#[serde(rename_all = "snake_case")]
pub enum HandleMsg {
Create(CreateMsg),
/// Adds all sent native tokens to the contract
TopUp {
id: String,
},
/// Approve sends all tokens to the recipient.
/// Only the arbiter can do this
Approve {
Expand Down

0 comments on commit 83a2f36

Please sign in to comment.