-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathsend.rs
More file actions
513 lines (453 loc) · 15.8 KB
/
Copy pathsend.rs
File metadata and controls
513 lines (453 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
use alloy::{
dyn_abi::TypedData,
eips::eip7702::Authorization,
primitives::{Address, Bytes, ChainId, FixedBytes, U256, address},
providers::Provider,
sol_types::eip712_domain,
};
use engine_core::{
chain::{Chain, ChainService, RpcCredentials},
credentials::SigningCredential,
error::{EngineError, RpcErrorKind},
execution_options::WebhookOptions,
signer::{AccountSigner, EoaSigner, EoaSigningOptions},
transaction::InnerTransaction,
};
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::sync::Arc;
use twmq::{
FailHookData, NackHookData, Queue, SuccessHookData, UserCancellable,
error::TwmqError,
hooks::TransactionContext,
job::{BorrowedJob, JobResult, ToJobResult},
};
use crate::{
transaction_registry::TransactionRegistry,
webhook::{
WebhookJobHandler,
envelope::{ExecutorStage, HasTransactionMetadata, HasWebhookOptions, WebhookCapable},
},
};
use super::confirm::{Eip7702ConfirmationHandler, Eip7702ConfirmationJobData};
const MINIMAL_ACCOUNT_IMPLEMENTATION_ADDRESS: Address =
address!("0xD6999651Fc0964B9c6B444307a0ab20534a66560");
// --- Job Payload ---
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Eip7702SendJobData {
pub transaction_id: String,
pub chain_id: u64,
pub transactions: Vec<InnerTransaction>,
pub eoa_address: Address,
pub signing_credential: SigningCredential,
#[serde(default)]
pub webhook_options: Vec<WebhookOptions>,
pub rpc_credentials: RpcCredentials,
pub nonce: Option<U256>,
}
impl HasWebhookOptions for Eip7702SendJobData {
fn webhook_options(&self) -> Vec<WebhookOptions> {
self.webhook_options.clone()
}
}
impl HasTransactionMetadata for Eip7702SendJobData {
fn transaction_id(&self) -> String {
self.transaction_id.clone()
}
}
// --- Success Result ---
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Eip7702SendResult {
pub eoa_address: Address,
pub transaction_id: String,
pub wrapped_calls: Value,
pub signature: String,
pub authorization: Option<Authorization>,
}
// --- Error Types ---
#[derive(Serialize, Deserialize, Debug, Clone, thiserror::Error)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE", tag = "errorCode")]
pub enum Eip7702SendError {
#[error("Chain service error for chainId {chain_id}: {message}")]
ChainServiceError { chain_id: u64, message: String },
#[error("Failed to sign typed data: {message}")]
#[serde(rename_all = "camelCase")]
SigningError {
message: String,
inner_error: Option<EngineError>,
},
#[error("Failed to check 7702 delegation: {message}")]
#[serde(rename_all = "camelCase")]
DelegationCheckError {
message: String,
inner_error: Option<EngineError>,
},
#[error("Failed to call bundler: {message}")]
BundlerCallError { message: String },
#[error("Invalid RPC Credentials: {message}")]
InvalidRpcCredentials { message: String },
#[error("Internal error: {message}")]
InternalError { message: String },
#[error("Transaction cancelled by user")]
UserCancelled,
}
impl From<TwmqError> for Eip7702SendError {
fn from(error: TwmqError) -> Self {
Eip7702SendError::InternalError {
message: format!("Deserialization error for job data: {}", error),
}
}
}
impl UserCancellable for Eip7702SendError {
fn user_cancelled() -> Self {
Eip7702SendError::UserCancelled
}
}
// --- Wrapped Calls Structure ---
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Call {
pub target: Address,
pub value: U256,
pub data: Bytes,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct WrappedCalls {
pub calls: Vec<Call>,
pub uid: FixedBytes<32>,
}
// --- Handler ---
pub struct Eip7702SendHandler<CS>
where
CS: ChainService + Send + Sync + 'static,
{
pub chain_service: Arc<CS>,
pub eoa_signer: Arc<EoaSigner>,
pub webhook_queue: Arc<Queue<WebhookJobHandler>>,
pub confirm_queue: Arc<Queue<Eip7702ConfirmationHandler<CS>>>,
pub transaction_registry: Arc<TransactionRegistry>,
}
impl<CS> ExecutorStage for Eip7702SendHandler<CS>
where
CS: ChainService + Send + Sync + 'static,
{
fn executor_name() -> &'static str {
"eip7702"
}
fn stage_name() -> &'static str {
"prepare_and_send"
}
}
impl<CS> WebhookCapable for Eip7702SendHandler<CS>
where
CS: ChainService + Send + Sync + 'static,
{
fn webhook_queue(&self) -> &Arc<Queue<WebhookJobHandler>> {
&self.webhook_queue
}
}
impl<CS> twmq::DurableExecution for Eip7702SendHandler<CS>
where
CS: ChainService + Send + Sync + 'static,
{
type Output = Eip7702SendResult;
type ErrorData = Eip7702SendError;
type JobData = Eip7702SendJobData;
#[tracing::instrument(skip(self, job), fields(transaction_id = job.job.id, stage = Self::stage_name(), executor = Self::executor_name()))]
async fn process(
&self,
job: &BorrowedJob<Self::JobData>,
) -> JobResult<Self::Output, Self::ErrorData> {
let job_data = &job.job.data;
// 1. Get Chain
let chain = self
.chain_service
.get_chain(job_data.chain_id)
.map_err(|e| Eip7702SendError::ChainServiceError {
chain_id: job_data.chain_id,
message: format!("Failed to get chain instance: {}", e),
})
.map_err_fail()?;
let chain_auth_headers = job_data
.rpc_credentials
.to_header_map()
.map_err(|e| Eip7702SendError::InvalidRpcCredentials {
message: e.to_string(),
})
.map_err_fail()?;
let chain = chain.with_new_default_headers(chain_auth_headers);
// 2. Create wrapped calls with random UID
let wrapped_calls = WrappedCalls {
calls: job_data
.transactions
.iter()
.map(|tx| Call {
target: tx.to.unwrap_or_default(),
value: tx.value,
data: tx.data.clone(),
})
.collect(),
uid: {
let mut rng = rand::rng();
let mut bytes = [0u8; 32];
rng.fill(&mut bytes);
FixedBytes::from(bytes)
},
};
// 3. Sign typed data for wrapped calls
let typed_data = create_wrapped_calls_typed_data(
job_data.chain_id,
job_data.eoa_address,
&wrapped_calls,
);
let signing_options = EoaSigningOptions {
from: job_data.eoa_address,
chain_id: Some(ChainId::from(job_data.chain_id)),
};
let signature = self
.eoa_signer
.sign_typed_data(
signing_options.clone(),
&typed_data,
&job_data.signing_credential,
)
.await
.map_err(|e| Eip7702SendError::SigningError {
message: format!("Failed to sign typed data: {e}"),
inner_error: Some(e),
})
.map_err_fail()?;
// 4. Check if wallet has 7702 delegation set
let is_minimal_account = check_is_7702_minimal_account(&chain, job_data.eoa_address)
.await
.map_err(|e| Eip7702SendError::DelegationCheckError {
message: format!("Failed to check if wallet has 7702 delegation: {e}"),
inner_error: Some(e),
})
.map_err_fail()?;
// 5. Sign authorization if needed
let authorization = if !is_minimal_account {
let nonce = job_data.nonce.unwrap_or_default();
let auth = self
.eoa_signer
.sign_authorization(
signing_options.clone(),
job_data.chain_id,
MINIMAL_ACCOUNT_IMPLEMENTATION_ADDRESS,
nonce,
&job_data.signing_credential,
)
.await
.map_err(|e| Eip7702SendError::SigningError {
message: format!("Failed to sign authorization: {e}"),
inner_error: Some(e),
})
.map_err_fail()?;
Some(auth.clone())
} else {
None
};
// 6. Call bundler
let transaction_id = chain
.bundler_client()
.tw_execute(
job_data.eoa_address,
&serde_json::to_value(&wrapped_calls)
.map_err(|e| Eip7702SendError::InternalError {
message: format!("Failed to serialize wrapped calls: {}", e),
})
.map_err_fail()?,
&signature,
authorization.as_ref(),
)
.await
.map_err(|e| Eip7702SendError::BundlerCallError {
message: e.to_string(),
})
.map_err_fail()?;
tracing::debug!(transaction_id = ?transaction_id, "EIP-7702 transaction sent to bundler");
Ok(Eip7702SendResult {
eoa_address: job_data.eoa_address,
transaction_id,
wrapped_calls: serde_json::to_value(&wrapped_calls)
.map_err(|e| Eip7702SendError::InternalError {
message: format!("Failed to serialize wrapped calls: {}", e),
})
.map_err_fail()?,
signature,
authorization: authorization.map(|f| f.inner().clone()),
})
}
async fn on_success(
&self,
job: &BorrowedJob<Eip7702SendJobData>,
success_data: SuccessHookData<'_, Eip7702SendResult>,
tx: &mut TransactionContext<'_>,
) {
// Update transaction registry: move from send queue to confirm queue
self.transaction_registry.add_set_command(
tx.pipeline(),
&job.job.data.transaction_id,
"eip7702_confirm",
);
// Send confirmation job
let confirmation_job = self
.confirm_queue
.clone()
.job(Eip7702ConfirmationJobData {
transaction_id: job.job.data.transaction_id.clone(),
chain_id: job.job.data.chain_id,
bundler_transaction_id: success_data.result.transaction_id.clone(),
eoa_address: success_data.result.eoa_address,
rpc_credentials: job.job.data.rpc_credentials.clone(),
webhook_options: job.job.data.webhook_options.clone(),
})
.with_id(job.job.transaction_id());
if let Err(e) = tx.queue_job(confirmation_job) {
tracing::error!(
transaction_id = job.job.data.transaction_id,
error = ?e,
"Failed to enqueue confirmation job"
);
}
// Send webhook
if let Err(e) = self.queue_success_webhook(job, success_data, tx) {
tracing::error!(
transaction_id = job.job.data.transaction_id,
error = ?e,
"Failed to queue success webhook"
);
}
}
async fn on_nack(
&self,
job: &BorrowedJob<Eip7702SendJobData>,
nack_data: NackHookData<'_, Eip7702SendError>,
tx: &mut TransactionContext<'_>,
) {
// Don't modify transaction registry on NACK - job will be retried
if let Err(e) = self.queue_nack_webhook(job, nack_data, tx) {
tracing::error!(
transaction_id = job.job.data.transaction_id,
error = ?e,
"Failed to queue nack webhook"
);
}
}
async fn on_fail(
&self,
job: &BorrowedJob<Eip7702SendJobData>,
fail_data: FailHookData<'_, Eip7702SendError>,
tx: &mut TransactionContext<'_>,
) {
// Remove transaction from registry since it failed permanently
self.transaction_registry
.add_remove_command(tx.pipeline(), &job.job.data.transaction_id);
tracing::error!(
transaction_id = job.job.data.transaction_id,
error = ?fail_data.error,
"EIP-7702 send job failed"
);
if let Err(e) = self.queue_fail_webhook(job, fail_data, tx) {
tracing::error!(
transaction_id = job.job.data.transaction_id,
error = ?e,
"Failed to queue fail webhook"
);
}
}
}
// --- Helper Functions ---
fn create_wrapped_calls_typed_data(
chain_id: u64,
verifying_contract: Address,
wrapped_calls: &WrappedCalls,
) -> TypedData {
let domain = eip712_domain! {
name: "MinimalAccount",
version: "1",
chain_id: chain_id,
verifying_contract: verifying_contract,
};
let types_json = json!({
"Call": [
{"name": "target", "type": "address"},
{"name": "value", "type": "uint256"},
{"name": "data", "type": "bytes"}
],
"WrappedCalls": [
{"name": "calls", "type": "Call[]"},
{"name": "uid", "type": "bytes32"}
]
});
let message = json!({
"calls": wrapped_calls.calls,
"uid": wrapped_calls.uid
});
// Parse the JSON into Eip712Types and create resolver
let eip712_types: alloy::dyn_abi::eip712::Eip712Types =
serde_json::from_value(types_json).expect("Failed to parse EIP712 types");
TypedData {
domain,
resolver: eip712_types.into(),
primary_type: "WrappedCalls".to_string(),
message,
}
}
async fn check_is_7702_minimal_account(
chain: &impl Chain,
eoa_address: Address,
) -> Result<bool, EngineError> {
// Get the bytecode at the EOA address using eth_getCode
let code = chain
.provider()
.get_code_at(eoa_address)
.await
.map_err(|e| EngineError::RpcError {
chain_id: chain.chain_id(),
rpc_url: chain.rpc_url().to_string(),
message: format!("Failed to get code at address {}: {}", eoa_address, e),
kind: RpcErrorKind::InternalError {
message: e.to_string(),
},
})?;
tracing::debug!(
eoa_address = ?eoa_address,
code_length = code.len(),
code_hex = ?alloy::hex::encode(&code),
"Checking EIP-7702 delegation"
);
// Check if code exists and starts with EIP-7702 delegation prefix "0xef0100"
if code.len() < 23 || !code.starts_with(&[0xef, 0x01, 0x00]) {
tracing::debug!(
eoa_address = ?eoa_address,
has_delegation = false,
reason = "Code too short or doesn't start with EIP-7702 prefix",
"EIP-7702 delegation check result"
);
return Ok(false);
}
// Extract the target address from bytes 3-23 (20 bytes for address)
// EIP-7702 format: 0xef0100 + 20 bytes address
// JS equivalent: code.slice(8, 48) extracts 40 hex chars = 20 bytes
// In hex string: "0xef0100" + address, so address starts at position 8
// In byte array: [0xef, 0x01, 0x00, address_bytes...]
// The address starts at byte 3 and is 20 bytes long (bytes 3-22)
let target_bytes = &code[3..23];
let target_address = Address::from_slice(target_bytes);
// Compare with the minimal account implementation address
let minimal_account_address: Address = MINIMAL_ACCOUNT_IMPLEMENTATION_ADDRESS;
let is_delegated = target_address == minimal_account_address;
tracing::debug!(
eoa_address = ?eoa_address,
target_address = ?target_address,
minimal_account_address = ?minimal_account_address,
has_delegation = is_delegated,
"EIP-7702 delegation check result"
);
Ok(is_delegated)
}