#![cfg(feature = "rpc")]
use std::str::FromStr;
use alloy::primitives::{Address, Bytes, FixedBytes};
use cid::Cid;
use newton_common::{get_provider, get_signer};
use crate::{
config::ipfs::IpfsConfig,
mock_newton_policy_client::{INewtonPolicy::PolicyConfig, MockNewtonPolicyClient},
newton_policy_client::NewtonPolicyClient,
};
pub async fn newton_policy_client_set_policy(
private_key: &str,
rpc_url: &str,
policy_client: Address,
policy_params: Bytes,
expire_after: u32,
) -> eyre::Result<(Address, FixedBytes<32>)> {
tracing::info!("Setting policy for policy client {}", policy_client);
let signer = get_signer(private_key, rpc_url);
let policy_client_instance = MockNewtonPolicyClient::new(policy_client, signer);
let policy_address = policy_client_instance.getPolicyAddress().call().await.unwrap();
let _ = policy_client_instance
.setPolicy(PolicyConfig {
policyParams: policy_params,
expireAfter: expire_after,
})
.send()
.await
.unwrap()
.get_receipt()
.await
.unwrap();
match policy_client_instance.getPolicyId().call().await {
Ok(policy_id) => Ok((policy_address, policy_id)),
Err(e) => Err(eyre::eyre!(
"Failed to get policy id for policy client {}: {}",
policy_client,
e,
)),
}
}
pub async fn get_policy_id_for_policy_client(
rpc_url: &str,
policy_client_address: Address,
) -> eyre::Result<FixedBytes<32>> {
let policy = NewtonPolicyClient::new(policy_client_address, get_provider(rpc_url));
let policy_id = policy.getPolicyId().call().await.map_err(|e| {
eyre::eyre!(
"failed to get policy id for policy client {}: {}",
policy_client_address,
e
)
})?;
Ok(policy_id)
}
pub async fn get_policy_address_for_policy_client(
rpc_url: &str,
policy_client_address: Address,
) -> eyre::Result<Address> {
let policy = NewtonPolicyClient::new(policy_client_address, get_provider(rpc_url));
let policy_address = policy.getPolicyAddress().call().await.map_err(|e| {
eyre::eyre!(
"failed to get policy address for policy client {}: {}",
policy_client_address,
e
)
})?;
Ok(policy_address)
}
pub fn get_ipfs_url(cid: &str, config: Option<&IpfsConfig>) -> eyre::Result<(String, bool)> {
let default = IpfsConfig::default();
let config = config.unwrap_or(&default);
if config.gateway.eq(crate::config::ipfs::PUBLIC_IPFS_GATEWAY) {
tracing::warn!("Using public IPFS gateway to fetch schema");
}
let _ = Cid::from_str(cid).map_err(|_| eyre::eyre!("Invalid CID \"{}\"", cid))?;
let uri = if !config.params.is_empty() {
format!("{}{}?{}", config.gateway, cid, config.params)
} else {
format!("{}{}", config.gateway, cid)
};
Ok((uri, config.gateway.eq(crate::config::ipfs::PUBLIC_IPFS_GATEWAY)))
}