Skip to content

Commit

Permalink
Test wallet integration (#383)
Browse files Browse the repository at this point in the history
* chore: get_payload_works

* test(wallet-integration): up contract get payload works

* get paylaod from server works

* test(wallet-integration): retrieve upload call data works

* test(wallet-integration): retrieve instantiate call data works

* style: better comments

* test: try higher wait times in CI

* test(wallet-integration): bump sleep time

* test(wallet-integration): even more sleep time

* test(wallet-integration): maybe a port problem ?

* revert 0075e94

* test(wallet-integration): better unit tests

* test(wallet-integration): wait for wallet signature

* test(wallet-integration): assert on received payload

* test(wallet-integration): use tokio spawn

* test(wallet-integration): add some waiting time

* test(wallet-integration): use cargo run

* style: nightly fmt

* test(wallet-integration): 500s sleep time

* test(wallet-integration): ignore some tests

* test(wallet-integration): get instantiate call data

* test(wallet-integration): integration tests improvements

* test(wallet-integration): bump sleep time

* test(wallet-integration): merge integration tests

* test(wallet-integration): remove sign_call_data test

* test(wallet-integration): use random free port

* test(wallet-integration): define gas_limit & proof_size

* fix: merge issues

---------

Co-authored-by: Alejandro Martinez Andres <[email protected]>
  • Loading branch information
peterwht and al3mart authored Dec 16, 2024
1 parent 074e2f9 commit 6b13134
Show file tree
Hide file tree
Showing 8 changed files with 290 additions and 17 deletions.
12 changes: 7 additions & 5 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 crates/pop-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,11 @@ tower-http = { workspace = true, features = ["fs", "cors"] }

[dev-dependencies]
assert_cmd.workspace = true
contract-extrinsics.workspace = true
predicates.workspace = true
subxt.workspace = true
subxt-signer.workspace = true
sp-weights.workspace = true

[features]
default = ["contract", "parachain", "telemetry"]
Expand Down
134 changes: 129 additions & 5 deletions crates/pop-cli/src/commands/up/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,7 @@ impl UpContractCommand {
let weight_limit = if self.gas_limit.is_some() && self.proof_size.is_some() {
Weight::from_parts(self.gas_limit.unwrap(), self.proof_size.unwrap())
} else {
// Frontend will do dry run and update call data.
Weight::from_parts(0, 0)
};
let call_data = get_instantiate_payload(instantiate_exec, weight_limit).await?;
Expand Down Expand Up @@ -403,6 +404,16 @@ fn display_contract_info(spinner: &ProgressBar, address: String, code_hash: Opti
#[cfg(test)]
mod tests {
use super::*;
use pop_common::{find_free_port, set_executable_permission};
use pop_contracts::{contracts_node_generator, mock_build_process, new_environment};
use std::{
env,
process::{Child, Command},
time::Duration,
};
use subxt::{tx::Payload, SubstrateConfig};
use tempfile::TempDir;
use tokio::time::sleep;
use url::Url;

fn default_up_contract_command() -> UpContractCommand {
Expand All @@ -423,6 +434,28 @@ mod tests {
}
}

async fn start_test_environment() -> anyhow::Result<(Child, u16, TempDir)> {
let random_port = find_free_port();
let temp_dir = new_environment("testing")?;
let current_dir = env::current_dir().expect("Failed to get current directory");
mock_build_process(
temp_dir.path().join("testing"),
current_dir.join("../pop-contracts/tests/files/testing.contract"),
current_dir.join("../pop-contracts/tests/files/testing.json"),
)?;
let cache = temp_dir.path().join("");
let binary = contracts_node_generator(cache.clone(), None).await?;
binary.source(false, &(), true).await?;
set_executable_permission(binary.path())?;
let process = run_contracts_node(binary.path(), None, random_port).await?;
Ok((process, random_port, temp_dir))
}

fn stop_test_environment(id: &str) -> anyhow::Result<()> {
Command::new("kill").args(["-s", "TERM", id]).spawn()?.wait()?;
Ok(())
}

#[test]
fn conversion_up_contract_command_to_up_opts_works() -> anyhow::Result<()> {
let command = default_up_contract_command();
Expand All @@ -444,15 +477,106 @@ mod tests {
Ok(())
}

#[tokio::test]
async fn get_upload_call_data_works() -> anyhow::Result<()> {
todo!()
let (contracts_node_process, port, temp_dir) = start_test_environment().await?;
let localhost_url = format!("ws://127.0.0.1:{}", port);
sleep(Duration::from_secs(20)).await;

let up_contract_opts = UpContractCommand {
path: Some(temp_dir.path().join("testing")),
constructor: "new".to_string(),
args: vec![],
value: "0".to_string(),
gas_limit: None,
proof_size: None,
salt: None,
url: Url::parse(&localhost_url).expect("given url is valid"),
suri: "//Alice".to_string(),
dry_run: false,
upload_only: true,
skip_confirm: true,
use_wallet: true,
};

let rpc_client = subxt::backend::rpc::RpcClient::from_url(&up_contract_opts.url).await?;
let client = subxt::OnlineClient::<SubstrateConfig>::from_rpc_client(rpc_client).await?;

// Retrieve call data based on the above command options.
let (retrieved_call_data, _) = match up_contract_opts.get_contract_data().await {
Ok(data) => data,
Err(e) => {
error(format!("An error occurred getting the call data: {e}"))?;
return Err(e);
},
};
// We have retrieved some payload.
assert!(!retrieved_call_data.is_empty());

// Craft encoded call data for an upload code call.
let contract_code = get_contract_code(up_contract_opts.path.as_ref()).await?;
let storage_deposit_limit: Option<u128> = None;
let upload_code = contract_extrinsics::extrinsic_calls::UploadCode::new(
contract_code,
storage_deposit_limit,
contract_extrinsics::upload::Determinism::Enforced,
);
let expected_call_data = upload_code.build();
let mut encoded_expected_call_data = Vec::<u8>::new();
expected_call_data
.encode_call_data_to(&client.metadata(), &mut encoded_expected_call_data)?;

// Retrieved call data and calculated match.
assert_eq!(retrieved_call_data, encoded_expected_call_data);

// Stop running contracts-node
stop_test_environment(&contracts_node_process.id().to_string())?;
Ok(())
}

#[tokio::test]
async fn get_instantiate_call_data_works() -> anyhow::Result<()> {
todo!()
}
let (contracts_node_process, port, temp_dir) = start_test_environment().await?;
let localhost_url = format!("ws://127.0.0.1:{}", port);
sleep(Duration::from_secs(20)).await;

let up_contract_opts = UpContractCommand {
path: Some(temp_dir.path().join("testing")),
constructor: "new".to_string(),
args: vec!["false".to_string()],
value: "0".to_string(),
gas_limit: Some(200_000_000),
proof_size: Some(30_000),
salt: None,
url: Url::parse(&localhost_url).expect("given url is valid"),
suri: "//Alice".to_string(),
dry_run: false,
upload_only: false,
skip_confirm: true,
use_wallet: true,
};

async fn wait_for_signature_works() -> anyhow::Result<()> {
todo!()
// Retrieve call data based on the above command options.
let (retrieved_call_data, _) = match up_contract_opts.get_contract_data().await {
Ok(data) => data,
Err(e) => {
error(format!("An error occurred getting the call data: {e}"))?;
return Err(e);
},
};
// We have retrieved some payload.
assert!(!retrieved_call_data.is_empty());

// Craft instantiate call data.
let weight = Weight::from_parts(200_000_000, 30_000);
let expected_call_data =
get_instantiate_payload(set_up_deployment(up_contract_opts.into()).await?, weight)
.await?;
// Retrieved call data matches the one crafted above.
assert_eq!(retrieved_call_data, expected_call_data);

// Stop running contracts-node
stop_test_environment(&contracts_node_process.id().to_string())?;
Ok(())
}
}
2 changes: 1 addition & 1 deletion crates/pop-cli/src/wallet_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ mod tests {
.await
.expect("Failed to parse response");

assert_eq!(response, json!({"status": "success"}));
assert_eq!(response, json!({"status": "success"}).to_string());
assert_eq!(wim.state.lock().await.signed_payload, Some("0xDEADBEEF".to_string()));
assert_eq!(wim.is_running(), false);

Expand Down
Loading

0 comments on commit 6b13134

Please sign in to comment.