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

Fix V2 tests #1378

Merged
merged 3 commits into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions contracts/scripts/DeployLocal.sol
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {Initializer} from "../src/Initializer.sol";
import {SafeNativeTransfer} from "../src/utils/SafeTransfer.sol";
import {stdJson} from "forge-std/StdJson.sol";
import {UD60x18, ud60x18} from "prb/math/src/UD60x18.sol";
import {HelloWorld} from "../test/mocks/HelloWorld.sol";

contract DeployLocal is Script {
using SafeNativeTransfer for address payable;
Expand Down Expand Up @@ -88,6 +89,9 @@ contract DeployLocal is Script {
// Deploy WETH for testing
new WETH9();

// For testing call contract
new HelloWorld();

// Fund the gateway proxy contract. Used to reward relayers
uint256 initialDeposit = vm.envUint("GATEWAY_PROXY_INITIAL_DEPOSIT");
IGatewayV1(address(gateway)).depositEther{value: initialDeposit}();
Expand Down
2 changes: 1 addition & 1 deletion relayer/relays/parachain/parachain-writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ func (relay *Relay) writeToParachain(ctx context.Context, proof scale.ProofPaylo
"Proof": inboundMsg.Proof,
}).Debug("Generated message from Ethereum log")

err := relay.parachainWriter.WriteToParachainAndWatch(ctx, "EthereumOutboundQueueV2.submit_delivery_proof", inboundMsg)
err := relay.parachainWriter.WriteToParachainAndWatch(ctx, "EthereumOutboundQueueV2.submit_delivery_receipt", inboundMsg)
if err != nil {
return fmt.Errorf("submit message to outbound queue v2: %w", err)
}
Expand Down
9 changes: 5 additions & 4 deletions smoketest/Cargo.lock

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

1 change: 1 addition & 0 deletions smoketest/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ edition = "2021"
futures = "0.3.30"
tokio = { version = "1.35.0", features = ["macros", "rt-multi-thread", "time"] }
codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["bit-vec", "derive", "full"] }
scale-info = { features = ["derive"], version = "2.11.6", default-features = false }
hex = "0.4.3"
hex-literal = "0.4.1"
serde = { version = "1.0.197", features = ["derive"] }
Expand Down
2 changes: 1 addition & 1 deletion smoketest/make-bindings.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mkdir -p src/contracts

# Generate Rust bindings for contracts
forge bind --module --overwrite --ethers\
--select 'IGateway|IUpgradable|WETH9|MockGatewayV2|Token' \
--select 'IGateway|IUpgradable|WETH9|MockGatewayV2|Token|HelloWorld' \
--bindings-path src/contracts \
--root ../contracts

Expand Down
25 changes: 23 additions & 2 deletions smoketest/src/asset_hub_helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub fn weth_location() -> Location {
}
}

