newton-chainio 0.5.2

newton prover chainio
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! Policy Client

use crate::error::ChainIoError;
use alloy::{
    primitives::{Address, Bytes, B256, U256},
    rpc::types::TransactionReceipt,
    sol_types::SolValue,
};
use eigensdk::common::{get_provider, get_signer};
use newton_core::{
    mock_newton_policy_client::{
        INewtonProverTaskManager::{Task as MockTask, TaskResponse as MockTaskResponse},
        MockNewtonPolicyClient, NewtonMessage,
    },
    newton_policy_client::{INewtonPolicy, NewtonPolicyClient},
    newton_prover_task_manager::{
        INewtonPolicy as IINewtonPolicy,
        INewtonProverTaskManager::{Task, TaskResponse as ContractTaskResponse},
        NewtonProverTaskManager,
    },
};

use tracing::info;

/// PolicyClientController struct
#[derive(Debug)]
pub struct PolicyClientController {
    rpc_url: String,
    signer: String,
    client_address: Address,
}

impl PolicyClientController {
    /// new instance
    pub fn new(signer: String, rpc_url: String, client_address: Address) -> Self {
        PolicyClientController {
            signer,
            rpc_url,
            client_address,
        }
    }

    /// Get the policy address associated with this client
    pub async fn get_policy_address(&self) -> Result<Address, ChainIoError> {
        let provider = get_provider(&self.rpc_url);
        let policy_client = NewtonPolicyClient::new(self.client_address, provider);

        info!("Getting policy address for client: {}", self.client_address);

        let get_policy_address_call = policy_client.getPolicyAddress();

        let get_policy_address_result = get_policy_address_call.call().await;

        match get_policy_address_result {
            Ok(result) => {
                let policy_address = result;
                info!("Policy address for client {}: {}", self.client_address, policy_address);
                Ok(policy_address)
            }
            Err(e) => Err(ChainIoError::ContractError(e)),
        }
    }

    /// Get the policy configuration for this client
    pub async fn get_policy_config(&self) -> Result<INewtonPolicy::PolicyConfig, ChainIoError> {
        get_policy_config_for_client(self.client_address, self.rpc_url.clone())
            .await
            .map(|config| INewtonPolicy::PolicyConfig {
                policyParams: config.policyParams,
                expireAfter: config.expireAfter,
            })
    }

    /// Get the policy ID for this client
    pub async fn get_policy_id(&self) -> Result<B256, ChainIoError> {
        get_policy_id_for_client(self.client_address, self.rpc_url.clone()).await
    }

    /// Get the Newton Policy Task Manager address
    pub async fn get_newton_policy_task_manager(&self) -> Result<Address, ChainIoError> {
        let provider = get_provider(&self.rpc_url);
        let policy_client = NewtonPolicyClient::new(self.client_address, provider);

        info!(
            "Getting Newton Policy Task Manager address for client: {}",
            self.client_address
        );

        let get_task_manager_call = policy_client.getNewtonPolicyTaskManager();

        let get_task_manager_result = get_task_manager_call.call().await;

        match get_task_manager_result {
            Ok(result) => {
                let task_manager_address = result;
                info!(
                    "Newton Policy Task Manager address for client {}: {}",
                    self.client_address, task_manager_address
                );
                Ok(task_manager_address)
            }
            Err(e) => Err(ChainIoError::ContractError(e)),
        }
    }

    /// Set the policy configuration for this client
    pub async fn set_policy(
        &self,
        policy_params: Bytes,
        expire_after: u32,
    ) -> Result<(TransactionReceipt, B256), ChainIoError> {
        let wallet = get_signer(&self.signer, &self.rpc_url);
        let policy_client = NewtonPolicyClient::new(self.client_address, wallet);

        let policy_config = INewtonPolicy::PolicyConfig {
            policyParams: policy_params.clone(),
            expireAfter: expire_after,
        };

        info!(
            "Setting policy for client: {} with params: {}, expire_after: {}",
            self.client_address,
            hex!(policy_params),
            expire_after
        );

        let set_policy_call = policy_client.setPolicy(policy_config);

        let set_policy_result = set_policy_call.send().await;

        match set_policy_result {
            Ok(set_policy) => {
                let receipt_result = set_policy.get_receipt().await;

                match receipt_result {
                    Ok(receipt) => {
                        // Get the policy ID after setting
                        let policy_id = self.get_policy_id().await?;

                        info!(
                            "Policy set successfully for client: {}, policy_id: {}",
                            self.client_address, policy_id
                        );
                        Ok((receipt, policy_id))
                    }
                    Err(e) => Err(ChainIoError::AlloyProviderError(e)),
                }
            }
            Err(e) => Err(ChainIoError::ContractError(e)),
        }
    }

