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: improve overall rust IC code #26

Open
wants to merge 1 commit into
base: master
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
4 changes: 2 additions & 2 deletions core/ic/src/tera/src/api/consume_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn consume(from: Principal, nonce: Nonce, payload: Vec<Nat>) -> ConsumeMessageRe
from: from.to_nat(),
to: caller.to_nat(),
nonce: nonce.clone(),
payload: payload.clone(),
payload,
});

let res = STATE.with(|s| {
Expand All @@ -41,7 +41,7 @@ fn consume(from: Principal, nonce: Nonce, payload: Vec<Nat>) -> ConsumeMessageRe
let message_counter = message.unwrap();

// if there is exactly 1 message, we'll remove it from hashmap
if message_counter.clone() == 1 {
if *message_counter == 1 {
map.remove(&msg_hash);
} else {
*message_counter -= 1;
Expand Down
2 changes: 1 addition & 1 deletion core/ic/src/tera/src/api/send_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ fn send(to: Principal, payload: Vec<Nat>) -> SendMessageResponse {
let msg_hash = Message.calculate_hash(OutgoingMessageHashParams {
from: caller.to_nat(),
to: to.to_nat(),
payload: payload.clone(),
payload,
});

STATE.with(|s| SendMessageResponse(s.store_outgoing_message(msg_hash)))
Expand Down
8 changes: 4 additions & 4 deletions core/ic/src/tera/src/common/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl Keccak256HashFn<IncomingMessageHashParams> for Message {
let slice = &x.0.to_bytes_be()[..];
// calculate zero values padding
let l = 32 - slice.len();
[&f[..l], &slice].concat()
[&f[..l], slice].concat()
})
.collect();

Expand All @@ -37,7 +37,7 @@ impl Keccak256HashFn<IncomingMessageHashParams> for Message {

let result = hasher.finalize();

hex::encode(result.to_vec())
hex::encode(result)
}
}

Expand All @@ -55,7 +55,7 @@ impl Keccak256HashFn<OutgoingMessageHashParams> for Message {
let slice = &x.0.to_bytes_be()[..];
// calculate zero values padding
let l = 32 - slice.len();
[&f[..l], &slice].concat()
[&f[..l], slice].concat()
})
.collect();

Expand All @@ -66,6 +66,6 @@ impl Keccak256HashFn<OutgoingMessageHashParams> for Message {

let result = hasher.finalize();

hex::encode(result.to_vec())
hex::encode(result)
}
}
6 changes: 3 additions & 3 deletions core/ic/src/tera/src/tera.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ impl From<OutgoingMessagePair> for OutgoingMessage {
let mut msg_key = [0u8; 32];
let msg_key_slice = &hex::decode(message.msg_key).unwrap()[..];

msg_key.copy_from_slice(&msg_key_slice);
msg_key.copy_from_slice(msg_key_slice);

OutgoingMessage {
msg_key: msg_key.to_vec(),
Expand All @@ -96,7 +96,7 @@ pub trait ToNat {
impl ToNat for Principal {
#[inline(always)]
fn to_nat(&self) -> Nat {
Nat::from(num_bigint::BigUint::from_bytes_be(&self.as_slice()[..]))
Nat::from(num_bigint::BigUint::from_bytes_be(self.as_slice()))
}
}

Expand Down Expand Up @@ -213,7 +213,7 @@ impl TerabetiaState {
.borrow()
.contains(&caller())
.then(|| ())
.ok_or("Caller is not authorized".to_string())
.ok_or_else(|| "Caller is not authorized".to_string())
}

/// Add new pid to list of authorized
Expand Down
16 changes: 8 additions & 8 deletions eth_bridge/ic/src/eth_proxy/src/api/burn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async fn burn(eth_addr: EthereumAddr, amount: Nat) -> TxReceipt {
if (weth_ic_addr_pid.name().await).is_err() {
return Err(TxError::Other(format!(
"Token {} canister is not responding!",
weth_ic_addr_pid.to_string(),
weth_ic_addr_pid,
)));
}

Expand All @@ -47,7 +47,7 @@ async fn burn(eth_addr: EthereumAddr, amount: Nat) -> TxReceipt {
STATE.with(|s| {
let current_balance = s
.get_balance(caller, weth_ic_addr_pid)
.unwrap_or(Nat::from(0));
.unwrap_or_else(|| Nat::from(0));

s.update_balance(
caller,
Expand All @@ -56,15 +56,15 @@ async fn burn(eth_addr: EthereumAddr, amount: Nat) -> TxReceipt {
);

s.add_claimable_message(ClaimableMessage {
owner: eth_addr.clone(),
owner: eth_addr,
msg_hash: outgoing_message.msg_hash.clone(),
msg_key: outgoing_message.msg_key.clone(),
token: weth_ic_addr_pid.clone(),
msg_key: outgoing_message.msg_key,
token: weth_ic_addr_pid,
amount: amount.clone(),
});
});
// All correct
return Ok(burn_txn_id);
Ok(burn_txn_id)
}
// send_message to Tera error
Err(_) => {
Expand All @@ -77,9 +77,9 @@ async fn burn(eth_addr: EthereumAddr, amount: Nat) -> TxReceipt {
}
// burn error
Err(error) => {
return Err(error);
Err(error)
}
};
}
}
// transfer_from error
Err(error) => Err(error),
Expand Down
6 changes: 3 additions & 3 deletions eth_bridge/ic/src/eth_proxy/src/api/handle_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ use crate::proxy::WETH_ADDRESS_ETH;
async fn handler(eth_addr: EthereumAddr, nonce: Nonce, payload: Vec<Nat>) -> TxReceipt {
let eth_addr_hex = hex::encode(eth_addr);

if !(eth_addr_hex
== WETH_ADDRESS_ETH
if eth_addr_hex
!= WETH_ADDRESS_ETH
.trim_start_matches("0x")
.to_ascii_lowercase())
.to_ascii_lowercase()
{
return Err(TxError::Other(format!(
"Eth Contract Address is inccorrect: {}",
Expand Down
2 changes: 1 addition & 1 deletion eth_bridge/ic/src/eth_proxy/src/api/mint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub async fn mint(nonce: Nonce, payload: Vec<Nat>) -> TxReceipt {
if (weth_ic_addr_pid.name().await).is_err() {
return Err(TxError::Other(format!(
"Token {} canister is not responding!",
weth_ic_addr_pid.to_string()
weth_ic_addr_pid,
)));
}

Expand Down
4 changes: 2 additions & 2 deletions eth_bridge/ic/src/eth_proxy/src/api/withdraw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub async fn withdraw(eth_addr: EthereumAddr, _amount: Nat) -> TxReceipt {
if (weth_ic_addr_pid.name().await).is_err() {
return Err(TxError::Other(format!(
"Token {} canister is not responding!",
weth_ic_addr_pid.to_string(),
weth_ic_addr_pid,
)));
}

Expand All @@ -44,7 +44,7 @@ pub async fn withdraw(eth_addr: EthereumAddr, _amount: Nat) -> TxReceipt {
.await
.is_err()
{
return Err(TxError::Other(format!("Sending message to L1 failed!")));
return Err(TxError::Other("Sending message to L1 failed!".to_string()));
}

let zero = Nat::from(0_u32);
Expand Down
8 changes: 4 additions & 4 deletions eth_bridge/ic/src/eth_proxy/src/common/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl Keccak256HashFn<IncomingMessageHashParams> for Message {
let slice = &x.0.to_bytes_be()[..];
// calculate zero values padding
let l = 32 - slice.len();
[&f[..l], &slice].concat()
[&f[..l], slice].concat()
})
.collect();

Expand All @@ -55,7 +55,7 @@ impl Keccak256HashFn<IncomingMessageHashParams> for Message {

let result = hasher.finalize();

hex::encode(result.to_vec())
hex::encode(result)
}
}

Expand All @@ -73,7 +73,7 @@ impl Keccak256HashFn<OutgoingMessageHashParams> for Message {
let slice = &x.0.to_bytes_be()[..];
// calculate zero values padding
let l = 32 - slice.len();
[&f[..l], &slice].concat()
[&f[..l], slice].concat()
})
.collect();

Expand All @@ -84,6 +84,6 @@ impl Keccak256HashFn<OutgoingMessageHashParams> for Message {

let result = hasher.finalize();

hex::encode(result.to_vec())
hex::encode(result)
}
}
1 change: 0 additions & 1 deletion eth_bridge/ic/src/eth_proxy/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ fn main() {}
#[cfg(not(any(target_arch = "wasm32", test)))]
fn main() {
use common::types::*;
use ic_kit::candid;
use ic_kit::candid::Nat;
use ic_kit::Principal;

Expand Down
15 changes: 7 additions & 8 deletions eth_bridge/ic/src/eth_proxy/src/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl ProxyState {
.or_default()
.entry(token_id)
.or_default()
.add_assign(amount.clone())
.add_assign(amount)
}

pub fn update_balance(&self, caller: Principal, token_id: TokendId, amount: Nat) {
Expand All @@ -78,10 +78,9 @@ impl ProxyState {

pub fn add_claimable_message(&self, message: ClaimableMessage) {
let mut map = self.messages_unclaimed.borrow_mut();
let messages = map.entry(message.owner.clone()).or_insert_with(Vec::new);
let messages = map.entry(message.owner).or_insert_with(Vec::new);

messages.push(message.clone());
return;
messages.push(message);
}

pub fn get_claimable_messages(&self, eth_address: EthereumAddr) -> Vec<ClaimableMessage> {
Expand All @@ -91,7 +90,7 @@ impl ProxyState {
.get(&eth_address)
.unwrap_or(&vec![])
.clone();
return unclaimed_messages;
unclaimed_messages
}

pub fn remove_claimable_message(
Expand All @@ -115,7 +114,7 @@ impl ProxyState {

messages.remove(item_index);

return Ok(());
Ok(())
}

pub fn authorize(&self, other: Principal) {
Expand All @@ -131,7 +130,7 @@ impl ProxyState {
.borrow()
.contains(&ic::caller())
.then(|| ())
.ok_or("Caller is not authorized".to_string())
.ok_or_else(|| "Caller is not authorized".to_string())
}

pub fn take_all(&self) -> StableProxyState {
Expand Down Expand Up @@ -166,7 +165,7 @@ pub trait ToNat {

impl ToNat for Principal {
fn to_nat(&self) -> Nat {
Nat::from(num_bigint::BigUint::from_bytes_be(&self.as_slice()[..]))
Nat::from(num_bigint::BigUint::from_bytes_be(self.as_slice()))
}
}

Expand Down
21 changes: 10 additions & 11 deletions magic_bridge/ic/src/dip20_proxy/src/api/burn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async fn burn(token_id: TokendId, eth_addr: EthereumAddr, amount: Nat) -> TxRece
if (token_id.name().await).is_err() {
return Err(TxError::Other(format!(
"Token {} canister is not responding!",
token_id.to_string(),
token_id,
)));
}

Expand Down Expand Up @@ -55,8 +55,9 @@ async fn burn(token_id: TokendId, eth_addr: EthereumAddr, amount: Nat) -> TxRece
STATE.with(|s| {
// there could be an underflow here
// like negative balance
let current_balance =
s.get_balance(caller, token_id).unwrap_or(Nat::from(0));
let current_balance = s
.get_balance(caller, token_id)
.unwrap_or_else(|| Nat::from(0));

s.update_balance(
caller,
Expand All @@ -65,15 +66,15 @@ async fn burn(token_id: TokendId, eth_addr: EthereumAddr, amount: Nat) -> TxRece
);

s.add_claimable_message(ClaimableMessage {
owner: eth_addr.clone(),
owner: eth_addr,
msg_hash: outgoing_message.msg_hash.clone(),
msg_key: outgoing_message.msg_key.clone(),
token: token_id.clone(),
msg_key: outgoing_message.msg_key,
token: token_id,
amount: amount.clone(),
});
});
// All correct
return Ok(burn_txn_id);
Ok(burn_txn_id)
}
// send_message error
Err(_) => {
Expand All @@ -85,10 +86,8 @@ async fn burn(token_id: TokendId, eth_addr: EthereumAddr, amount: Nat) -> TxRece
}
}
// burn error
Err(error) => {
return Err(error);
}
};
Err(error) => Err(error),
}
}
// transfer error
Err(error) => Err(error),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ fn remove_claimable(
token_id: TokendId,
amount: Nat,
) -> Result<bool, String> {
STATE.with(|s| s.remove_claimable_message(eth_address, token_id.clone(), amount.clone()))
STATE.with(|s| s.remove_claimable_message(eth_address, token_id, amount.clone()))
}
6 changes: 3 additions & 3 deletions magic_bridge/ic/src/dip20_proxy/src/api/handle_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ use crate::proxy::{ERC20_ADDRESS_ETH, MAGIC_ADDRESS_IC};
async fn handler(eth_addr: EthereumAddr, nonce: Nonce, payload: Vec<Nat>) -> TxReceipt {
let erc20_addr_hex = hex::encode(eth_addr);

if !(erc20_addr_hex
== ERC20_ADDRESS_ETH
if erc20_addr_hex
!= ERC20_ADDRESS_ETH
.trim_start_matches("0x")
.to_ascii_lowercase())
.to_ascii_lowercase()
{
return Err(TxError::Other(format!(
"ERC20 Contract Address is inccorrect: {}",
Expand Down
2 changes: 1 addition & 1 deletion magic_bridge/ic/src/dip20_proxy/src/api/mint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub async fn mint(token_id: TokendId, nonce: Nonce, payload: Vec<Nat>) -> TxRece
if (token_id.name().await).is_err() {
return Err(TxError::Other(format!(
"Token {} canister is not responding!",
token_id.to_string()
token_id
)));
}

Expand Down
4 changes: 2 additions & 2 deletions magic_bridge/ic/src/dip20_proxy/src/api/withdraw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub async fn withdraw(token_id: TokendId, eth_addr: EthereumAddr, _amount: Nat)
if (token_id.name().await).is_err() {
return Err(TxError::Other(format!(
"Token {} canister is not responding!",
token_id.to_string(),
token_id,
)));
}

Expand All @@ -37,7 +37,7 @@ pub async fn withdraw(token_id: TokendId, eth_addr: EthereumAddr, _amount: Nat)
let payload = [eth_addr.clone().to_nat(), balance.clone()].to_vec();
let tera_id = Principal::from_text(TERA_ADDRESS).unwrap();
if tera_id.send_message(erc20_addr_pid, payload).await.is_err() {
return Err(TxError::Other(format!("Sending message to L1 failed!")));
return Err(TxError::Other("Sending message to L1 failed!".to_string()));
}

let zero = Nat::from(0_u32);
Expand Down
Loading