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

feat: enhance stargate test function #153

Merged
merged 6 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions crates/e2e-move-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ once_cell = { workspace = true }
sha3 = { workspace = true }
bytes = { workspace = true }
bigdecimal = { workspace = true }
bech32 = { workspace = true }

initia-move-types = { workspace = true }
initia-move-vm = { workspace = true }
Expand Down
202 changes: 110 additions & 92 deletions crates/e2e-move-tests/src/tests/cosmos.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use core::str;

use crate::tests::common::ExpectedOutput;
use crate::MoveHarness;
use initia_move_types::cosmos::{
CosmosCoin, CosmosMessage, DistributionMessage, IBCFee, IBCHeight, IBCMessage, MoveMessage,
StakingMessage, StargateCallback, StargateMessage,
};
use initia_move_types::cosmos::{CosmosCallback, CosmosMessage};
use move_core_types::account_address::AccountAddress;
use move_core_types::language_storage::TypeTag;
use move_core_types::vm_status::VMStatus;

use bech32::{Bech32, Hrp};
use sha3::{Digest, Sha3_256};

const STAKING_SYMBOL: &[u8] = b"ustake";
Expand Down Expand Up @@ -104,6 +105,13 @@ fn test_cosmos_delegate() {
);
tests.push(test_initialize_coin);

let staking_denom = str::from_utf8(STAKING_SYMBOL).unwrap();
let delegator_cosmos_addr = bech32::encode::<Bech32>(
Hrp::parse_unchecked("init"),
&delegator_address.into_bytes(),
)
.unwrap();
let expected_data = format!("{{\"@type\":\"/initia.mstaking.v1.MsgDelegate\",\"amount\":[{{\"amount\":\"{amount}\",\"denom\":\"{staking_denom}\"}}],\"delegator_address\":\"{delegator_cosmos_addr}\",\"validator_address\":\"{validator_address}\"}}");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider using serde for JSON formatting.

Manual JSON string formatting with format! is error-prone and harder to maintain. Using serde would provide type safety and better maintainability.

Example implementation:

use serde::Serialize;

#[derive(Serialize)]
struct DelegateMessage {
    #[serde(rename = "@type")]
    type_url: String,
    amount: Vec<CoinAmount>,
    delegator_address: String,
    validator_address: String,
}

#[derive(Serialize)]
struct CoinAmount {
    amount: String,
    denom: String,
}

// Usage
let msg = DelegateMessage {
    type_url: "/initia.mstaking.v1.MsgDelegate".to_string(),
    amount: vec![CoinAmount {
        amount: amount.to_string(),
        denom: staking_denom.to_string(),
    }],
    delegator_address: delegator_cosmos_addr,
    validator_address: validator_address,
};
let expected_data = serde_json::to_string(&msg).unwrap();

Also applies to: 168-168, 225-225, 297-298, 397-397, 446-447, 490-490, 535-535, 576-577

Comment on lines +108 to +114
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Refactor repeated Bech32 encoding and JSON formatting patterns.

The code shows significant duplication in two areas:

  1. Bech32 address encoding with the "init" prefix
  2. Manual JSON string formatting with format!

Consider these improvements:

  1. Add a helper function for Bech32 encoding:
fn encode_init_address(address: AccountAddress) -> String {
    bech32::encode::<Bech32>(
        Hrp::parse_unchecked("init"),
        &address.into_bytes(),
    )
    .unwrap()
}
  1. Use serde for type-safe JSON formatting:
use serde::Serialize;

#[derive(Serialize)]
struct DelegateMessage {
    #[serde(rename = "@type")]
    type_url: String,
    amount: Vec<CoinAmount>,
    delegator_address: String,
    validator_address: String,
}

#[derive(Serialize)]
struct CoinAmount {
    amount: String,
    denom: String,
}

These changes would:

  • Reduce code duplication
  • Improve maintainability
  • Provide compile-time type safety for JSON structures
  • Make the code more resistant to formatting errors

Also applies to: 164-168, 222-225, 294-298, 392-397, 442-447, 489-492, 532-537, 575-578

let test_delegate = (
delegator_address,
"0x1::cosmos::delegate",
Expand All @@ -117,11 +125,12 @@ fn test_cosmos_delegate() {
VMStatus::Executed,
None,
None,
Some(vec![CosmosMessage::Staking(StakingMessage::Delegate {
delegator_address,
validator_address,
amount: CosmosCoin { amount, metadata },
})]),
Some(vec![CosmosMessage {
sender: delegator_address,
data: expected_data.into_bytes(),
allow_failure: false,
callback: None,
}]),
),
);
tests.push(test_delegate);
Expand Down Expand Up @@ -152,6 +161,12 @@ fn test_cosmos_fund_community_pool() {
);
tests.push(test_initialize_coin);

