Skip to content

Commit

Permalink
feat: Merge cw-hub-bnUSD to hubToken (#30)
Browse files Browse the repository at this point in the history
* style: cargo fix and clippy

* feat: changes after the review

* fix: cargo clippy run

* feat: change common/rlp to crate rlp

* style: cargo fix and clippy

* feat: changes after the review

* fix: cargo clippy run

* feat: change common/rlp to crate rlp

* feat: network validation added, and tests fixed according to that

* feat: changes after the review

* feat: changes after the review

* feat: changes after the review

* feat: changes after the review

* feat: changes after the review

* style: run cargo fmt

Signed-off-by: Night Owl <[email protected]>

* fix: validate icon address fixes

* feat: event functions created

* feat: cw20base query and execute msgs added

* feat: integration tests added

* chore: run pre-commit script

* chore: run precommit script

* style: cargo clippy

* fix: delete xcall-mock-contract

* feat: cw20-flow tests added

* feat: query tests added

* fix: icon-check validation removed

* fix: implementation of instantiate and setup changed

* feat: contract migrate entry point added

* fix: change handleMessage signature

* feat: integration tests for cross transfer and xcrossTransfer

* fix: changes in migration entry point

* fix: network address, and xcall messages are used from xcall

* fix: change in decodable implementation

* chore: cargo lints fixes

* fix: unnecessary clone and strng lenght comparition removed

* fix: spelling error

Signed-off-by: Night Owl <[email protected]>

* fix: make imports pub

Signed-off-by: Night Owl <[email protected]>

* chore: run lint scripts

Signed-off-by: Night Owl <[email protected]>

* fix: xcall imported as library

* fix: cargo lock file updated

* fix: cargo lock file updated

* fix: exclude archway from member list in workspace

Signed-off-by: Night Owl <[email protected]>

* fix: remove unnecessary use

Signed-off-by: Night Owl <[email protected]>

* update: cargo packages

Signed-off-by: Night Owl <[email protected]>

---------

Signed-off-by: Night Owl <[email protected]>
Co-authored-by: Night Owl <[email protected]>
Co-authored-by: qwerty0789 <[email protected]>
  • Loading branch information
3 people authored Sep 8, 2023
1 parent a602c22 commit 5a670c5
Show file tree
Hide file tree
Showing 37 changed files with 4,684 additions and 920 deletions.
1,392 changes: 1,271 additions & 121 deletions Cargo.lock

Large diffs are not rendered by default.

10 changes: 3 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
[workspace]
members = [
# "contracts/core-contracts/*",
"contracts/token-contracts/cw-hub-bnusd",
"contracts/cw-common",
"contracts/mock-contracts/x-call-mock",]

members = ["contracts/token-contracts/cw-hub-bnusd", "contracts/cw-common"]
exclude = ["contracts/archway"]

[profile.release]
opt-level = 'z'
Expand All @@ -18,4 +14,4 @@ incremental = false
overflow-checks = true

[workspace.dependencies]
debug_print = "1.0.0"
debug_print = "1.0.0"
4 changes: 3 additions & 1 deletion contracts/cw-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,7 @@ cosmwasm-std = { version = "1.2.5", default-features = false }
rlp = { version = "0.5.2", default-features = false }
cosmwasm-schema = "1.2.6"
cw-storage-plus = "1.1.0"

cw20-base = { version = "1.0.1", features = ["library"] }
cw-xcall-multi = {package="cw-xcall", git="https://github.com/icon-project/xcall-multi.git", branch="main", features=["library"]}
cw-xcall-lib={package="cw-xcall-lib", git="https://github.com/icon-project/xcall-multi.git", branch="main", features = ["library"]}

13 changes: 9 additions & 4 deletions contracts/cw-common/src/data_types.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::str::FromStr;

use cosmwasm_schema::cw_serde;
use cosmwasm_std::Addr;
use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream};
Expand Down Expand Up @@ -33,11 +35,14 @@ impl Encodable for CrossTransfer {
}

