terra: contracts: fix clippy warnings (#983)

This commit is contained in:
Chirantan Ekbote 2022-03-30 19:01:43 +09:00 committed by GitHub
parent 3ceec1833f
commit 4d0e3b9030
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 80 additions and 93 deletions

View File

@ -1,5 +1,4 @@
use cosmwasm_std::{
entry_point,
to_binary,
Binary,
CosmosMsg,
@ -14,6 +13,9 @@ use cosmwasm_std::{
WasmMsg,
};
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cw2::set_contract_version;
use cw20_legacy::{
allowances::{
@ -78,7 +80,7 @@ pub fn instantiate(
total_supply: Uint128::new(0),
// set creator as minter
mint: Some(MinterData {
minter: deps.api.addr_canonicalize(&info.sender.as_str())?,
minter: deps.api.addr_canonicalize(info.sender.as_str())?,
cap: None,
}),
};
@ -88,7 +90,7 @@ pub fn instantiate(
let data = WrappedAssetInfo {
asset_chain: msg.asset_chain,
asset_address: msg.asset_address,
bridge: deps.api.addr_canonicalize(&info.sender.as_str())?,
bridge: deps.api.addr_canonicalize(info.sender.as_str())?,
};
wrapped_asset_info(deps.storage).save(&data)?;
@ -120,16 +122,14 @@ pub fn execute(
match msg {
// these all come from cw20-base to implement the cw20 standard
ExecuteMsg::Transfer { recipient, amount } => {
Ok(execute_transfer(deps, env, info, recipient, amount)?)
}
ExecuteMsg::Burn { account, amount } => {
Ok(execute_burn_from(deps, env, info, account, amount)?)
execute_transfer(deps, env, info, recipient, amount)
}
ExecuteMsg::Burn { account, amount } => execute_burn_from(deps, env, info, account, amount),
ExecuteMsg::Send {
contract,
amount,
msg,
} => Ok(execute_send(deps, env, info, contract, amount, msg)?),
} => execute_send(deps, env, info, contract, amount, msg),
ExecuteMsg::Mint { recipient, amount } => {
execute_mint_wrapped(deps, env, info, recipient, amount)
}
@ -137,36 +137,26 @@ pub fn execute(
spender,
amount,
expires,
} => Ok(execute_increase_allowance(
deps, env, info, spender, amount, expires,
)?),
} => execute_increase_allowance(deps, env, info, spender, amount, expires),
ExecuteMsg::DecreaseAllowance {
spender,
amount,
expires,
} => Ok(execute_decrease_allowance(
deps, env, info, spender, amount, expires,
)?),
} => execute_decrease_allowance(deps, env, info, spender, amount, expires),
ExecuteMsg::TransferFrom {
owner,
recipient,
amount,
} => Ok(execute_transfer_from(
deps, env, info, owner, recipient, amount,
)?),
ExecuteMsg::BurnFrom { owner, amount } => {
Ok(execute_burn_from(deps, env, info, owner, amount)?)
}
} => execute_transfer_from(deps, env, info, owner, recipient, amount),
ExecuteMsg::BurnFrom { owner, amount } => execute_burn_from(deps, env, info, owner, amount),
ExecuteMsg::SendFrom {
owner,
contract,
amount,
msg,
} => Ok(execute_send_from(
deps, env, info, owner, contract, amount, msg,
)?),
} => execute_send_from(deps, env, info, owner, contract, amount, msg),
ExecuteMsg::UpdateMetadata { name, symbol } => {
Ok(execute_update_metadata(deps, env, info, name, symbol)?)
execute_update_metadata(deps, env, info, name, symbol)
}
}
}
@ -180,11 +170,11 @@ fn execute_mint_wrapped(
) -> Result<Response, ContractError> {
// Only bridge can mint
let wrapped_info = wrapped_asset_info_read(deps.storage).load()?;
if wrapped_info.bridge != deps.api.addr_canonicalize(&info.sender.as_str())? {
if wrapped_info.bridge != deps.api.addr_canonicalize(info.sender.as_str())? {
return Err(ContractError::Unauthorized {});
}
Ok(execute_mint(deps, env, info, recipient, amount)?)
execute_mint(deps, env, info, recipient, amount)
}
fn execute_update_metadata(
@ -196,7 +186,7 @@ fn execute_update_metadata(
) -> Result<Response, ContractError> {
// Only bridge can update.
let wrapped_info = wrapped_asset_info_read(deps.storage).load()?;
if wrapped_info.bridge != deps.api.addr_canonicalize(&info.sender.as_str())? {
if wrapped_info.bridge != deps.api.addr_canonicalize(info.sender.as_str())? {
return Err(ContractError::Unauthorized {});
}
@ -221,7 +211,7 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> StdResult<Response> {
pub fn migrate(_deps: DepsMut, _env: Env, _msg: MigrateMsg) -> StdResult<Response> {
Ok(Response::new())
}

View File

@ -114,7 +114,7 @@ pub fn instantiate(
pub fn parse_vaa(deps: DepsMut, block_time: u64, data: &Binary) -> StdResult<ParsedVAA> {
let cfg = config_read(deps.storage).load()?;
let vaa: ParsedVAA = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: cfg.wormhole_contract.clone(),
contract_addr: cfg.wormhole_contract,
msg: to_binary(&WormholeQueryMsg::VerifyVAA {
vaa: data.clone(),
block_time,
@ -144,7 +144,7 @@ pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> S
),
ExecuteMsg::SubmitVaa { data } => submit_vaa(deps, env, info, &data),
ExecuteMsg::RegisterAssetHook { asset_id } => {
handle_register_asset(deps, env, info, &asset_id.as_slice())
handle_register_asset(deps, env, info, asset_id.as_slice())
}
}
}
@ -185,8 +185,8 @@ fn submit_vaa(
}
}
fn handle_governance_payload(deps: DepsMut, env: Env, data: &Vec<u8>) -> StdResult<Response> {
let gov_packet = GovernancePacket::deserialize(&data)?;
fn handle_governance_payload(deps: DepsMut, env: Env, data: &[u8]) -> StdResult<Response> {
let gov_packet = GovernancePacket::deserialize(data)?;
let module = get_string_from_32(&gov_packet.module);
if module != "NFTBridge" {
@ -280,7 +280,7 @@ fn handle_complete_transfer(
let recipient = deps
.api
.addr_humanize(&target_address)
.addr_humanize(target_address)
.or_else(|_| ContractError::WrongTargetAddressFormat.std_err())?;
let contract_addr;
@ -298,7 +298,7 @@ fn handle_complete_transfer(
let asset_id = build_asset_id(token_chain, &asset_address);
let token_uri = String::from_utf8(transfer_info.uri.to_vec())
.or_else(|_| Err(StdError::generic_err("could not parse uri string")))?;
.map_err(|_| StdError::generic_err("could not parse uri string"))?;
let mint_msg = cw721_base::msg::MintMsg {
token_id,
@ -308,7 +308,7 @@ fn handle_complete_transfer(
};
// Check if this asset is already deployed
if let Some(wrapped_addr) = wrapped_asset_read(deps.storage).load(&asset_id).ok() {
if let Ok(wrapped_addr) = wrapped_asset_read(deps.storage).load(&asset_id) {
contract_addr = wrapped_addr;
// Asset already deployed, just mint
@ -335,8 +335,8 @@ fn handle_complete_transfer(
)
} else {
(
get_string_from_32(&transfer_info.name.to_vec()),
get_string_from_32(&transfer_info.symbol.to_vec()),
get_string_from_32(&transfer_info.name),
get_string_from_32(&transfer_info.symbol),
)
};
messages.push(CosmosMsg::Wasm(WasmMsg::Instantiate {
@ -383,6 +383,7 @@ fn handle_complete_transfer(
.add_attribute("contract", contract_addr))
}
#[allow(clippy::too_many_arguments)]
fn handle_initiate_transfer(
deps: DepsMut,
env: Env,
@ -405,7 +406,7 @@ fn handle_initiate_transfer(
let mut messages: Vec<CosmosMsg> = vec![];
if let Ok(_) = wrapped_asset_address_read(deps.storage).load(asset_canonical.as_slice()) {
if wrapped_asset_address_read(deps.storage).load(asset_canonical.as_slice()).is_ok() {
// This is a deployed wrapped asset, burn it
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: asset.clone(),
@ -466,7 +467,7 @@ fn handle_initiate_transfer(
let cw721::NftInfoResponse::<Option<Empty>> { token_uri, .. } =
deps.querier
.custom_query(&QueryRequest::<Empty>::Wasm(WasmQuery::Smart {
contract_addr: asset.clone(),
contract_addr: asset,
msg: to_binary(&cw721_base::msg::QueryMsg::NftInfo {
token_id: token_id.clone(),
})?,
@ -506,7 +507,7 @@ fn handle_initiate_transfer(
.add_attribute(
"transfer.sender",
hex::encode(extend_address_to_32(
&deps.api.addr_canonicalize(&info.sender.as_str())?,
&deps.api.addr_canonicalize(info.sender.as_str())?,
)),
)
.add_attribute("transfer.recipient_chain", recipient_chain.to_string())
@ -538,13 +539,13 @@ fn handle_register_asset(
let result = bucket
.load(asset_id)
.map_err(|_| ContractError::RegistrationForbidden.std())?;
if result != HumanAddr::from(WRAPPED_ASSET_UPDATING) {
if result != WRAPPED_ASSET_UPDATING {
return ContractError::AssetAlreadyRegistered.std_err();
}
bucket.save(asset_id, &info.sender.to_string())?;
let contract_address: CanonicalAddr = deps.api.addr_canonicalize(&info.sender.as_str())?;
let contract_address: CanonicalAddr = deps.api.addr_canonicalize(info.sender.as_str())?;
wrapped_asset_address(deps.storage).save(contract_address.as_slice(), &asset_id.to_vec())?;
Ok(Response::new()

View File

@ -122,8 +122,7 @@ pub struct TokenBridgeMessage {
}
impl TokenBridgeMessage {
pub fn deserialize(data: &Vec<u8>) -> StdResult<Self> {
let data = data.as_slice();
pub fn deserialize(data: &[u8]) -> StdResult<Self> {
let action = data.get_u8(0);
let payload = &data[1..];
@ -166,6 +165,11 @@ impl<T, const N: usize> BoundedVec<T, N> {
pub fn len(&self) -> usize {
self.vec.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.vec.is_empty()
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
@ -181,8 +185,7 @@ pub struct TransferInfo {
}
impl TransferInfo {
pub fn deserialize(data: &Vec<u8>) -> StdResult<Self> {
let data = data.as_slice();
pub fn deserialize(data: &[u8]) -> StdResult<Self> {
let mut offset: usize = 0; // offset into data in bytes
let nft_address = data.get_const_bytes::<32>(offset);
offset += 32;
@ -250,16 +253,14 @@ pub struct RegisterChain {
}
impl UpgradeContract {
pub fn deserialize(data: &Vec<u8>) -> StdResult<Self> {
let data = data.as_slice();
pub fn deserialize(data: &[u8]) -> StdResult<Self> {
let new_contract = data.get_u64(24);
Ok(UpgradeContract { new_contract })
}
}
impl RegisterChain {
pub fn deserialize(data: &Vec<u8>) -> StdResult<Self> {
let data = data.as_slice();
pub fn deserialize(data: &[u8]) -> StdResult<Self> {
let chain_id = data.get_u16(0);
let chain_address = data[2..].to_vec();

View File

@ -6,8 +6,8 @@ use cosmwasm_std::{
};
use sha3::{
Digest,
Keccak256,
digest::{consts::U32, generic_array::GenericArray},
Digest, Keccak256,
};
use wormhole::byte_utils::ByteUtils;
@ -66,10 +66,10 @@ pub fn from_external_token_id(
}
}
fn hash(token_id: &String) -> Vec<u8> {
fn hash(token_id: &str) -> GenericArray<u8, U32> {
let mut hasher = Keccak256::new();
hasher.update(token_id);
hasher.finalize().to_vec()
hasher.finalize()
}
pub fn to_external_token_id(

View File

@ -91,7 +91,7 @@ pub fn extend_string_to_32(s: &str) -> Vec<u8> {
string_to_array::<32>(s).to_vec()
}
pub fn get_string_from_32(v: &Vec<u8>) -> String {
pub fn get_string_from_32(v: &[u8]) -> String {
let s = String::from_utf8_lossy(v);
s.chars().filter(|c| c != &'\0').collect()
}

View File

@ -1,5 +1,4 @@
use cosmwasm_std::{
entry_point,
has_coins,
to_binary,
BankMsg,
@ -17,6 +16,9 @@ use cosmwasm_std::{
WasmMsg,
};
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use crate::{
byte_utils::{
extend_address_to_32,
@ -117,7 +119,7 @@ pub fn instantiate(
pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> StdResult<Response> {
match msg {
ExecuteMsg::PostMessage { message, nonce } => {
handle_post_message(deps, env, info, &message.as_slice(), nonce)
handle_post_message(deps, env, info, message.as_slice(), nonce)
}
ExecuteMsg::SubmitVAA { vaa } => handle_submit_vaa(deps, env, info, vaa.as_slice()),
}
@ -147,8 +149,8 @@ fn handle_submit_vaa(
ContractError::InvalidVAAAction.std_err()
}
fn handle_governance_payload(deps: DepsMut, env: Env, data: &Vec<u8>) -> StdResult<Response> {
let gov_packet = GovernancePacket::deserialize(&data)?;
fn handle_governance_payload(deps: DepsMut, env: Env, data: &[u8]) -> StdResult<Response> {
let gov_packet = GovernancePacket::deserialize(data)?;
let module = String::from_utf8(gov_packet.module).unwrap();
let module: String = module.chars().filter(|c| c != &'\0').collect();
@ -243,7 +245,7 @@ fn parse_and_verify_vaa(
Ok(vaa)
}
fn vaa_update_guardian_set(deps: DepsMut, env: Env, data: &Vec<u8>) -> StdResult<Response> {
fn vaa_update_guardian_set(deps: DepsMut, env: Env, data: &[u8]) -> StdResult<Response> {
/* Payload format
0 uint32 new_index
4 uint8 len(keys)
@ -255,7 +257,7 @@ fn vaa_update_guardian_set(deps: DepsMut, env: Env, data: &Vec<u8>) -> StdResult
let GuardianSetUpgrade {
new_guardian_set_index,
new_guardian_set,
} = GuardianSetUpgrade::deserialize(&data)?;
} = GuardianSetUpgrade::deserialize(data)?;
if new_guardian_set_index != state.guardian_set_index + 1 {
return ContractError::GuardianSetIndexIncreaseError.std_err();
@ -279,12 +281,12 @@ fn vaa_update_guardian_set(deps: DepsMut, env: Env, data: &Vec<u8>) -> StdResult
.add_attribute("new", state.guardian_set_index.to_string()))
}
fn vaa_update_contract(_deps: DepsMut, env: Env, data: &Vec<u8>) -> StdResult<Response> {
fn vaa_update_contract(_deps: DepsMut, env: Env, data: &[u8]) -> StdResult<Response> {
/* Payload format
0 [][32]uint8 new_contract
*/
let ContractUpgrade { new_contract } = ContractUpgrade::deserialize(&data)?;
let ContractUpgrade { new_contract } = ContractUpgrade::deserialize(data)?;
Ok(Response::new()
.add_message(CosmosMsg::Wasm(WasmMsg::Migrate {
@ -295,8 +297,8 @@ fn vaa_update_contract(_deps: DepsMut, env: Env, data: &Vec<u8>) -> StdResult<Re
.add_attribute("action", "contract_upgrade"))
}
pub fn handle_set_fee(deps: DepsMut, _env: Env, data: &Vec<u8>) -> StdResult<Response> {
let set_fee_msg = SetFee::deserialize(&data)?;
pub fn handle_set_fee(deps: DepsMut, _env: Env, data: &[u8]) -> StdResult<Response> {
let set_fee_msg = SetFee::deserialize(data)?;
// Save new fees
let mut state = config_read(deps.storage).load()?;
@ -305,12 +307,12 @@ pub fn handle_set_fee(deps: DepsMut, _env: Env, data: &Vec<u8>) -> StdResult<Res
Ok(Response::new()
.add_attribute("action", "fee_change")
.add_attribute("new_fee.amount", state.fee.amount.to_string())
.add_attribute("new_fee.denom", state.fee.denom.to_string()))
.add_attribute("new_fee.amount", state.fee.amount)
.add_attribute("new_fee.denom", state.fee.denom))
}
pub fn handle_transfer_fee(deps: DepsMut, _env: Env, data: &Vec<u8>) -> StdResult<Response> {
let transfer_msg = TransferFee::deserialize(&data)?;
pub fn handle_transfer_fee(deps: DepsMut, _env: Env, data: &[u8]) -> StdResult<Response> {
let transfer_msg = TransferFee::deserialize(data)?;
Ok(Response::new().add_message(CosmosMsg::Bank(BankMsg::Send {
to_address: deps.api.addr_humanize(&transfer_msg.recipient)?.to_string(),
@ -333,7 +335,7 @@ fn handle_post_message(
return ContractError::FeeTooLow.std_err();
}
let emitter = extend_address_to_32(&deps.api.addr_canonicalize(&info.sender.as_str())?);
let emitter = extend_address_to_32(&deps.api.addr_canonicalize(info.sender.as_str())?);
let sequence = sequence_read(deps.storage, emitter.as_slice());
sequence_set(deps.storage, emitter.as_slice(), sequence + 1)?;
@ -352,7 +354,7 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
QueryMsg::GuardianSetInfo {} => to_binary(&query_guardian_set_info(deps)?),
QueryMsg::VerifyVAA { vaa, block_time } => to_binary(&query_parse_and_verify_vaa(
deps,
&vaa.as_slice(),
vaa.as_slice(),
block_time,
)?),
QueryMsg::GetState {} => to_binary(&query_state(deps)?),
@ -381,7 +383,7 @@ pub fn query_parse_and_verify_vaa(
// returns the hex of the 32 byte address we use for some address on this chain
pub fn query_address_hex(deps: Deps, address: &HumanAddr) -> StdResult<GetAddressHexResponse> {
Ok(GetAddressHexResponse {
hex: hex::encode(extend_address_to_32(&deps.api.addr_canonicalize(&address)?)),
hex: hex::encode(extend_address_to_32(&deps.api.addr_canonicalize(address)?)),
})
}
@ -394,12 +396,11 @@ pub fn query_state(deps: Deps) -> StdResult<GetStateResponse> {
fn keys_equal(a: &VerifyingKey, b: &GuardianAddress) -> bool {
let mut hasher = Keccak256::new();
let point: EncodedPoint = EncodedPoint::from(a);
let point = point.decompress();
if bool::from(point.is_none()) {
let point = if let Some(p) = EncodedPoint::from(a).decompress() {
p
} else {
return false;
}
let point = point.unwrap();
};
hasher.update(&point.as_bytes()[1..]);
let a = &hasher.finalize()[12..];

View File

@ -203,7 +203,7 @@ pub struct GuardianSetInfo {
impl GuardianSetInfo {
pub fn quorum(&self) -> usize {
// allow quorum of 0 for testing purposes...
if self.addresses.len() == 0 {
if self.addresses.is_empty() {
return 0;
}
((self.addresses.len() * 10 / 3) * 2) / 10 + 1
@ -243,7 +243,7 @@ pub fn sequence_set(storage: &mut dyn Storage, emitter: &[u8], sequence: u64) ->
pub fn sequence_read(storage: &dyn Storage, emitter: &[u8]) -> u64 {
bucket_read(storage, SEQUENCE_KEY)
.load(&emitter)
.load(emitter)
.or::<u64>(Ok(0))
.unwrap()
}
@ -254,7 +254,7 @@ pub fn vaa_archive_add(storage: &mut dyn Storage, hash: &[u8]) -> StdResult<()>
pub fn vaa_archive_check(storage: &dyn Storage, hash: &[u8]) -> bool {
bucket_read(storage, GUARDIAN_SET_KEY)
.load(&hash)
.load(hash)
.or::<bool>(Ok(false))
.unwrap()
}
@ -283,8 +283,7 @@ pub struct GovernancePacket {
}
impl GovernancePacket {
pub fn deserialize(data: &Vec<u8>) -> StdResult<Self> {
let data = data.as_slice();
pub fn deserialize(data: &[u8]) -> StdResult<Self> {
let module = data.get_bytes32(0).to_vec();
let action = data.get_u8(32);
let chain = data.get_u16(33);
@ -311,8 +310,7 @@ pub struct GuardianSetUpgrade {
}
impl ContractUpgrade {
pub fn deserialize(data: &Vec<u8>) -> StdResult<Self> {
let data = data.as_slice();
pub fn deserialize(data: &[u8]) -> StdResult<Self> {
let new_contract = data.get_u64(24);
Ok(ContractUpgrade {
new_contract,
@ -321,10 +319,9 @@ impl ContractUpgrade {
}
impl GuardianSetUpgrade {
pub fn deserialize(data: &Vec<u8>) -> StdResult<Self> {
pub fn deserialize(data: &[u8]) -> StdResult<Self> {
const ADDRESS_LEN: usize = 20;
let data = data.as_slice();
let new_guardian_set_index = data.get_u32(0);
let n_guardians = data.get_u8(4);
@ -347,10 +344,10 @@ impl GuardianSetUpgrade {
expiration_time: 0,
};
return Ok(GuardianSetUpgrade {
Ok(GuardianSetUpgrade {
new_guardian_set_index,
new_guardian_set,
});
})
}
}
@ -360,9 +357,7 @@ pub struct SetFee {
}
impl SetFee {
pub fn deserialize(data: &Vec<u8>) -> StdResult<Self> {
let data = data.as_slice();
pub fn deserialize(data: &[u8]) -> StdResult<Self> {
let (_, amount) = data.get_u256(0);
let fee = Coin {
denom: String::from(FEE_DENOMINATION),
@ -379,8 +374,7 @@ pub struct TransferFee {
}
impl TransferFee {
pub fn deserialize(data: &Vec<u8>) -> StdResult<Self> {
let data = data.as_slice();
pub fn deserialize(data: &[u8]) -> StdResult<Self> {
let recipient = data.get_address(0);
let (_, amount) = data.get_u256(32);