let denom = str::from_utf8(STAKING_SYMBOL).unwrap();
let depositor_cosmos_addr =
bech32::encode::<Bech32>(Hrp::parse_unchecked("init"), &sender_address.into_bytes())
.unwrap();
let expected_data = format!("{{\"@type\":\"/cosmos.distribution.v1beta1.MsgFundCommunityPool\",\"amount\":[{{\"amount\":\"{amount}\",\"denom\":\"{denom}\"}}],\"depositor\":\"{depositor_cosmos_addr}\"}}");

let test_fund_community_pool = (
sender_address,
"0x1::cosmos::fund_community_pool",
Expand All @@ -161,12 +176,12 @@ fn test_cosmos_fund_community_pool() {
VMStatus::Executed,
None,
None,
Some(vec![CosmosMessage::Distribution(
DistributionMessage::FundCommunityPool {
sender_address,
amount: CosmosCoin { amount, metadata },
},
)]),
Some(vec![CosmosMessage {
sender: sender_address,
data: expected_data.into_bytes(),
allow_failure: false,
callback: None,
}]),
),
);
tests.push(test_fund_community_pool);
Expand Down Expand Up @@ -204,6 +219,11 @@ fn test_cosmos_transfer() {
);
tests.push(test_initialize_coin);

let denom = str::from_utf8(STAKING_SYMBOL).unwrap();
let sender_cosmos_addr =
bech32::encode::<Bech32>(Hrp::parse_unchecked("init"), &sender.into_bytes()).unwrap();
let expected_data = format!("{{\"@type\":\"/ibc.applications.transfer.v1.MsgTransfer\",\"memo\":\"{memo}\",\"receiver\":\"{receiver}\",\"sender\":\"{sender_cosmos_addr}\",\"source_channel\":\"{source_channel}\",\"source_port\":\"{source_port}\",\"timeout_height\":{{\"revision_height\":\"{revision_height}\",\"revision_number\":\"{revision_number}\"}},\"timeout_timestamp\":\"{timeout_timestamp}\",\"token\":{{\"amount\":\"{amount}\",\"denom\":\"{denom}\"}}}}");

let test_transfer = (
sender,
"0x1::cosmos::transfer",
Expand All @@ -223,19 +243,12 @@ fn test_cosmos_transfer() {
VMStatus::Executed,
None,
None,
Some(vec![CosmosMessage::IBC(IBCMessage::Transfer {
source_port,
source_channel,
token: CosmosCoin { amount, metadata },
Some(vec![CosmosMessage {
sender,
receiver,
timeout_height: IBCHeight {
revision_height,
revision_number,
},
timeout_timestamp,
memo,
})]),
data: expected_data.into_bytes(),
allow_failure: false,
callback: None,
}]),
),
);
tests.push(test_transfer);
Expand Down Expand Up @@ -278,6 +291,11 @@ fn test_cosmos_nft_transfer() {
);
tests.push(test_create_collection);

let class_id = str::from_utf8(COLLECTION_NAME).unwrap();
let sender_cosmos_addr =
bech32::encode::<Bech32>(Hrp::parse_unchecked("init"), &sender.into_bytes()).unwrap();
let expected_data = format!("{{\"@type\":\"/ibc.applications.nft_transfer.v1.MsgTransfer\",\"class_id\":\"{class_id}\",\"memo\":\"{memo}\",\"receiver\":\"{receiver}\",\"sender\":\"{sender_cosmos_addr}\",\"source_channel\":\"{source_channel}\",\"source_port\":\"{source_port}\",\"timeout_height\":{{\"revision_height\":\"{revision_height}\",\"revision_number\":\"{revision_number}\"}},\"timeout_timestamp\":\"{timeout_timestamp}\",\"token_ids\":[\"id1\",\"id2\"]}}");

let test_nft_transfer = (
sender,
"0x1::cosmos::nft_transfer",
Expand All @@ -297,20 +315,12 @@ fn test_cosmos_nft_transfer() {
VMStatus::Executed,
None,
None,
Some(vec![CosmosMessage::IBC(IBCMessage::NFTTransfer {
source_port,
source_channel,
collection,
token_ids,
Some(vec![CosmosMessage {
sender,
receiver,
timeout_height: IBCHeight {
revision_height,
revision_number,
},
timeout_timestamp,
memo,
})]),
data: expected_data.into_bytes(),
allow_failure: false,
callback: None,
}]),
),
);
tests.push(test_nft_transfer);
Expand Down Expand Up @@ -379,6 +389,13 @@ fn test_cosmos_pay_fee() {
);
tests.push(test_initialize_coin);

