hypercall_client/
account.rs1#![expect(
4 clippy::result_large_err,
5 reason = "these helpers preserve the established unboxed public ClientError contract"
6)]
7
8use alloy::primitives::{aliases::U96, Address, B256, U256};
9use alloy::providers::{Provider, ProviderBuilder};
10use alloy::sol;
11
12use crate::api::HypercallClient;
13use crate::error::{ClientError, Result};
14use crate::wallet::{evm_submission_lock, AccountAddress, HypercallWallet};
15
16const BPS_DENOMINATOR: u64 = 10_000;
17const CREATION_DEPOSIT_BUFFER_BPS: u64 = 100;
18const GAS_LIMIT_BUFFER_BPS: u64 = 2_000;
19const MAX_U96: u128 = (1_u128 << 96) - 1;
20
21sol! {
22 #[sol(rpc)]
23 interface AccountFactory {
24 event AccountCreated(address indexed account, address indexed manager);
25
26 function getCreationDeposit() external view returns (uint256);
27 function createAccount(uint96 salt) external payable returns (address account);
28 }
29}
30
31#[derive(Debug, Clone)]
33pub struct CreateAccountParams {
34 pub rpc_url: String,
36 pub factory_address: AccountAddress,
38 pub salt: Option<u128>,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct CreateAccountResult {
45 pub account: AccountAddress,
47 pub transaction_hash: B256,
49 pub hype_value: U256,
51}
52
53impl HypercallClient {
54 pub async fn create_account(
59 &self,
60 manager: &HypercallWallet,
61 params: CreateAccountParams,
62 ) -> Result<CreateAccountResult> {
63 let rpc_url = params
64 .rpc_url
65 .parse()
66 .map_err(|source| ClientError::invalid_input("HyperEVM RPC URL", source))?;
67 let salt = validate_salt(params.salt)?;
68 let factory_address = params.factory_address.as_wallet_address().inner();
69 let provider = ProviderBuilder::new()
70 .wallet(manager.ethereum_wallet())
71 .connect_http(rpc_url);
72
73 let rpc_chain_id = provider
74 .get_chain_id()
75 .await
76 .map_err(|error| onchain_error("read HyperEVM chain ID", error))?;
77 validate_chain_id(rpc_chain_id, manager.chain_id())?;
78
79 let submission_lock = evm_submission_lock(manager.address.as_wallet_address().inner());
80 let _submission_guard = submission_lock.lock().await;
81 create_account_on_provider(&provider, manager.address, factory_address, salt).await
82 }
83}
84
85async fn create_account_on_provider<P>(
86 provider: &P,
87 manager: AccountAddress,
88 factory_address: Address,
89 salt: U96,
90) -> Result<CreateAccountResult>
91where
92 P: Provider,
93{
94 let factory = AccountFactory::new(factory_address, provider);
95 let creation_deposit = factory
96 .getCreationDeposit()
97 .call()
98 .await
99 .map_err(|error| onchain_error("read Factory creation deposit", error))?;
100 let hype_value = buffered_u256(creation_deposit, CREATION_DEPOSIT_BUFFER_BPS)?;
101
102 let predicted_account = factory
103 .createAccount(salt)
104 .value(hype_value)
105 .from(manager.as_wallet_address().inner())
106 .call()
107 .await
108 .map_err(|error| onchain_error("simulate Factory account creation", error))?;
109 let estimated_gas = factory
110 .createAccount(salt)
111 .value(hype_value)
112 .from(manager.as_wallet_address().inner())
113 .estimate_gas()
114 .await
115 .map_err(|error| onchain_error("estimate Factory account creation gas", error))?;
116 let gas_limit = buffered_u64(estimated_gas, GAS_LIMIT_BUFFER_BPS)?;
117
118 let receipt = factory
119 .createAccount(salt)
120 .value(hype_value)
121 .gas(gas_limit)
122 .from(manager.as_wallet_address().inner())
123 .send()
124 .await
125 .map_err(|error| onchain_error("submit Factory account creation", error))?
126 .get_receipt()
127 .await
128 .map_err(|error| onchain_error("confirm Factory account creation", error))?;
129
130 if !receipt.status() {
131 return Err(ClientError::TransactionReverted {
132 operation: "Factory account creation",
133 transaction_hash: Some(receipt.transaction_hash),
134 });
135 }
136
137 let event = receipt
138 .logs()
139 .iter()
140 .filter(|log| log.address() == factory_address)
141 .find_map(|log| log.log_decode::<AccountFactory::AccountCreated>().ok());
142 let account = validate_account_created_event(
143 event.as_ref().map(|event| event.data()),
144 manager.as_wallet_address().inner(),
145 predicted_account,
146 )?;
147
148 Ok(CreateAccountResult {
149 account,
150 transaction_hash: receipt.transaction_hash,
151 hype_value,
152 })
153}
154
155fn validate_chain_id(rpc_chain_id: u64, wallet_chain_id: u64) -> Result<()> {
156 if rpc_chain_id == wallet_chain_id {
157 return Ok(());
158 }
159 Err(ClientError::InvalidInput(format!(
160 "HyperEVM RPC chain ID {rpc_chain_id} does not match wallet chain ID {wallet_chain_id}"
161 )))
162}
163
164fn validate_account_created_event(
165 event: Option<&AccountFactory::AccountCreated>,
166 manager_address: Address,
167 predicted_account: Address,
168) -> Result<AccountAddress> {
169 let event = event.ok_or(ClientError::MissingAccountCreatedEvent)?;
170 if event.manager != manager_address {
171 return Err(ClientError::AccountCreatedManagerMismatch {
172 observed: event.manager,
173 expected: manager_address,
174 });
175 }
176 if event.account != predicted_account {
177 return Err(ClientError::AccountCreatedAddressMismatch {
178 observed: event.account,
179 expected: predicted_account,
180 });
181 }
182 Ok(AccountAddress::from(event.account))
183}
184
185fn validate_salt(salt: Option<u128>) -> Result<U96> {
186 let salt = salt.unwrap_or_default();
187 if salt > MAX_U96 {
188 return Err(ClientError::InvalidInput(format!(
189 "account salt {salt} exceeds uint96"
190 )));
191 }
192 Ok(U96::from(salt))
193}
194
195fn buffered_u256(value: U256, buffer_bps: u64) -> Result<U256> {
196 let multiplier = U256::from(BPS_DENOMINATOR + buffer_bps);
197 value
198 .checked_mul(multiplier)
199 .and_then(|scaled| scaled.checked_add(U256::from(BPS_DENOMINATOR - 1)))
200 .map(|rounded| rounded / U256::from(BPS_DENOMINATOR))
201 .ok_or(ClientError::ArithmeticOverflow {
202 operation: "account creation deposit buffer",
203 })
204}
205
206fn buffered_u64(value: u64, buffer_bps: u64) -> Result<u64> {
207 let rounded = u128::from(value)
208 .checked_mul(u128::from(BPS_DENOMINATOR + buffer_bps))
209 .and_then(|scaled| scaled.checked_add(u128::from(BPS_DENOMINATOR - 1)))
210 .map(|scaled| scaled / u128::from(BPS_DENOMINATOR))
211 .ok_or(ClientError::ArithmeticOverflow {
212 operation: "account creation gas buffer",
213 })?;
214 u64::try_from(rounded).map_err(|_| ClientError::ArithmeticOverflow {
215 operation: "account creation gas buffer",
216 })
217}
218
219fn onchain_error(
220 operation: impl Into<String>,
221 source: impl std::error::Error + Send + Sync + 'static,
222) -> ClientError {
223 ClientError::Onchain {
224 operation: operation.into(),
225 source: Box::new(source),
226 }
227}
228
229#[cfg(test)]
230#[path = "account_test.rs"]
231mod tests;