Skip to content

Commit

Permalink
remove query to predict address (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
Art3miX authored Oct 8, 2024
1 parent c3822f2 commit 7bd7c76
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 54 deletions.
53 changes: 34 additions & 19 deletions workflow-manager/src/domain/cosmos_cw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::{
account::{AccountType, InstantiateAccountData},
bridge::PolytoneSingleChainInfo,
config::{ChainInfo, ConfigError, CONFIG},
helpers::{addr_canonicalize, addr_humanize},
service::{ServiceConfig, ServiceError},
workflow_config::WorkflowConfig,
MAIN_CHAIN, NEUTRON_DOMAIN,
Expand All @@ -25,7 +26,7 @@ use cosmos_grpc_client::{
cosmrs::bip32::secp256k1::sha2::{digest::Update, Digest, Sha256},
BroadcastMode, Decimal, GrpcClient, ProstMsgNameToAny, Wallet,
};
use cosmwasm_std::{from_json, to_json_binary};
use cosmwasm_std::{from_json, instantiate2_address, to_json_binary};
use serde_json::to_vec;
use strum::VariantNames;
use thiserror::Error;
Expand Down Expand Up @@ -79,6 +80,7 @@ pub struct CosmosCosmwasmConnector {
wallet: Wallet,
code_ids: HashMap<String, u64>,
chain_name: String,
prefix: String,
}

impl fmt::Debug for CosmosCosmwasmConnector {
Expand Down Expand Up @@ -123,6 +125,7 @@ impl CosmosCosmwasmConnector {
wallet,
code_ids: code_ids.clone(),
chain_name: chain_info.name.clone(),
prefix: chain_info.prefix.clone(),
})
}
}
Expand Down Expand Up @@ -226,24 +229,36 @@ impl Connector for CosmosCosmwasmConnector {
.finalize()
.to_vec();

let addr = self
.wallet
.client
.proto_query::<QueryBuildAddressRequest, QueryBuildAddressResponse>(
QueryBuildAddressRequest {
code_hash: hex::encode(checksum.clone()),
creator_address: self.wallet.account_address.clone(),
salt: hex::encode(salt.clone()),
},
"/cosmwasm.wasm.v1.Query/BuildAddress",
)
.await
.context(format!(
"Failed to query the instantiate2 address: {:?}",
checksum
))
.map_err(CosmosCosmwasmError::Error)?
.address;
let addr_canonical = instantiate2_address(
&checksum,
&addr_canonicalize(&self.prefix, self.wallet.account_address.as_str()).unwrap(),
&salt,
)
.context("Failed to instantiate2 address")
.map_err(CosmosCosmwasmError::Error)?;

let addr =
addr_humanize(&self.prefix, &addr_canonical).map_err(CosmosCosmwasmError::Error)?;

// TODO: Remove this later
// let addr2 = self
// .wallet
// .client
// .proto_query::<QueryBuildAddressRequest, QueryBuildAddressResponse>(
// QueryBuildAddressRequest {
// code_hash: hex::encode(checksum.clone()),
// creator_address: self.wallet.account_address.clone(),
// salt: hex::encode(salt.clone()),
// },
// "/cosmwasm.wasm.v1.Query/BuildAddress",
// )
// .await
// .context(format!(
// "Failed to query the instantiate2 address: {:?}",
// checksum
// ))
// .map_err(CosmosCosmwasmError::Error)?
// .address;

Ok((addr, salt.to_vec()))
}
Expand Down
34 changes: 34 additions & 0 deletions workflow-manager/src/helpers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use anyhow::anyhow;
use bech32::{encode, primitives::decode::CheckedHrpstring, Bech32, Hrp};
use cosmwasm_std::CanonicalAddr;

fn validate_length(bytes: &[u8]) -> Result<(), anyhow::Error> {
match bytes.len() {
1..=255 => Ok(()),
_ => Err(anyhow!("Invalid canonical address length")),
}
}

pub fn addr_canonicalize(prefix: &str, input: &str) -> Result<CanonicalAddr, anyhow::Error> {
let hrp_str =
CheckedHrpstring::new::<Bech32>(input).map_err(|_| anyhow!("Error decoding bech32"))?;

if !hrp_str
.hrp()
.as_bytes()
.eq_ignore_ascii_case(prefix.as_bytes())
{
return Err(anyhow!("Wrong bech32 prefix"));
}

let bytes: Vec<u8> = hrp_str.byte_iter().collect();
validate_length(&bytes)?;
Ok(bytes.into())
}

pub fn addr_humanize(prefix: &str, canonical: &CanonicalAddr) -> Result<String, anyhow::Error> {
validate_length(canonical.as_ref())?;

let prefix = Hrp::parse(prefix).map_err(|_| anyhow!("Invalid bech32 prefix"))?;
encode::<Bech32>(prefix, canonical.as_slice()).map_err(|_| anyhow!("Bech32 encoding error"))
}
1 change: 1 addition & 0 deletions workflow-manager/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod config;
pub mod connectors;
pub mod domain;
pub mod error;
pub mod helpers;
pub mod macros;
pub mod service;
pub mod tests;
Expand Down
39 changes: 4 additions & 35 deletions workflow-manager/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#[cfg(test)]
mod test {
use cosmwasm_std::Uint128;
use std::collections::BTreeMap;

use cosmwasm_std::Uint128;
use serde_json_any_key::MapIterToJson;
use valence_service_utils::ServiceAccountType;
use valence_splitter_service::msg::{
Expand Down Expand Up @@ -35,43 +35,12 @@ mod test {
let _config = Config::default();
// let ctx = Connectors::new(&config);

let domain = Domain::CosmosCosmwasm("neutron");
let mut _connector = domain.generate_connector().await.unwrap();
// let domain = Domain::CosmosCosmwasm("neutron");
// let mut connector = domain.generate_connector().await.unwrap();
// let (addr, salt) = connector
// .get_address(1, "base_account", "account")
// .get_address(2, "splitter", "splitter")
// .await
// .unwrap();
// let account_info = InstantiateAccountData {
// id: 1,
// info: AccountInfo{ name: "Test".to_string(), ty: AccountType::Base { admin: None }, domain },
// addr,
// salt,
// approved_services: vec![],
// };

// let id = connector.reserve_workflow_id().await.unwrap();
// println!("{:?}", id);

// // let domain2 = Domain::Cosmos("neutron".to_string());
// let mut domain_info = DomainInfo::from_domain(&domain).await;
// println!("{domain_info:?}");
// let mut domain_info2 = DomainInfo::from_domain(domain2).await;
// println!("{domain_info2:?}");

// let mut domain_info3 = DomainInfo::from_domain(domain).await;
// println!("{domain_info3:?}");

// let stats = dhat::HeapStats::get();

// let d = domain_info
// .connector
// .init_account(
// 1,
// None,
// "label".to_string(),
// )
// .await;
// println!("Balance: {d:?}");
}

#[ignore = "internal test"]
Expand Down

0 comments on commit 7bd7c76

Please sign in to comment.