Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
TropicalDog17 committed Oct 12, 2023
1 parent a096d9d commit 4187c33
Show file tree
Hide file tree
Showing 6 changed files with 143 additions and 24 deletions.
33 changes: 33 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ optimize = """sudo docker run --rm -v "$(pwd)":/code \
cosmwasm-schema = "1.4.0"
cosmwasm-std = { version = "1.4.0" }
cw-storage-plus = "1.1.0"
cw-utils = "1.0.2"
cw2 = "1.1.0"
cw20-base = "1.1.1"
schemars = "0.8.10"
serde = { version = "1.0.145", default-features = false, features = ["derive"] }
thiserror = { version = "1.0.31" }
Expand Down
56 changes: 35 additions & 21 deletions src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,26 @@
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult};
use cosmwasm_std::{to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, Uint128, Addr};
use cw2::set_contract_version;
// use cw2::set_contract_version;

use crate::error::ContractError;
use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg, SocialResponse};
use crate::state::{Platform, ProfileId, SocialInfo, ADDRESS_TO_SOCIAL, OWNER, SOCIAL_TO_ADDRESS};
use cosmwasm_std::Addr;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::state::{Platform, ProfileId, SocialInfo, ADDRESS_TO_SOCIAL, OWNER, SOCIAL_TO_ADDRESS, ACCEPTED_TOKEN};
use cw20_base::contract::{execute_transfer, execute_send};
const CONTRACT_NAME: &str = "cosmos:donex-sm";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct State {
pub count: i32,
pub owner: Addr,
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
_deps: DepsMut,
deps: DepsMut,
_env: Env,
info: MessageInfo,
_msg: InstantiateMsg,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
set_contract_version(_deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
OWNER.save(_deps.storage, &info.sender)?;
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
OWNER.save(deps.storage, &info.sender)?;
ACCEPTED_TOKEN.save(deps.storage, &msg.accepted_token)?;
Ok(Response::new()
.add_attribute("method", "instantiate")
.add_attribute("owner", info.sender))
Expand All @@ -37,16 +29,17 @@ pub fn instantiate(
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut,
_env: Env,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
use ExecuteMsg::*;
match msg {
ExecuteMsg::SubmitSocial {
SubmitSocial {
social_info,
address,
} => submit_social_link(deps, info, social_info, address),
// ExecuteMsg::Reset { count } => try_reset(deps, info, count),
Donate {recipient, amount} => donate(deps, env, info, recipient, amount),
}
}

Expand Down Expand Up @@ -83,6 +76,23 @@ pub fn submit_social_link(
ADDRESS_TO_SOCIAL.save(deps.storage, address, &social_info)?;
Ok(Response::new().add_attribute("method", "submit_social_link"))
}

pub fn donate(mut deps: DepsMut, env: Env, info: MessageInfo, recipient: Addr, amount: Uint128) -> Result<Response, ContractError>{
const FEE_RATIO: u64 = 5;
let accepted_token = ACCEPTED_TOKEN.load(deps.storage)?;
let _owner = OWNER.load(deps.storage);
let denom = accepted_token.first().unwrap();
let donation = cw_utils::must_pay(&info, &denom)?.u128();

// Calculate fee and actual amount receive
let fee = donation / FEE_RATIO as u128 * 100;
let actual = donation - fee;

execute_transfer(deps.branch(), env.clone(), info.clone(), recipient.to_string(), actual.into())?;
let msg =format!("Handling donation from {} to {}", info.sender.to_string(), recipient.to_string());
execute_send(deps.branch(), env.clone(), info.clone(), env.contract.address.to_string(), amount, cosmwasm_std::Binary(msg.into_bytes()))?;
Ok(Response::new())
}
fn query_by_social_link(
deps: Deps,
profile_id: ProfileId,
Expand Down Expand Up @@ -110,7 +120,9 @@ mod tests {
.instantiate_contract(
code_id,
Addr::unchecked("owner"),
&InstantiateMsg {},
&InstantiateMsg {
accepted_token: vec!["ATOM".to_string()],
},
&[],
"Contract",
None,
Expand Down Expand Up @@ -147,7 +159,9 @@ mod tests {
deps.as_mut(),
env.clone(),
mock_info("sender", &[]),
InstantiateMsg {},
InstantiateMsg {
accepted_token: vec!["ATOM".to_string()],
},
)
.unwrap();
let resp = query(
Expand Down
64 changes: 63 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use cosmwasm_std::StdError;
use thiserror::Error;

use cw_utils::PaymentError;
#[derive(Error, Debug)]
pub enum ContractError {
#[error("{0}")]
Expand All @@ -14,6 +14,68 @@ pub enum ContractError {
SocialAlreadyLinked {},
#[error("Social info not found")]
SocialInfoNotFound {},

#[error("Payment error: {0}")]
Payment(#[from] PaymentError),

#[error("Cannot set to own account")]
CannotSetOwnAccount {},

// Unused error case. Zero is now treated like every other value.
#[deprecated(note = "Unused. All zero amount checks have been removed")]
#[error("Invalid zero amount")]
InvalidZeroAmount {},

#[error("Allowance is expired")]
Expired {},

#[error("No allowance for this account")]
NoAllowance {},

#[error("Minting cannot exceed the cap")]
CannotExceedCap {},

#[error("Logo binary data exceeds 5KB limit")]
LogoTooBig {},

#[error("Invalid xml preamble for SVG")]
InvalidXmlPreamble {},

#[error("Invalid png header")]
InvalidPngHeader {},

#[error("Invalid expiration value")]
InvalidExpiration {},

#[error("Duplicate initial balance addresses")]
DuplicateInitialBalanceAddresses {},

// Add any other custom errors you like here.
// Look at https://docs.rs/thiserror/1.0.21/thiserror/ for details.
}

impl From<cw20_base::ContractError> for ContractError {
fn from(err: cw20_base::ContractError) -> Self {
match err {
cw20_base::ContractError::Std(error) => ContractError::Std(error),
cw20_base::ContractError::Unauthorized {} => ContractError::Unauthorized {},
cw20_base::ContractError::CannotSetOwnAccount {} => {
ContractError::CannotSetOwnAccount {}
}
cw20_base::ContractError::InvalidExpiration {} => ContractError::InvalidExpiration {},
cw20_base::ContractError::InvalidZeroAmount {} => ContractError::InvalidZeroAmount {},

Check warning on line 66 in src/error.rs

View workflow job for this annotation

GitHub Actions / Test Suite

use of deprecated variant `cw20_base::ContractError::InvalidZeroAmount`: Unused. All zero amount checks have been removed

Check warning on line 66 in src/error.rs

View workflow job for this annotation

GitHub Actions / Test Suite

use of deprecated variant `error::ContractError::InvalidZeroAmount`: Unused. All zero amount checks have been removed

Check warning on line 66 in src/error.rs

View workflow job for this annotation

GitHub Actions / Test Suite

use of deprecated variant `cw20_base::ContractError::InvalidZeroAmount`: Unused. All zero amount checks have been removed

Check warning on line 66 in src/error.rs

View workflow job for this annotation

GitHub Actions / Test Suite

use of deprecated variant `error::ContractError::InvalidZeroAmount`: Unused. All zero amount checks have been removed
cw20_base::ContractError::Expired {} => ContractError::Expired {},
cw20_base::ContractError::NoAllowance {} => ContractError::NoAllowance {},
cw20_base::ContractError::CannotExceedCap {} => ContractError::CannotExceedCap {},
// This should never happen, as this contract doesn't use logo
cw20_base::ContractError::LogoTooBig {}
| cw20_base::ContractError::InvalidPngHeader {}
| cw20_base::ContractError::InvalidXmlPreamble {} => {
ContractError::Std(StdError::generic_err(err.to_string()))
}
cw20_base::ContractError::DuplicateInitialBalanceAddresses {} => {
ContractError::DuplicateInitialBalanceAddresses {}
}
}
}
}
10 changes: 8 additions & 2 deletions src/msg.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
use crate::state::{Platform, ProfileId, SocialInfo};
use cosmwasm_schema::{cw_serde, QueryResponses};
use cosmwasm_std::Addr;
use cosmwasm_std::{Addr, Uint128};
#[cw_serde]
pub struct InstantiateMsg {}
pub struct InstantiateMsg {
pub accepted_token: Vec<String>,
}

#[cw_serde]
pub enum ExecuteMsg {
SubmitSocial {
social_info: SocialInfo,
address: Addr,
},
Donate{
recipient: Addr,
amount: Uint128
}
}

#[cw_serde]
Expand Down
2 changes: 2 additions & 0 deletions src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ pub type ProfileId = String;
pub const SOCIAL_TO_ADDRESS: Map<SocialInfo, Addr> = Map::new("social_to_address");
pub const ADDRESS_TO_SOCIAL: Map<Addr, SocialInfo> = Map::new("wallet_to_social");
pub const OWNER: Item<Addr> = Item::new("owner");
pub const ACCEPTED_TOKEN: Item<Vec<String>> = Item::new("accepted_token");

0 comments on commit 4187c33

Please sign in to comment.