    /// Set the policy client owner
    pub async fn set_policy_client_owner(&self, new_owner: Address) -> Result<TransactionReceipt, ChainIoError> {
        let wallet = get_signer(&self.signer, &self.rpc_url);
        let policy_client = NewtonPolicyClient::new(self.client_address, wallet);

        info!(
            "Setting policy client owner for client: {} to: {}",
            self.client_address, new_owner
        );

        let set_owner_call = policy_client.setPolicyClientOwner(new_owner);

        let set_owner_result = set_owner_call.send().await;

        match set_owner_result {
            Ok(set_owner) => {
                let receipt_result = set_owner.get_receipt().await;
                match receipt_result {
                    Ok(receipt) => {
                        info!(
                            "Policy client owner set successfully for client: {} to: {}",
                            self.client_address, new_owner
                        );
                        Ok(receipt)
                    }
                    Err(e) => Err(ChainIoError::AlloyProviderError(e)),
                }
            }
            Err(e) => Err(ChainIoError::ContractError(e)),
        }
    }
}

/// MockPolicyClientController struct for mock policy client operations
#[derive(Debug)]
pub struct MockPolicyClientController {
    rpc_url: String,
    signer: String,
    client_address: Address,
}

impl MockPolicyClientController {
    /// new instance
    pub fn new(signer: String, rpc_url: String, client_address: Address) -> Self {
        MockPolicyClientController {
            signer,
            rpc_url,
            client_address,
        }
    }

    /// Get the balance of a token for this client
    pub async fn balance_of(&self, token: Address) -> Result<U256, ChainIoError> {
        let provider = get_provider(&self.rpc_url);
        let mock_policy_client = MockNewtonPolicyClient::new(self.client_address, provider);

        info!(
            "Getting balance for token: {} for client: {}",
            token, self.client_address
        );

        let balance_of_call = mock_policy_client.balanceOf(token);

        let balance_of_result = balance_of_call.call().await;

        match balance_of_result {
            Ok(result) => {
                let balance = result;
                info!(
                    "Balance for token {} for client {}: {}",
                    token, self.client_address, balance
                );
                Ok(balance)
            }
            Err(e) => Err(ChainIoError::ContractError(e)),
        }
    }

    /// Deposit tokens to this client
    pub async fn deposit(&self, token: Address, token_amount: U256) -> Result<TransactionReceipt, ChainIoError> {
        let wallet = get_signer(&self.signer, &self.rpc_url);
        let mock_policy_client = MockNewtonPolicyClient::new(self.client_address, wallet);

        info!(
            "Depositing {} tokens of {} for client: {}",
            token_amount, token, self.client_address
        );

        let deposit_call = mock_policy_client.deposit(token, token_amount);

        let deposit_result = deposit_call.send().await;

        match deposit_result {
            Ok(deposit) => {
                let receipt_result = deposit.get_receipt().await;
                match receipt_result {
                    Ok(receipt) => {
                        info!(
                            "Deposit successful for client: {} - {} tokens of {}",
                            self.client_address, token_amount, token
                        );
                        Ok(receipt)
                    }
                    Err(e) => Err(ChainIoError::AlloyProviderError(e)),
                }
            }
            Err(e) => Err(ChainIoError::ContractError(e)),
        }
    }

    /// Withdraw tokens from this client
    pub async fn withdraw(&self, token: Address, token_amount: U256) -> Result<TransactionReceipt, ChainIoError> {
        let wallet = get_signer(&self.signer, &self.rpc_url);
        let mock_policy_client = MockNewtonPolicyClient::new(self.client_address, wallet);

        info!(
            "Withdrawing {} tokens of {} for client: {}",
            token_amount, token, self.client_address
        );

        let withdraw_call = mock_policy_client.withdraw(token, token_amount);

        let withdraw_result = withdraw_call.send().await;

        match withdraw_result {
            Ok(withdraw) => {
                let receipt_result = withdraw.get_receipt().await;
                match receipt_result {
                    Ok(receipt) => {
                        info!(
                            "Withdrawal successful for client: {} - {} tokens of {}",
                            self.client_address, token_amount, token
                        );
                        Ok(receipt)
                    }
                    Err(e) => Err(ChainIoError::AlloyProviderError(e)),
                }
            }
            Err(e) => Err(ChainIoError::ContractError(e)),
        }
    }

