Skip to content

Commit

Permalink
Add integration tests(2) (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
duguorong009 authored May 27, 2022
1 parent 197c16e commit e4fddf6
Show file tree
Hide file tree
Showing 14 changed files with 482 additions and 40 deletions.
7 changes: 6 additions & 1 deletion contracts/anchor/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,12 @@ fn wrap_and_deposit_cw20(
let anchor = ANCHOR.load(deps.storage)?;
let tokenwrapper = anchor.tokenwrapper_addr.as_str();

// Validations
// Only non-"TokenWrapper" Cw20 token contract can execute this message.
if anchor.tokenwrapper_addr == deps.api.addr_validate(recv_token_addr.as_str())? {
return Err(ContractError::Unauthorized {});
}

// Check if the "recv_token_amt" == "ext_amt" + "wrapping_fee"
let amt_to_wrap_query: GetAmountToWrapResponse = deps.querier.query_wasm_smart(
tokenwrapper.to_string(),
&TokenWrapperQueryMsg::GetAmountToWrap {
Expand Down
Binary file modified contracts/anchor/tests/cosmwasm_anchor.wasm
Binary file not shown.
6 changes: 2 additions & 4 deletions contracts/signature-bridge/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,8 @@ fn admin_set_resource_with_signature(
}));
}

if msg.nonce != state.proposal_nonce + 1 {
return Err(ContractError::Std(StdError::GenericErr {
msg: "Invalid nonce".to_string(),
}));
if msg.nonce != state.proposal_nonce + 1048 {
return Err(ContractError::InvalidNonce);
}

let func_sig = Keccak256::hash(
Expand Down
12 changes: 4 additions & 8 deletions contracts/tokenwrapper/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,10 +477,8 @@ fn add_token_addr(
}

// Validate the "nonce" value
if nonce != config.proposal_nonce + 1 {
return Err(ContractError::Std(StdError::GenericErr {
msg: "Nonce must increment by 1".to_string(),
}));
if nonce <= config.proposal_nonce || config.proposal_nonce + 1048 < nonce {
return Err(ContractError::InvalidNonce);
}

// Add the "token" to wrapping list
Expand Down Expand Up @@ -521,10 +519,8 @@ fn remove_token_addr(
}

// Validate the "nonce" value
if nonce != config.proposal_nonce + 1 {
return Err(ContractError::Std(StdError::GenericErr {
msg: "Nonce must increment by 1".to_string(),
}));
if nonce <= config.proposal_nonce || config.proposal_nonce + 1048 < nonce {
return Err(ContractError::InvalidNonce);
}

// Remove the "token" from wrapping list
Expand Down
5 changes: 3 additions & 2 deletions contracts/tokenwrapper/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,14 +354,15 @@ fn test_add_token_addr() {
let info = mock_info("creator", &[]);
let add_token_msg = ExecuteMsg::AddCw20TokenAddr {
token: "new_cw20_token".to_string(),
nonce: 2,
nonce: 1049,
};

// Failure since the invalid nonce value
let err = execute(deps.as_mut(), mock_env(), info, add_token_msg).unwrap_err();
assert_eq!(
err.to_string(),
"Generic error: Nonce must increment by 1".to_string()
"Nonce must be greater than current nonce. Nonce must not increment more than 1048"
.to_string()
);

// Success
Expand Down
Binary file modified contracts/tokenwrapper/tests/cosmwasm_tokenwrapper.wasm
Binary file not shown.
55 changes: 39 additions & 16 deletions contracts/vanchor/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ use protocol_cosmwasm::structs::{
};
use protocol_cosmwasm::token_wrapper::{
ConfigResponse as TokenWrapperConfigResp, Cw20HookMsg as TokenWrapperHookMsg,
ExecuteMsg as TokenWrapperExecuteMsg, QueryMsg as TokenWrapperQueryMsg,
ExecuteMsg as TokenWrapperExecuteMsg, GetAmountToWrapResponse,
QueryMsg as TokenWrapperQueryMsg,
};
use protocol_cosmwasm::utils::{compute_chain_id_type, element_encoder};
use protocol_cosmwasm::utils::{compute_chain_id_type, element_encoder, parse_string_to_uint128};
use protocol_cosmwasm::vanchor::{
ConfigResponse, Cw20HookMsg, ExecuteMsg, ExtData, InstantiateMsg, MigrateMsg, ProofData,
QueryMsg, UpdateConfigMsg,
Expand Down Expand Up @@ -378,6 +379,10 @@ fn transact_deposit_wrap_native(
proof_data: ProofData,
ext_data: ExtData,
) -> Result<Response, ContractError> {
let ext_data_fee: u128 = ext_data.fee.u128();
let ext_amt: i128 = ext_data.ext_amount.parse().expect("Invalid ext_amount");
let abs_ext_amt = ext_amt.unsigned_abs();

let vanchor: VAnchor = VANCHOR.load(deps.storage)?;

// Validations
Expand All @@ -392,11 +397,21 @@ fn transact_deposit_wrap_native(
None => return Err(ContractError::InsufficientFunds {}),
};

validate_proof(deps.branch(), proof_data.clone(), ext_data.clone())?;
// Check if the "recv_token_amt" == "ext_amt" + "wrapping_fee"
let amt_to_wrap_query: GetAmountToWrapResponse = deps.querier.query_wasm_smart(
vanchor.tokenwrapper_addr.to_string(),
&TokenWrapperQueryMsg::GetAmountToWrap {
target_amount: abs_ext_amt.to_string(),
},
)?;
let amt_to_wrap = parse_string_to_uint128(amt_to_wrap_query.amount_to_wrap)?;

let ext_data_fee: u128 = ext_data.fee.u128();
let ext_amt: i128 = ext_data.ext_amount.parse().expect("Invalid ext_amount");
let abs_ext_amt = ext_amt.unsigned_abs();
if recv_token_amt != amt_to_wrap {
return Err(ContractError::InsufficientFunds {});
}

// Validate the "proof_data" & "ext_data"
validate_proof(deps.branch(), proof_data.clone(), ext_data.clone())?;

// Deposit
let mut msgs: Vec<CosmosMsg> = vec![];
Expand All @@ -408,9 +423,6 @@ fn transact_deposit_wrap_native(
if Uint128::from(abs_ext_amt) > vanchor.max_deposit_amt {
return Err(ContractError::InvalidDepositAmount);
};
if abs_ext_amt != recv_token_amt.u128() {
return Err(ContractError::InsufficientFunds {});
};
msgs.push(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: vanchor.tokenwrapper_addr.to_string(),
funds: info.funds,
Expand Down Expand Up @@ -452,17 +464,31 @@ fn transact_deposit_wrap_cw20(
recv_token_addr: String,
recv_token_amt: Uint128,
) -> Result<Response, ContractError> {
let ext_data_fee: u128 = ext_data.fee.u128();
let ext_amt: i128 = ext_data.ext_amount.parse().expect("Invalid ext_amount");
let abs_ext_amt = ext_amt.unsigned_abs();

// Only non-"TokenWrapper" Cw20 token contract can execute this message.
let vanchor: VAnchor = VANCHOR.load(deps.storage)?;
if vanchor.tokenwrapper_addr == deps.api.addr_validate(recv_token_addr.as_str())? {
return Err(ContractError::Unauthorized {});
}

validate_proof(deps.branch(), proof_data.clone(), ext_data.clone())?;
// Check if the "recv_token_amt" == "ext_amt" + "wrapping_fee"
let amt_to_wrap_query: GetAmountToWrapResponse = deps.querier.query_wasm_smart(
vanchor.tokenwrapper_addr.to_string(),
&TokenWrapperQueryMsg::GetAmountToWrap {
target_amount: abs_ext_amt.to_string(),
},
)?;
let amt_to_wrap = parse_string_to_uint128(amt_to_wrap_query.amount_to_wrap)?;

let ext_data_fee: u128 = ext_data.fee.u128();
let ext_amt: i128 = ext_data.ext_amount.parse().expect("Invalid ext_amount");
let abs_ext_amt = ext_amt.unsigned_abs();
if recv_token_amt != amt_to_wrap {
return Err(ContractError::InsufficientFunds {});
}

// Validate the "proof_data" & "ext_data"
validate_proof(deps.branch(), proof_data.clone(), ext_data.clone())?;

// Deposit
let mut msgs: Vec<CosmosMsg> = vec![];
Expand All @@ -473,9 +499,6 @@ fn transact_deposit_wrap_cw20(
if Uint128::from(abs_ext_amt) > vanchor.max_deposit_amt {
return Err(ContractError::InvalidDepositAmount);
};
if abs_ext_amt != recv_token_amt.u128() {
return Err(ContractError::InsufficientFunds {});
};
msgs.push(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: recv_token_addr,
funds: vec![],
Expand Down
10 changes: 7 additions & 3 deletions contracts/vanchor/src/mock_querier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ use std::marker::PhantomData;
use cosmwasm_std::testing::{MockApi, MockQuerier, MockStorage, MOCK_CONTRACT_ADDR};
use cosmwasm_std::{
from_binary, from_slice, to_binary, Coin, ContractResult, Empty, OwnedDeps, Querier,
QuerierResult, QueryRequest, SystemError, SystemResult, WasmQuery,
QuerierResult, QueryRequest, SystemError, SystemResult, Uint128, WasmQuery,
};
use protocol_cosmwasm::utils::parse_string_to_uint128;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -81,10 +82,13 @@ impl WasmMockQuerier {
.unwrap(),
)),
QueryMsg::GetAmountToWrap { target_amount } => {
let targ_amt = parse_string_to_uint128(target_amount).unwrap();
// Assumes that the "fee_percentage" is 10%
let amt_to_wrap = targ_amt.multiply_ratio(100_u128, 90_u128);
SystemResult::Ok(ContractResult::Ok(
to_binary(&GetAmountToWrapResponse {
target_amount,
amount_to_wrap: "1000000".to_string(),
target_amount: targ_amt.to_string(),
amount_to_wrap: amt_to_wrap.to_string(),
})
.unwrap(),
))
Expand Down
14 changes: 10 additions & 4 deletions contracts/vanchor/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ const MAX_EXT_AMT: u128 = 200;
const MAX_FEE: u128 = 100;

const CW20_ADDRESS: &str = "terra1340t6lqq6jxhm8d6gtz0hzz5jzcszvm27urkn2";
const TRANSACTOR: &str = "terra1kejftqzx05y9rv00lw5m76csfmx7lf9se02dz4";
const RECIPIENT: &str = "terra1kejftqzx05y9rv00lw5m76csfmx7lf9se02dz4";
const RELAYER: &str = "terra1jrj2vh6cstqwk3pg8nkmdf0r9z0n3q3f3jk5xn";
const TRANSACTOR: &str = "juno1yq0azfkky8aqq4kvzdawrs7tm3rmpl8xs6vcx2";
const RECIPIENT: &str = "juno16e3t7td2wu0wmggnxa3xnyu5whljyed69ptvkp";
const RELAYER: &str = "juno16g2rahf5846rxzp3fwlswy08fz8ccuwk03k57y";
const HANDLER: &str = "terra1fex9f78reuwhfsnc8sun6mz8rl9zwqh03fhwf3";

fn element_encoder(v: &[u8]) -> [u8; 32] {
Expand Down Expand Up @@ -1411,7 +1411,7 @@ fn test_vanchor_wrap_and_deposit_cw20() {
let info = mock_info("any-cw20", &[]);
let deposit_cw20_msg = ExecuteMsg::Receive(Cw20ReceiveMsg {
sender: TRANSACTOR.to_string(),
amount: Uint128::from(10_u128),
amount: Uint128::from(11_u128), // Assume that "fee_percentage" is 10% & wrap_amt is "10"
msg: to_binary(&Cw20HookMsg::TransactDepositWrap {
proof_data: proof_data,
ext_data: ext_data,
Expand Down Expand Up @@ -1497,6 +1497,9 @@ fn test_vanchor_withdraw_and_unwrap_native() {
ext_data_hash.0,
);

println!("proof_data:{:?}\n", proof_data);
println!("ext_data:{:?}", ext_data);

// Should "transact" with success.
let info = mock_info(CW20_ADDRESS, &[]);
let deposit_cw20_msg = ExecuteMsg::Receive(Cw20ReceiveMsg {
Expand Down Expand Up @@ -1570,6 +1573,9 @@ fn test_vanchor_withdraw_and_unwrap_native() {
ext_data_hash.0,
);

println!("proof_data:{:?}\n", proof_data);
println!("ext_data:{:?}", ext_data);

// Should "transact" with success.
let info = mock_info(CW20_ADDRESS, &[]);
let withdraw_cw20_msg = ExecuteMsg::TransactWithdrawUnwrap {
Expand Down
Binary file modified contracts/vanchor/tests/cosmwasm_vanchor.wasm
Binary file not shown.
2 changes: 1 addition & 1 deletion packages/protocol_cosmwasm/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ pub enum ContractError {
#[error("Too many edges")]
TooManyEdges,

#[error("Invalid nonce")]
#[error("Nonce must be greater than current nonce. Nonce must not increment more than 1048")]
InvalidNonce,

/* ------ VAnchor errors ------ */
Expand Down
15 changes: 15 additions & 0 deletions test-scripts/src/processes/tests/testnet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,15 @@ import {
testAnchorUnwrapCw20,
} from './anchor';

import {
testVAnchorInitialize,
testVAnchorDepositWithdraw,
testVAnchorWrapNative,
testVAnchorUnwrapNative,
testVAnchorWrapCw20,
testVAnchorUnwrapCw20,
} from './vanchor';

import {
testMixerInitialize,
testMixerDepositNativeToken,
Expand Down Expand Up @@ -62,6 +71,12 @@ export async function testExecute(
await testAnchorUnwrapCw20(junod, anchor, tokenWrapper, cw20, wallet3, "100");

// VAnchor
await testVAnchorInitialize(junod, vanchor);
await testVAnchorDepositWithdraw(junod, vanchor, cw20, wallet1, wallet2, wallet3, "10", "10", "0", "-7", "-5", "2");
await testVAnchorWrapNative(junod, vanchor, wallet3, "100000");
await testVAnchorUnwrapNative(junod, vanchor, wallet3, "100");
await testVAnchorWrapCw20(junod, vanchor, tokenWrapper, cw20, wallet3, "10000");
await testVAnchorUnwrapCw20(junod, vanchor, tokenWrapper, cw20, wallet3, "100");

// Mixer
await testMixerInitialize(junod, mixer);
Expand Down
2 changes: 1 addition & 1 deletion test-scripts/src/processes/tests/tokenWrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export async function testTokenWrapperInitialize(
expect(result.fee_percentage == (parseInt(localjuno.contractsConsts.feePercentage) / 100).toString()).to.be.ok;
expect(result.is_native_allowed == (localjuno.contractsConsts.isNativeAllowed == 1).toString()).to.be.ok;
expect(result.wrapping_limit == localjuno.contractsConsts.tokenWrapperWrappingLimit).to.be.ok;
expect(result.proposal_nonce == "0").to.be.ok;
expect(result.proposal_nonce == "1").to.be.ok;

console.log(chalk.green(" Passed!"));
}
Expand Down
Loading

0 comments on commit e4fddf6

Please sign in to comment.