impl Decodable for CrossTransfer {
fn decode(rlp: &Rlp<'_>) -> Result<CrossTransfer, DecoderError> {
fn decode(rlp: &Rlp<'_>) -> Result<Self, DecoderError> {
let from: String = rlp.val_at(1)?;
let to: String = rlp.val_at(2)?;
Ok(Self {
method: rlp.val_at(0)?,
from: NetworkAddress(rlp.val_at(1)?),
to: NetworkAddress(rlp.val_at(2)?),
from: NetworkAddress::from_str(&from)
.map_err(|_e| rlp::DecoderError::RlpInvalidLength)?,
to: NetworkAddress::from_str(&to).map_err(|_e| rlp::DecoderError::RlpInvalidLength)?,
value: rlp.val_at(3)?,
data: rlp.val_at(4)?,
})
Expand All @@ -55,7 +60,7 @@ impl Encodable for CrossTransferRevert {
}

impl Decodable for CrossTransferRevert {
fn decode(rlp: &Rlp<'_>) -> Result<CrossTransferRevert, DecoderError> {
fn decode(rlp: &Rlp<'_>) -> Result<Self, DecoderError> {
let from: String = rlp.val_at(1)?;
Ok(Self {
method: rlp.val_at(0)?,
Expand Down
59 changes: 54 additions & 5 deletions contracts/cw-common/src/hub_token_msg.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
use cosmwasm_schema::{cw_serde, QueryResponses};
use cosmwasm_std::Addr;
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Addr, Uint128};
use cw20::Expiration;

use crate::network_address::NetworkAddress;
pub use cw20_base::msg::{ExecuteMsg as Cw20ExecuteMsg, QueryMsg};

#[cw_serde]
pub struct InstantiateMsg {
pub x_call: String,
pub hub_address: String,
}

//TODO: Add network address as a parameter for xcall network address
#[cw_serde]
pub enum ExecuteMsg {
Setup {
Expand All @@ -26,8 +27,56 @@ pub enum ExecuteMsg {
amount: u128,
data: Vec<u8>,
},
/// Transfer is a base message to move tokens to another account without triggering actions
Transfer {
recipient: String,
amount: Uint128,
},
/// Burn is a base message to destroy tokens forever
Burn {
amount: Uint128,
},
/// Only with "approval" extension. Allows spender to access an additional amount tokens
/// from the owner's (env.sender) account. If expires is Some(), overwrites current allowance
/// expiration with this one.
IncreaseAllowance {
spender: String,
amount: Uint128,
expires: Option<Expiration>,
},
/// Only with "approval" extension. Lowers the spender's access of tokens
/// from the owner's (env.sender) account by amount. If expires is Some(), overwrites current
/// allowance expiration with this one.
DecreaseAllowance {
spender: String,
amount: Uint128,
expires: Option<Expiration>,
},
/// Only with "approval" extension. Transfers amount tokens from owner -> recipient
/// if `env.sender` has sufficient pre-approval.
TransferFrom {
owner: String,
recipient: String,
amount: Uint128,
},
/// Only with "approval" extension. Destroys tokens forever
BurnFrom {
owner: String,
amount: Uint128,
},
/// Only with the "mintable" extension. If authorized, creates amount new tokens
/// and adds to the recipient balance.
Mint {
recipient: String,
amount: Uint128,
},
/// Only with the "mintable" extension. The current minter may set
/// a new minter. Setting the minter to None will remove the
/// token's minter forever.
UpdateMinter {
new_minter: Option<String>,
},
}

#[cw_serde]

Check warning on line 81 in contracts/cw-common/src/hub_token_msg.rs

View check run for this annotation

Codecov / codecov/patch

contracts/cw-common/src/hub_token_msg.rs#L81

Added line #L81 was not covered by tests
#[derive(QueryResponses)]
pub enum QueryMsg {}
pub struct MigrateMsg {}
150 changes: 22 additions & 128 deletions contracts/cw-common/src/network_address.rs
Original file line number Diff line number Diff line change
@@ -1,97 +1,13 @@
use std::str::FromStr;
pub use cosmwasm_std::Addr;
pub use cw_xcall_lib::network_address::{NetId, NetworkAddress};
pub use std::str::FromStr;

use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Addr, StdError};
use cw_storage_plus::{Key, KeyDeserialize, PrimaryKey};

#[cw_serde]
#[derive(Eq)]
pub struct NetId(String);

impl From<String> for NetId {
fn from(value: String) -> Self {
Self(value)
}
}

impl ToString for NetId {
fn to_string(&self) -> String {
self.0.to_string()
}
pub trait IconAddressValidation {
fn validate_foreign_addresses(&self) -> bool;
}

impl NetId {
pub fn as_str(&self) -> &str {
&self.0
}
}

impl FromStr for NetId {
type Err = StdError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(s.to_owned()))
}
}

impl<'a> PrimaryKey<'a> for NetId {
type Prefix = ();

type SubPrefix = ();

type Suffix = Self;

type SuperSuffix = Self;

fn key(&self) -> Vec<Key> {
vec![Key::Ref(self.0.as_bytes())]
}
}

impl KeyDeserialize for NetId {
type Output = NetId;

fn from_vec(value: Vec<u8>) -> cosmwasm_std::StdResult<Self::Output> {
let result = String::from_utf8(value)
.map_err(StdError::invalid_utf8)
.unwrap();
let net_id = NetId::from_str(&result).unwrap();
Ok(net_id)
}
}

#[cw_serde]
#[derive(Eq)]
pub struct NetworkAddress(pub String);

impl NetworkAddress {
pub fn new(nid: &str, address: &str) -> Self {
Self(format!("{}/{}", nid, address))
}

pub fn nid(&self) -> NetId {
NetId(self.get_parts()[0].to_string())
}

pub fn is_empty(&self) -> bool {
self.0.is_empty()
}

pub fn account(&self) -> Addr {
Addr::unchecked(self.get_parts()[1])
}

pub fn get_parts(&self) -> Vec<&str> {
let parts = self.0.split('/').collect::<Vec<&str>>();
parts
}

pub fn parse_parts(&self) -> (NetId, Addr) {
let parts = self.0.split('/').collect::<Vec<&str>>();
(NetId(parts[0].to_string()), Addr::unchecked(parts[1]))
}

pub fn validate(&self) -> bool {
impl IconAddressValidation for NetworkAddress {
fn validate_foreign_addresses(&self) -> bool {
let parts = self.get_parts();
let net_id = parts[0].to_string();
let address = parts[1];
Expand All @@ -102,27 +18,6 @@ impl NetworkAddress {
}
}

impl ToString for NetworkAddress {
fn to_string(&self) -> String {
self.0.to_string()
}
}

impl FromStr for NetworkAddress {
type Err = StdError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts = s.split('/').collect::<Vec<&str>>();
if parts.len() != 2 {
return Err(StdError::GenericErr {
msg: "Invalid Network Address".to_owned(),
});
}
let na = format!("{}/{}", parts[0], parts[1]);
Ok(Self(na))
}
}

fn validate_icon_address(address: &str) -> bool {
let lowercase_address = address.to_lowercase();

Expand All @@ -140,44 +35,43 @@ fn is_valid_character_set(address: &str) -> bool {
#[test]
fn test_parse_btp_address() {
let network_address =
NetworkAddress("0x01.icon/cx9876543210fedcba9876543210fedcba98765432".to_string());
let (network, account) = network_address.parse_parts();
assert_eq!(network, NetId("0x01.icon".to_string()));
NetworkAddress::from_str("0x01.icon/cx9876543210fedcba9876543210fedcba98765432").unwrap();
assert_eq!(network_address.nid(), NetId::from_str("0x01.icon").unwrap());
assert_eq!(
account,
network_address.account(),
Addr::unchecked("cx9876543210fedcba9876543210fedcba98765432")
);
}

#[test]
fn address_validation_test() {
let network_address =
NetworkAddress("0x01.icon/cx9876543210fedcba9876543210fedcba98765432".to_string());
let res = network_address.validate();
NetworkAddress::from_str("0x7.icon/cxd06f80e28e989a67e297799ab1fb501cdddc2b4d").unwrap();
let res = network_address.validate_foreign_addresses();
assert!(res);

let network_address =
NetworkAddress("0x01.icon/hx9876543210fedcba9876543210fedcba98765432".to_string());
let res = network_address.validate();
NetworkAddress::from_str("0x01.icon/hx9876543210fedcba9876543210fedcba98765432").unwrap();
let res = network_address.validate_foreign_addresses();
assert!(res);

let network_address =
NetworkAddress("0x01.bsc/cx9876543210fedcba9876543210fedcba98765432".to_string());
let res = network_address.validate();
NetworkAddress::from_str("0x01.bsc/cx9876543210fedcba9876543210fedcba98765432").unwrap();
let res = network_address.validate_foreign_addresses();
assert!(!res);

let network_address =
NetworkAddress("0x01.icon/wx9876543210fedcba9876543210fedcba98765432".to_string());
let res = network_address.validate();
NetworkAddress::from_str("0x01.icon/wx9876543210fedcba9876543210fedcba98765432").unwrap();
let res = network_address.validate_foreign_addresses();
assert!(!res);

let network_address =
NetworkAddress("0x01.icon/cx9876543210fedcba9876543210fedcba9876542".to_string());
let res = network_address.validate();
NetworkAddress::from_str("0x01.icon/cx9876543210fedcba9876543210fedcba9876542").unwrap();
let res = network_address.validate_foreign_addresses();
assert!(!res);

let network_address =
NetworkAddress("0x01.icon/cx9876543210fedcba9876543210fedcba9876543_".to_string());
let res = network_address.validate();
NetworkAddress::from_str("0x01.icon/cx9876543210fedcba9876543210fedcba9876543_").unwrap();
let res = network_address.validate_foreign_addresses();
assert!(!res);
}
34 changes: 2 additions & 32 deletions contracts/cw-common/src/x_call_msg.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,2 @@
use cosmwasm_schema::{cw_serde, QueryResponses};

#[cw_serde]
struct NetworkAddress {
address: String,
}

#[cw_serde]
pub struct InstantiateMsg {}

#[cw_serde]
#[derive(QueryResponses)]
pub enum XCallQuery {
#[returns(NetworkAddress)]
GetNetworkAddress {},
}

//TODO: Use the ibc-integration/xcallmsg and xcall contract from ibc
#[cw_serde]
pub enum XCallMsg {
SendCallMessage {
to: String,
data: Vec<u8>,
rollback: Option<Vec<u8>>,
},

TestHandleCallMessage {
from: String,
data: Vec<u8>,
hub_token: String,
},
}
pub use cw_xcall_lib::xcall_msg::ExecuteMsg as XCallMsg;
pub use cw_xcall_multi::msg::QueryMsg::GetNetworkAddress;
4 changes: 0 additions & 4 deletions contracts/mock-contracts/x-call-mock/.cargo/config

This file was deleted.

Loading

0 comments on commit 5a670c5

Please sign in to comment.