    /// Execute an intent using an attestation
    pub async fn execute_intent(
        &self,
        attestation: NewtonMessage::Attestation,
    ) -> Result<TransactionReceipt, ChainIoError> {
        let wallet = get_signer(&self.signer, &self.rpc_url);
        let mock_policy_client = MockNewtonPolicyClient::new(self.client_address, wallet);

        info!(
            "Executing intent for client: {} with task_id: {}, policy_id: {}",
            self.client_address, attestation.taskId, attestation.policyId
        );

        let execute_intent_call = mock_policy_client.executeIntent(attestation);

        let execute_intent_result = execute_intent_call.send().await;

        match execute_intent_result {
            Ok(execute_intent) => {
                let receipt_result = execute_intent.get_receipt().await;
                match receipt_result {
                    Ok(receipt) => {
                        info!("Intent executed successfully for client: {}", self.client_address);
                        Ok(receipt)
                    }
                    Err(e) => Err(ChainIoError::AlloyProviderError(e)),
                }
            }
            Err(e) => Err(ChainIoError::ContractError(e)),
        }
    }

    /// Get the owner of this mock policy client
    pub async fn owner(&self) -> Result<Address, ChainIoError> {
        let provider = get_provider(&self.rpc_url);
        let mock_policy_client = MockNewtonPolicyClient::new(self.client_address, provider);

        info!("Getting owner for mock client: {}", self.client_address);

        let owner_call = mock_policy_client.owner();

        let owner_result = owner_call.call().await;

        match owner_result {
            Ok(result) => {
                let owner = result;
                info!("Owner for mock client {}: {}", self.client_address, owner);
                Ok(owner)
            }
            Err(e) => Err(ChainIoError::ContractError(e)),
        }
    }

    /// Set the owner of this mock policy client
    pub async fn set_owner(&self, new_owner: Address) -> Result<TransactionReceipt, ChainIoError> {
        let wallet = get_signer(&self.signer, &self.rpc_url);
        let mock_policy_client = MockNewtonPolicyClient::new(self.client_address, wallet);

        info!(
            "Setting owner for mock client: {} to: {}",
            self.client_address, new_owner
        );

        let set_owner_call = mock_policy_client.setOwner(new_owner);

        let set_owner_result = set_owner_call.send().await;

        match set_owner_result {
            Ok(set_owner) => {
                let receipt_result = set_owner.get_receipt().await;
                match receipt_result {
                    Ok(receipt) => {
                        info!(
                            "Owner set successfully for mock client: {} to: {}",
                            self.client_address, new_owner
                        );
                        Ok(receipt)
                    }
                    Err(e) => Err(ChainIoError::AlloyProviderError(e)),
                }
            }
            Err(e) => Err(ChainIoError::ContractError(e)),
        }
    }

    /// Execute intent using direct attestation validation (on-chain signature verification).
    ///
    /// Calls `validateAttestationDirect` through the policy client contract, which
    /// is required because the TaskManager enforces `msg.sender == task.policyClient`.
    ///
    /// # Arguments
    /// * `task_manager_address` - Address of the NewtonProverTaskManager contract (unused, kept for API compatibility)
    /// * `task` - The Task struct
    /// * `task_response` - The TaskResponse struct (contract format)
    /// * `signature_data` - ABI-encoded signature data (NonSignerStakesAndSignature or BN254Certificate)
    pub async fn execute_intent_direct(
        &self,
        _task_manager_address: Address,
        task: Task,
        task_response: ContractTaskResponse,
        signature_data: Bytes,
    ) -> Result<bool, ChainIoError> {
        let wallet = get_signer(&self.signer, &self.rpc_url);
        let policy_client = MockNewtonPolicyClient::new(self.client_address, wallet);

        info!(
            "Executing validateAttestationDirect via policy client {} for task_id: {}",
            self.client_address, task_response.taskId
        );

        // ABI roundtrip to convert between structurally identical but type-incompatible
        // Task/TaskResponse from different generated modules
        let mock_task = MockTask::abi_decode(&task.abi_encode()).expect("Task ABI roundtrip");
        let mock_task_response =
            MockTaskResponse::abi_decode(&task_response.abi_encode()).expect("TaskResponse ABI roundtrip");

        let validate_call = policy_client.validateAttestationDirect(mock_task, mock_task_response, signature_data);

        let validate_result = validate_call.send().await;

        match validate_result {
            Ok(pending_tx) => {
                let receipt = pending_tx
                    .get_receipt()
                    .await
                    .map_err(ChainIoError::AlloyProviderError)?;

                if !receipt.status() {
                    tracing::error!(
                        tx_hash = %receipt.transaction_hash,
                        "validateAttestationDirect transaction reverted on-chain"
                    );
                    return Err(ChainIoError::TransactionReverted(receipt.transaction_hash));
                }

                info!(
                    "validateAttestationDirect executed successfully, tx_hash: {}",
                    receipt.transaction_hash
                );
                Ok(true)
            }
            Err(e) => {
                info!("validateAttestationDirect failed: {}", e);
                Err(ChainIoError::ContractError(e))
            }
        }
    }
}