let recv_fee_denom = str::from_utf8(STAKING_SYMBOL).unwrap();
let ack_fee_denom = str::from_utf8(FEE_A_SYMBOL).unwrap();
let timeout_fee_denom = str::from_utf8(FEE_B_SYMBOL).unwrap();
let sender_cosmos_addr =
bech32::encode::<Bech32>(Hrp::parse_unchecked("init"), &sender.into_bytes()).unwrap();
let expected_data = format!("{{\"@type\":\"/ibc.applications.fee.v1.MsgPayPacketFee\",\"fee\":{{\"ack_fee\":[{{\"amount\":\"{ack_fee_amount}\",\"denom\":\"{ack_fee_denom}\"}}],\"recv_fee\":[{{\"amount\":\"{recv_fee_amount}\",\"denom\":\"{recv_fee_denom}\"}}],\"timeout_fee\":[{{\"amount\":\"{timeout_fee_amount}\",\"denom\":\"{timeout_fee_denom}\"}}]}},\"relayers\":[],\"signer\":\"{sender_cosmos_addr}\",\"source_channel\":\"{source_channel}\",\"source_port\":\"{source_port}\"}}");

let test_pay_fee = (
sender,
"0x1::cosmos::pay_fee",
Expand All @@ -397,25 +414,12 @@ fn test_cosmos_pay_fee() {
VMStatus::Executed,
None,
None,
Some(vec![CosmosMessage::IBC(IBCMessage::PayFee {
signer: sender,
source_port,
source_channel,
fee: IBCFee {
recv_fee: CosmosCoin {
metadata: recv_fee_metadata,
amount: recv_fee_amount,
},
ack_fee: CosmosCoin {
metadata: ack_fee_metadata,
amount: ack_fee_amount,
},
timeout_fee: CosmosCoin {
metadata: timeout_fee_metadata,
amount: timeout_fee_amount,
},
},
})]),
Some(vec![CosmosMessage {
sender,
data: expected_data.into_bytes(),
allow_failure: false,
callback: None,
}]),
),
);
tests.push(test_pay_fee);
Expand All @@ -435,6 +439,12 @@ fn test_cosmos_move_execute() {
let arg1 = vec![1, 2, 3];
let arg2 = vec![4, 5, 6];

let arg1_hex = hex::encode(arg1.clone());
let arg2_hex = hex::encode(arg2.clone());
let sender_cosmos_addr =
bech32::encode::<Bech32>(Hrp::parse_unchecked("init"), &sender.into_bytes()).unwrap();
let expected_data = format!("{{\"@type\":\"/initia.move.v1.MsgExecute\",\"args\":[\"{arg1_hex}\",\"{arg2_hex}\"],\"function_name\":\"{function_name}\",\"module_address\":\"{module_address}\",\"module_name\":\"{module_name}\",\"sender\":\"{sender_cosmos_addr}\",\"type_args\":[\"{type_arg1}\",\"{type_arg2}\"]}}");

let test_move_execute = (
sender,
"0x1::cosmos::move_execute",
Expand All @@ -450,15 +460,12 @@ fn test_cosmos_move_execute() {
VMStatus::Executed,
None,
None,
Some(vec![CosmosMessage::Move(MoveMessage::Execute {
Some(vec![CosmosMessage {
sender,
module_address,
module_name,
function_name,
type_args: vec![type_arg1, type_arg2],
args: vec![arg1, arg2],
is_json: false,
})]),
data: expected_data.into_bytes(),
allow_failure: false,
callback: None,
}]),
),
);
tests.push(test_move_execute);
Expand All @@ -478,6 +485,10 @@ fn test_cosmos_move_execute_with_json() {
let arg1 = b"\"hello\"".to_vec();
let arg2 = b"\"world\"".to_vec();

let sender_cosmos_addr =
bech32::encode::<Bech32>(Hrp::parse_unchecked("init"), &sender.into_bytes()).unwrap();
let expected_data = format!("{{\"@type\":\"/initia.move.v1.MsgExecuteJSON\",\"args\":[\"\\\"hello\\\"\",\"\\\"world\\\"\"],\"function_name\":\"{function_name}\",\"module_address\":\"{module_address}\",\"module_name\":\"{module_name}\",\"sender\":\"{sender_cosmos_addr}\",\"type_args\":[\"{type_arg1}\",\"{type_arg2}\"]}}");

let test_move_execute = (
sender,
"0x1::cosmos::move_execute_with_json",
Expand All @@ -493,15 +504,12 @@ fn test_cosmos_move_execute_with_json() {
VMStatus::Executed,
None,
None,
Some(vec![CosmosMessage::Move(MoveMessage::Execute {
Some(vec![CosmosMessage {
sender,
module_address,
module_name,
function_name,
type_args: vec![type_arg1, type_arg2],
args: vec![arg1, arg2],
is_json: true,
})]),
data: expected_data.into_bytes(),
allow_failure: false,
callback: None,
}]),
),
);
tests.push(test_move_execute);
Expand All @@ -519,6 +527,13 @@ fn test_cosmos_move_script() {
let arg1 = vec![1, 2, 3];
let arg2 = vec![4, 5, 6];

let code_bytes_hex = hex::encode(code_bytes.clone());
let arg1_hex = hex::encode(arg1.clone());
let arg2_hex = hex::encode(arg2.clone());
let sender_cosmos_addr =
bech32::encode::<Bech32>(Hrp::parse_unchecked("init"), &sender.into_bytes()).unwrap();
let expected_data = format!("{{\"@type\":\"/initia.move.v1.MsgScript\",\"args\":[\"{arg1_hex}\",\"{arg2_hex}\"],\"code_bytes\":\"{code_bytes_hex}\",\"sender\":\"{sender_cosmos_addr}\",\"type_args\":[\"{type_arg1}\",\"{type_arg2}\"]}}");

let test_move_script = (
sender,
"0x1::cosmos::move_script",
Expand All @@ -532,13 +547,12 @@ fn test_cosmos_move_script() {
VMStatus::Executed,
None,
None,
Some(vec![CosmosMessage::Move(MoveMessage::Script {
Some(vec![CosmosMessage {
sender,
code_bytes,
type_args: vec![type_arg1, type_arg2],
args: vec![arg1, arg2],
is_json: false,
})]),
data: expected_data.into_bytes(),
allow_failure: false,
callback: None,
}]),
),
);
tests.push(test_move_script);
Expand All @@ -556,6 +570,11 @@ fn test_cosmos_move_script_with_json() {
let arg1 = b"\"hello\"".to_vec();
let arg2 = b"\"world\"".to_vec();

let code_bytes_hex = hex::encode(code_bytes.clone());
let sender_cosmos_addr =
bech32::encode::<Bech32>(Hrp::parse_unchecked("init"), &sender.into_bytes()).unwrap();
let expected_data = format!("{{\"@type\":\"/initia.move.v1.MsgScriptJSON\",\"args\":[\"\\\"hello\\\"\",\"\\\"world\\\"\"],\"code_bytes\":\"{code_bytes_hex}\",\"sender\":\"{sender_cosmos_addr}\",\"type_args\":[\"{type_arg1}\",\"{type_arg2}\"]}}");

let test_move_script = (
sender,
"0x1::cosmos::move_script_with_json",
Expand All @@ -569,13 +588,12 @@ fn test_cosmos_move_script_with_json() {
VMStatus::Executed,
None,
None,
Some(vec![CosmosMessage::Move(MoveMessage::Script {
Some(vec![CosmosMessage {
sender,
code_bytes,
type_args: vec![type_arg1, type_arg2],
args: vec![arg1, arg2],
is_json: true,
})]),
data: expected_data.into_bytes(),
allow_failure: false,
callback: None,
}]),
),
);
tests.push(test_move_script);
Expand All @@ -598,12 +616,12 @@ fn test_cosmos_stargate() {
VMStatus::Executed,
None,
None,
Some(vec![CosmosMessage::Stargate(StargateMessage {
Some(vec![CosmosMessage {
sender,
data: data.as_bytes().to_vec(),
allow_failure: false,
callback: None,
})]),
}]),
),
);
tests.push(test_stargate);
Expand All @@ -622,17 +640,17 @@ fn test_cosmos_stargate() {
VMStatus::Executed,
None,
None,
Some(vec![CosmosMessage::Stargate(StargateMessage {
Some(vec![CosmosMessage {
sender,
data: data.as_bytes().to_vec(),
allow_failure: false,
callback: Some(StargateCallback {
callback: Some(CosmosCallback {
id: 123,
module_address: AccountAddress::from_hex_literal("0xcafe").unwrap(),
module_name: "test".to_string(),
function_name: "callback".to_string(),
}),
})]),
}]),
),
);
tests.push(test_stargate);
Expand Down
Loading
Loading