use alloy::{
hex,
primitives::{
Address,
Bytes,
},
providers::Provider,
sol_types::SolCall,
};
use crate::{
artifacts::Artifacts,
bindings::proxy::IUUPSUpgradeable,
error::{
Error,
Result,
},
};
#[macro_export]
macro_rules! send_with_nonce_retry {
($call_expr:expr, $label:expr, $provider:expr, $sender:expr) => {{
const MAX_RETRIES: u32 = 3;
let mut result: $crate::Result<alloy::rpc::types::TransactionReceipt> =
Err($crate::Error::Rpc {
detail: "unreachable".into(),
});
for attempt in 0..MAX_RETRIES {
let nonce =
alloy::providers::Provider::get_transaction_count($provider, $sender)
.await
.map_err(|e| $crate::Error::Rpc {
detail: format!("{} failed to fetch nonce: {e}", $label),
})?;
match ($call_expr).nonce(nonce).send().await {
Ok(pending) => {
result =
pending.get_receipt().await.map_err(|e| $crate::Error::Rpc {
detail: format!("{} confirmation failed: {e}", $label),
});
break;
}
Err(e) => {
let msg = e.to_string();
let next_attempt = attempt.saturating_add(1);
if msg.contains("nonce too low") && next_attempt < MAX_RETRIES {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
continue;
}
result = Err($crate::Error::Rpc {
detail: format!("{} send failed: {e}", $label),
});
break;
}
}
}
result
}};
}
pub async fn deploy_contract<P: Provider>(
provider: &P,
bytecode: Bytes,
label: &str,
) -> Result<Address> {
deploy_contract_from(provider, bytecode, label, None).await
}
pub async fn deploy_contract_from<P: Provider>(
provider: &P,
bytecode: Bytes,
label: &str,
sender: Option<Address>,
) -> Result<Address> {
use alloy::{
network::TransactionBuilder,
rpc::types::TransactionRequest,
};
let mut tx = TransactionRequest::default().with_deploy_code(bytecode);
if let Some(addr) = sender {
let nonce =
provider
.get_transaction_count(addr)
.await
.map_err(|e| Error::Rpc {
detail: format!("failed to fetch nonce for {label}: {e}"),
})?;
tx = tx.with_nonce(nonce);
}
let pending = provider
.send_transaction(tx)
.await
.map_err(|e| Error::Rpc {
detail: format!("failed to send {label} deploy tx: {e}"),
})?;
let receipt = pending.get_receipt().await.map_err(|e| Error::Rpc {
detail: format!("failed to get {label} deploy receipt: {e}"),
})?;
receipt.contract_address.ok_or_else(|| Error::Rpc {
detail: format!("{label} deploy did not return contract address"),
})
}
pub async fn deploy_with_ctor<P: Provider>(
provider: &P,
bytecode: &Bytes,
constructor_args: &[u8],
label: &str,
sender: Option<Address>,
) -> Result<Address> {
let mut deploy_bytecode = bytecode.to_vec();
deploy_bytecode.extend_from_slice(constructor_args);
deploy_contract_from(provider, Bytes::from(deploy_bytecode), label, sender).await
}
pub async fn deploy_proxy<P: Provider>(
provider: &P,
proxy_bytecode: &Bytes,
implementation: Address,
init_data: Bytes,
label: &str,
sender: Option<Address>,
) -> Result<Address> {
let constructor_args =
alloy::sol_types::SolValue::abi_encode_params(&(implementation, init_data));
deploy_with_ctor(provider, proxy_bytecode, &constructor_args, label, sender).await
}
pub async fn deploy_behind_proxy<P: Provider, C: SolCall>(
provider: &P,
artifacts: &Artifacts,
contract: &str,
init_call: &C,
sender: Option<Address>,
) -> Result<Address> {
let implementation = deploy_contract_from(
provider,
artifacts.bytecode(contract)?,
&format!("{contract} (impl)"),
sender,
)
.await?;
let proxy_bytecode = artifacts.bytecode("ERC1967Proxy")?;
deploy_proxy(
provider,
&proxy_bytecode,
implementation,
init_call.abi_encode().into(),
&format!("{contract} (proxy)"),
sender,
)
.await
}
pub async fn upgrade_uups<P: Provider>(
provider: &P,
artifacts: &Artifacts,
proxy: Address,
contract: &str,
data: Bytes,
sender: Option<Address>,
) -> Result<Address> {
let new_impl = deploy_contract_from(
provider,
artifacts.bytecode(contract)?,
&format!("{contract} (new impl)"),
sender,
)
.await?;
let proxied = IUUPSUpgradeable::new(proxy, provider);
let call = proxied.upgradeToAndCall(new_impl, data);
let pending =
match sender {
Some(addr) => {
let nonce = provider.get_transaction_count(addr).await.map_err(|e| {
Error::Rpc {
detail: format!("{contract} upgrade failed to fetch nonce: {e}"),
}
})?;
call.nonce(nonce).send().await
}
None => call.send().await,
}
.map_err(|e| Error::Rpc {
detail: format!("{contract} upgradeToAndCall send failed: {e}"),
})?;
pending.get_receipt().await.map_err(|e| Error::Rpc {
detail: format!("{contract} upgradeToAndCall confirmation failed: {e}"),
})?;
Ok(new_impl)
}
pub async fn load_linked_bytecode<P: Provider>(
provider: &P,
artifacts: &Artifacts,
file: &str,
contract: &str,
sender: Option<Address>,
) -> Result<Bytes> {
let mut hex_str = artifacts.bytecode_hex(file, contract)?;
for (lib_file, libs) in artifacts.link_references(file, contract)? {
let lib_stem = std::path::Path::new(&lib_file)
.file_stem()
.and_then(|s| s.to_str())
.ok_or_else(|| Error::Artifact {
detail: format!("bad library file path {lib_file}"),
})?;
for (lib_name, refs) in libs.as_object().into_iter().flatten() {
let lib_bytecode = Box::pin(load_linked_bytecode(
provider, artifacts, lib_stem, lib_name, sender,
))
.await?;
let lib_addr = deploy_contract_from(
provider,
lib_bytecode,
&format!("{lib_name} (library)"),
sender,
)
.await?;
let addr_hex = hex::encode(lib_addr.as_slice()); for r in refs.as_array().into_iter().flatten() {
let start = r["start"]
.as_u64()
.and_then(|v| usize::try_from(v).ok())
.ok_or_else(|| Error::Artifact {
detail: format!("bad linkReference start for {lib_name}"),
})?;
let length = r["length"]
.as_u64()
.and_then(|v| usize::try_from(v).ok())
.ok_or_else(|| Error::Artifact {
detail: format!("bad linkReference length for {lib_name}"),
})?;
let begin = start.checked_mul(2);
let end = start.checked_add(length).and_then(|v| v.checked_mul(2));
let (begin, end) = begin.zip(end).ok_or_else(|| Error::Artifact {
detail: format!("linkReference offset overflow for {lib_name}"),
})?;
hex_str.replace_range(begin..end, &addr_hex);
}
}
}
let bytes = hex::decode(&hex_str).map_err(|e| Error::Artifact {
detail: format!("invalid bytecode hex after linking {file}.{contract}: {e}"),
})?;
Ok(Bytes::from(bytes))
}