// Standalone functions for policy client operations

/// Get the policy address for a given policy client address
pub async fn get_policy_address_for_client(client_address: Address, rpc_url: String) -> Result<Address, ChainIoError> {
    let provider = get_provider(&rpc_url);
    let policy_client = NewtonPolicyClient::new(client_address, provider);

    info!("Getting policy address for client: {}", client_address);

    let get_policy_address_call = policy_client.getPolicyAddress();

    let get_policy_address_result = get_policy_address_call.call().await;

    match get_policy_address_result {
        Ok(result) => {
            let policy_address = result;
            info!("Policy address for client {}: {}", client_address, policy_address);
            Ok(policy_address)
        }
        Err(e) => Err(ChainIoError::ContractError(e)),
    }
}

/// Get the policy ID for a given policy client address
pub async fn get_policy_id_for_client(client_address: Address, rpc_url: String) -> Result<B256, ChainIoError> {
    let provider = get_provider(&rpc_url);
    let policy_client = NewtonPolicyClient::new(client_address, provider);

    info!("Getting policy ID for client: {}", client_address);

    let get_policy_id_call = policy_client.getPolicyId();

    let get_policy_id_result = get_policy_id_call.call().await;

    match get_policy_id_result {
        Ok(result) => {
            let policy_id = result;
            info!("Policy ID for client {}: {}", client_address, policy_id);
            Ok(policy_id)
        }
        Err(e) => Err(ChainIoError::ContractError(e)),
    }
}

/// Get the policy configuration for a given policy client address
pub async fn get_policy_config_for_client(
    client_address: Address,
    rpc_url: String,
) -> Result<IINewtonPolicy::PolicyConfig, ChainIoError> {
    let provider = get_provider(&rpc_url);
    let policy_client = NewtonPolicyClient::new(client_address, provider);

    info!("Getting policy config for client: {}", client_address);

    let get_policy_config_call = policy_client.getPolicyConfig();

    let get_policy_config_result = get_policy_config_call.call().await;

    match get_policy_config_result {
        Ok(result) => {
            let policy_config = result;
            info!(
                "Policy config for client {}: params: {}, expire_after: {}",
                client_address,
                hex!(policy_config.policyParams.clone()),
                policy_config.expireAfter
            );
            Ok(IINewtonPolicy::PolicyConfig {
                policyParams: policy_config.policyParams,
                expireAfter: policy_config.expireAfter,
            })
        }
        Err(e) => Err(ChainIoError::ContractError(e)),
    }
}

/// Get the PolicyConfig for a given policyId on a specific policy contract.
///
/// This calls `NewtonPolicy.getPolicyConfig(policyId)` directly.
/// The policyId pins the config to a specific generation — the returned
/// config is consensus-safe for caching keyed by policyId.
pub async fn get_policy_config_by_id(
    policy_address: Address,
    policy_id: B256,
    rpc_url: &str,
) -> Result<newton_core::newton_prover_task_manager::INewtonPolicy::PolicyConfig, ChainIoError> {
    use newton_core::newton_policy::NewtonPolicy;

    let provider = get_provider(rpc_url);
    let policy = NewtonPolicy::new(policy_address, provider);

    let config = policy
        .getPolicyConfig(policy_id)
        .call()
        .await
        .map_err(ChainIoError::ContractError)?;

    Ok(newton_core::newton_prover_task_manager::INewtonPolicy::PolicyConfig {
        policyParams: config.policyParams,
        expireAfter: config.expireAfter,
    })
}