fn eth_location() -> Location {
pub fn eth_location() -> Location {
Location {
parents: 2,
interior: Junctions::X1([GlobalConsensus(NetworkId::Ethereum {
Expand All @@ -41,7 +41,7 @@ fn eth_location() -> Location {
}
}

fn dot_location() -> Location {
pub fn dot_location() -> Location {
Location { parents: 1, interior: Here }
}

Expand Down Expand Up @@ -142,3 +142,24 @@ pub async fn create_asset_pool(asset_hub_client: &Box<OnlineClient<AssetHubConfi

wait_for_assethub_event::<LiquidityAdded>(asset_hub_client).await;
}

pub async fn mint_token_to(
asset_hub_client: &Box<OnlineClient<AssetHubConfig>>,
token: Location,
who: [u8; 32],
amount: u128,
) {
let foreign_assets_api =
crate::parachains::assethub::api::foreign_assets::calls::TransactionApi;

// Mint eth to sovereign account
let beneficiary = MultiAddress::Id(who.into());
let mut encoded_mint_call = Vec::new();
foreign_assets_api
.mint(token, beneficiary, amount)
.encode_call_data_to(&asset_hub_client.metadata(), &mut encoded_mint_call)
.expect("encoded call");
snowbridge_assethub_call_from_relay_chain(encoded_mint_call)
.await
.expect("fund snowbridge sovereign with eth for pool");
}
14 changes: 9 additions & 5 deletions smoketest/src/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ pub async fn wait_for_bridgehub_event<Ev: StaticEvent>(
.subscribe_finalized()
.await
.expect("block subscription")
.take(5);
.take(500);

let mut substrate_event_found = false;
while let Some(Ok(block)) = blocks.next().await {
Expand Down Expand Up @@ -226,11 +226,12 @@ pub async fn get_balance(
pub async fn fund_account(
client: &Box<Arc<SignerMiddleware<Provider<Http>, LocalWallet>>>,
address_to: Address,
amount: u128,
) -> Result<(), Box<dyn std::error::Error>> {
let tx = TransactionRequest::new()
.to(address_to)
.from(client.address())
.value(U256::from(ethers::utils::parse_ether(1)?));
.value(U256::from(amount));
let tx = client.send_transaction(tx, None).await?.await?;
assert_eq!(tx.clone().unwrap().status.unwrap().as_u64(), 1u64);
println!("receipt: {:#?}", hex::encode(tx.unwrap().transaction_hash));
Expand Down Expand Up @@ -345,7 +346,7 @@ pub async fn snowbridge_assethub_call_from_relay_chain(
RelaychainJunction::Parachain(BRIDGE_HUB_PARA_ID),
)),
RelaychainInstruction::DescendOrigin(RelaychainJunctions::X1(
RelaychainJunction::PalletInstance(84),
RelaychainJunction::PalletInstance(91),
)),
RelaychainInstruction::UniversalOrigin(RelaychainJunction::GlobalConsensus(
RelaychainNetworkId::Ethereum { chain_id: ETHEREUM_CHAIN_ID },
Expand Down Expand Up @@ -564,7 +565,10 @@ pub async fn governance_assethub_call_from_relay_chain_sudo_as(
Ok(())
}

pub async fn fund_agent(agent_id: [u8; 32]) -> Result<(), Box<dyn std::error::Error>> {
pub async fn fund_agent(
agent_id: [u8; 32],
amount: u128,
) -> Result<(), Box<dyn std::error::Error>> {
let test_clients = initial_clients().await.expect("initialize clients");
let gateway_addr: Address = (*GATEWAY_PROXY_CONTRACT).into();
let ethereum_client = *(test_clients.ethereum_client.clone());
Expand All @@ -573,7 +577,7 @@ pub async fn fund_agent(agent_id: [u8; 32]) -> Result<(), Box<dyn std::error::Er

println!("agent address {}", hex::encode(agent_address));

fund_account(&test_clients.ethereum_signed_client, agent_address)
fund_account(&test_clients.ethereum_signed_client, agent_address, amount)
.await
.expect("fund account");
Ok(())
Expand Down
58 changes: 58 additions & 0 deletions smoketest/src/helper_v2.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
use crate::{
constants::*,
contracts::i_gateway_v2 as i_gateway,
helper::{fund_account, initial_clients},
};
use ethers::{
abi::{encode, Token},
prelude::{Address, EthEvent, Middleware, Provider, Ws},
types::{Bytes, H160, U256},
};
use futures::StreamExt;
use std::{ops::Deref, sync::Arc};

pub fn build_native_asset(token: H160, amount: u128) -> Bytes {
let kind_token = Token::Uint(U256::from(0u8));
Expand All @@ -10,3 +18,53 @@ pub fn build_native_asset(token: H160, amount: u128) -> Bytes {

encode(&[kind_token, token_token, amount_token]).into()
}

pub async fn wait_for_ethereum_event_v2<Ev: EthEvent>(ethereum_client: &Box<Arc<Provider<Ws>>>) {
let gateway_addr: Address = (*GATEWAY_PROXY_CONTRACT).into();
let gateway = i_gateway::IGatewayV2::new(gateway_addr, (*ethereum_client).deref().clone());

let wait_for_blocks = 500;
let mut stream = ethereum_client.subscribe_blocks().await.unwrap().take(wait_for_blocks);

let mut ethereum_event_found = false;
while let Some(block) = stream.next().await {
println!("Polling ethereum block {:?} for expected event", block.number.unwrap());
if let Ok(events) = gateway.event::<Ev>().at_block_hash(block.hash.unwrap()).query().await {
for _ in events {
println!("Event found at ethereum block {:?}", block.number.unwrap());
ethereum_event_found = true;
break
}
}
if ethereum_event_found {
break
}
}
assert!(ethereum_event_found);
}

pub async fn fund_agent_v2(
agent_id: [u8; 32],
amount: u128,
) -> Result<(), Box<dyn std::error::Error>> {
let test_clients = initial_clients().await.expect("initialize clients");
let agent_address = get_agent_address(&test_clients.ethereum_client, agent_id)
.await
.expect("get agent address");

fund_account(&test_clients.ethereum_signed_client, agent_address, amount)
.await
.expect("fund account");
Ok(())
}

pub async fn get_agent_address(
ethereum_client: &Box<Arc<Provider<Ws>>>,
agent_id: [u8; 32],
) -> Result<Address, Box<dyn std::error::Error>> {
let gateway_addr: Address = (*GATEWAY_PROXY_CONTRACT).into();
let gateway = i_gateway::IGatewayV2::new(gateway_addr, (*ethereum_client).deref().clone());
let agent_address = gateway.agent_of(agent_id).await.expect("find agent");

Ok(agent_address)
}
1 change: 1 addition & 0 deletions smoketest/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ pub mod helper;
pub mod helper_v2;
pub mod parachains;
pub mod penpal_helper;
pub mod types;
pub mod xcm;
17 changes: 17 additions & 0 deletions smoketest/src/types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use codec::{Decode, Encode};
use scale_info::TypeInfo;
use subxt::ext::sp_core::RuntimeDebug;

#[derive(Clone, Encode, Decode, PartialEq, RuntimeDebug, TypeInfo)]
pub enum ContractCall {
V1 {
/// Target contract address
target: [u8; 20],
/// ABI-encoded calldata
calldata: Vec<u8>,
/// Include ether held by agent contract
value: u128,
/// Maximum gas to forward to target contract
gas: u64,
},
}
4 changes: 2 additions & 2 deletions smoketest/tests/send_native_eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use ethers::{
use futures::StreamExt;
use snowbridge_smoketest::{
constants::*,
contracts::i_gateway,
contracts::i_gateway_v1 as i_gateway,
helper::{initial_clients, print_event_log_for_unit_tests},
parachains::assethub::api::{
foreign_assets::events::Issued,
Expand All @@ -27,7 +27,7 @@ async fn send_native_eth() {
let assethub = *(test_clients.asset_hub_client.clone());

let gateway_addr: Address = (*GATEWAY_PROXY_CONTRACT).into();
let gateway = i_gateway::IGateway::new(gateway_addr, ethereum_client.clone());
let gateway = i_gateway::IGatewayV1::new(gateway_addr, ethereum_client.clone());

let eth_address: Address = [0; 20].into();

Expand Down
2 changes: 1 addition & 1 deletion smoketest/tests/transfer_native_eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use ethers::{
use futures::StreamExt;
use snowbridge_smoketest::{
constants::*,
contracts::i_gateway::{IGateway, InboundMessageDispatchedFilter},
contracts::i_gateway_v1::{IGatewayV1 as IGateway, InboundMessageDispatchedFilter},
helper::AssetHubConfig,
parachains::assethub::{
self,
Expand Down
6 changes: 6 additions & 0 deletions smoketest/tests/v2.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
#[path = "v2/outbound/agent_transact.rs"]
mod agent_transact;
#[path = "v2/outbound/register_agent.rs"]
mod register_agent;
#[path = "v2/outbound/register_pna.rs"]
mod register_pna;
#[path = "v2/outbound/transfer_ena.rs"]
mod transfer_ena;
#[path = "v2/outbound/transfer_pna.rs"]
Expand Down
Loading
Loading