-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathconfirm.rs
More file actions
327 lines (288 loc) · 10.3 KB
/
Copy pathconfirm.rs
File metadata and controls
327 lines (288 loc) · 10.3 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
use alloy::primitives::{Address, TxHash};
use alloy::providers::Provider;
use alloy::rpc::types::TransactionReceipt;
use engine_core::error::{AlloyRpcErrorToEngineError, EngineError};
use engine_core::{
chain::{Chain, ChainService, RpcCredentials},
execution_options::WebhookOptions,
};
use serde::{Deserialize, Serialize};
use std::{sync::Arc, time::Duration};
use twmq::{
FailHookData, NackHookData, Queue, SuccessHookData, UserCancellable,
error::TwmqError,
hooks::TransactionContext,
job::{BorrowedJob, JobResult, RequeuePosition, ToJobError, ToJobResult},
};
use crate::{
transaction_registry::TransactionRegistry,
webhook::{
WebhookJobHandler,
envelope::{ExecutorStage, HasTransactionMetadata, HasWebhookOptions, WebhookCapable},
},
};
// --- Job Payload ---
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Eip7702ConfirmationJobData {
pub transaction_id: String,
pub chain_id: u64,
pub bundler_transaction_id: String,
pub eoa_address: Address,
pub rpc_credentials: RpcCredentials,
#[serde(default)]
pub webhook_options: Vec<WebhookOptions>,
}
impl HasWebhookOptions for Eip7702ConfirmationJobData {
fn webhook_options(&self) -> Vec<WebhookOptions> {
self.webhook_options.clone()
}
}
impl HasTransactionMetadata for Eip7702ConfirmationJobData {
fn transaction_id(&self) -> String {
self.transaction_id.clone()
}
}
// --- Success Result ---
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Eip7702ConfirmationResult {
pub transaction_id: String,
pub transaction_hash: TxHash,
pub receipt: TransactionReceipt,
pub eoa_address: Address,
}
// --- Error Types ---
#[derive(Serialize, Deserialize, Debug, Clone, thiserror::Error)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE", tag = "errorCode")]
pub enum Eip7702ConfirmationError {
#[error("Chain service error for chainId {chain_id}: {message}")]
#[serde(rename_all = "camelCase")]
ChainServiceError { chain_id: u64, message: String },
#[error("Failed to get transaction hash from bundler: {message}")]
TransactionHashError { message: String },
#[error("Failed to confirm transaction: {message}")]
#[serde(rename_all = "camelCase")]
ConfirmationError {
message: String,
inner_error: Option<EngineError>,
},
#[error("Receipt not yet available for transaction: {message}")]
#[serde(rename_all = "camelCase")]
ReceiptNotAvailable {
message: String,
transaction_hash: TxHash,
},
#[error("Transaction failed: {message}")]
TransactionFailed {
message: String,
receipt: TransactionReceipt,
},
#[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 Eip7702ConfirmationError {
fn from(error: TwmqError) -> Self {
Eip7702ConfirmationError::InternalError {
message: format!("Deserialization error for job data: {}", error),
}
}
}
impl UserCancellable for Eip7702ConfirmationError {
fn user_cancelled() -> Self {
Eip7702ConfirmationError::UserCancelled
}
}
// --- Handler ---
pub struct Eip7702ConfirmationHandler<CS>
where
CS: ChainService + Send + Sync + 'static,
{
pub chain_service: Arc<CS>,
pub webhook_queue: Arc<Queue<WebhookJobHandler>>,
pub transaction_registry: Arc<TransactionRegistry>,
}
impl<CS> ExecutorStage for Eip7702ConfirmationHandler<CS>
where
CS: ChainService + Send + Sync + 'static,
{
fn executor_name() -> &'static str {
"eip7702"
}
fn stage_name() -> &'static str {
"confirm"
}
}
impl<CS> WebhookCapable for Eip7702ConfirmationHandler<CS>
where
CS: ChainService + Send + Sync + 'static,
{
fn webhook_queue(&self) -> &Arc<Queue<WebhookJobHandler>> {
&self.webhook_queue
}
}
impl<CS> twmq::DurableExecution for Eip7702ConfirmationHandler<CS>
where
CS: ChainService + Send + Sync + 'static,
{
type Output = Eip7702ConfirmationResult;
type ErrorData = Eip7702ConfirmationError;
type JobData = Eip7702ConfirmationJobData;
#[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| Eip7702ConfirmationError::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| Eip7702ConfirmationError::InvalidRpcCredentials {
message: e.to_string(),
})
.map_err_fail()?;
let chain = chain.with_new_default_headers(chain_auth_headers);
// 2. Get transaction hash from bundler
let transaction_hash_str = chain
.bundler_client()
.tw_get_transaction_hash(&job_data.bundler_transaction_id)
.await
.map_err(|e| Eip7702ConfirmationError::TransactionHashError {
message: e.to_string(),
})
.map_err_fail()?;
let transaction_hash = match transaction_hash_str {
Some(hash) => hash.parse::<TxHash>().map_err(|e| {
Eip7702ConfirmationError::TransactionHashError {
message: format!("Invalid transaction hash format: {}", e),
}
.fail()
})?,
None => {
return Err(Eip7702ConfirmationError::TransactionHashError {
message: "Transaction not found".to_string(),
})
.map_err_nack(Some(Duration::from_secs(2)), RequeuePosition::Last);
}
};
tracing::debug!(
transaction_hash = ?transaction_hash,
bundler_transaction_id = job_data.bundler_transaction_id,
"Got transaction hash from bundler"
);
// 3. Wait for transaction confirmation
let receipt = chain
.provider()
.get_transaction_receipt(transaction_hash)
.await
.map_err(|e| {
// If transaction not found, nack and retry
Eip7702ConfirmationError::ConfirmationError {
message: format!("Failed to get transaction receipt: {}", e),
inner_error: Some(e.to_engine_error(&chain)),
}
.nack(Some(Duration::from_secs(5)), RequeuePosition::Last)
})?;
let receipt = match receipt {
Some(receipt) => receipt,
None => {
// Transaction not mined yet, nack and retry
return Err(Eip7702ConfirmationError::ReceiptNotAvailable {
message: "Transaction not mined yet".to_string(),
transaction_hash,
})
.map_err_nack(Some(Duration::from_secs(2)), RequeuePosition::Last);
}
};
// 4. Check transaction status
let success = receipt.status();
if !success {
return Err(Eip7702ConfirmationError::TransactionFailed {
message: "Transaction reverted".to_string(),
receipt,
})
.map_err_fail();
}
tracing::debug!(
transaction_hash = ?transaction_hash,
block_number = receipt.block_number,
gas_used = ?receipt.gas_used,
"Transaction confirmed successfully"
);
Ok(Eip7702ConfirmationResult {
transaction_id: job_data.transaction_id.clone(),
transaction_hash,
receipt,
eoa_address: job_data.eoa_address,
})
}
async fn on_success(
&self,
job: &BorrowedJob<Eip7702ConfirmationJobData>,
success_data: SuccessHookData<'_, Eip7702ConfirmationResult>,
tx: &mut TransactionContext<'_>,
) {
// Remove transaction from registry since confirmation is complete
self.transaction_registry
.add_remove_command(tx.pipeline(), &job.job.data.transaction_id);
// 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<Eip7702ConfirmationJobData>,
nack_data: NackHookData<'_, Eip7702ConfirmationError>,
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<Eip7702ConfirmationJobData>,
fail_data: FailHookData<'_, Eip7702ConfirmationError>,
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 confirmation 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 ---