nexus-sdk 2.0.0

Rust SDK for Nexus protocol types, RPC access, and transaction construction.
Documentation
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
//! Stateful scheduling operations exposed through [`NexusClient`].
//!
//! A [`Scheduler`] creates Tasks and returns handles for later mutations and
//! object inspection. Scheduling is the only request model. Runtime execution
//! objects appear only after an occurrence is dispatched.
//!
//! [`NexusClient`]: crate::nexus::client::NexusClient

mod occurrence;
pub(crate) mod resolve;
mod task;

use crate::{
    events::NexusEventKind,
    move_bindings::{self, scheduler::task::TaskPointer as MoveTaskPointer},
    nexus::{client::NexusClient, signer::ExecutedTransaction},
    scheduler::{
        OccurrenceRef,
        OccurrenceSource,
        Schedule,
        ScheduleDelta,
        ScheduledOccurrence,
        SchedulerError,
        TaskMutationReceipt,
        TaskPointer,
        TaskPointerPage,
        TaskSpec,
        TransactionReference,
        WithdrawalReason,
        WithdrawnOccurrence,
    },
    sui,
    transactions::scheduler::{compile_create_task_ptb, compile_schedule_task_ptb},
    types::{NexusContext, PackageRole},
};
pub use {occurrence::OccurrenceHandle, task::TaskHandle};

/// Scheduling facade owned by one configured [`NexusClient`].
///
/// Cloning this value is inexpensive. Every method retains the deployment,
/// signer, gas, and transport configuration of its client.
#[derive(Clone)]
pub struct Scheduler {
    pub(super) client: NexusClient,
}

impl Scheduler {
    async fn creator_context(
        &self,
        scheduler_package: sui::types::Address,
    ) -> Result<std::sync::Arc<NexusContext>, SchedulerError> {
        self.client
            .context_for_creator(scheduler_package, PackageRole::Scheduler, &[])
            .await
            .map_err(SchedulerError::from)
    }

    /// Validates the authored input shape against the selected authoritative DAG.
    ///
    /// This preflight performs no transaction submission. Task creation and scheduling repeat the
    /// check during final preparation so a caller cannot rely on a stale snapshot.
    ///
    /// # Errors
    ///
    /// Returns [`SchedulerError`] when the Task is invalid, the selected DAG cannot be read, or the
    /// entry group and input ports do not exactly match that DAG.
    pub async fn preflight_task_inputs(
        &self,
        scheduler_package: sui::types::Address,
        task: &TaskSpec,
    ) -> Result<(), SchedulerError> {
        let context = self.creator_context(scheduler_package).await?;
        resolve::preflight_task_inputs(&self.client, &context, task)
            .await
            .map(|_| ())
    }

    /// Creates and shares an empty Task.
    ///
    /// Use [`Self::schedule_task`] when the creation transaction must also add
    /// one or more occurrences.
    ///
    /// # Errors
    ///
    /// Returns [`SchedulerError`] when the Task is invalid, request
    /// preparation fails, or the transaction is not confirmed.
    pub async fn create_task(
        &self,
        scheduler_package: sui::types::Address,
        task: TaskSpec,
    ) -> Result<TaskMutationReceipt, SchedulerError> {
        let context = self.creator_context(scheduler_package).await?;
        let sender = self.client.owner().map_err(SchedulerError::from)?;
        let prepared = resolve::prepare_task(&self.client, &context, &task).await?;
        let transaction = compile_create_task_ptb(&context, &prepared, sender)?;
        let executed = self
            .client
            .submit_transaction(transaction, sender)
            .await
            .map_err(SchedulerError::from)?;
        let task_id = created_task_id(&executed)?;
        mutation_receipt(executed, task_id)
    }

    /// Creates, schedules, and shares one Task atomically.
    ///
    /// The Schedule may combine standalone occurrences and one recurrence.
    ///
    /// # Errors
    ///
    /// Returns [`SchedulerError`] when the Task or Schedule is invalid,
    /// including when the Schedule is empty, or when submission fails.
    pub async fn schedule_task(
        &self,
        scheduler_package: sui::types::Address,
        task: TaskSpec,
        schedule: Schedule,
    ) -> Result<TaskMutationReceipt, SchedulerError> {
        schedule.validate_for_task_creation()?;
        let context = self.creator_context(scheduler_package).await?;
        let sender = self.client.owner().map_err(SchedulerError::from)?;
        let prepared_task = resolve::prepare_task(&self.client, &context, &task).await?;
        let prepared_schedule = resolve::prepare_schedule(&self.client, &schedule).await?;
        let transaction =
            compile_schedule_task_ptb(&context, &prepared_task, &prepared_schedule, sender)?;
        let executed = self
            .client
            .submit_transaction(transaction, sender)
            .await
            .map_err(SchedulerError::from)?;
        let task_id = created_task_id(&executed)?;
        mutation_receipt(executed, task_id)
    }

    /// Returns a stateful handle for one Task identifier.
    pub fn task(&self, task_id: sui::types::Address) -> TaskHandle {
        TaskHandle::new(self.client.clone(), task_id)
    }

    /// Reads one RPC page of [`TaskPointer`] objects owned by the signer.
    ///
    /// The cursor is opaque and may be passed unchanged from
    /// [`TaskPointerPage::next_cursor`].
    ///
    /// # Errors
    ///
    /// Returns [`SchedulerError`] when the client has no signer, `limit` is
    /// zero, the page cannot be decoded, or chain data violates pointer
    /// identity.
    pub async fn task_pointers(
        &self,
        scheduler_package: sui::types::Address,
        cursor: Option<Vec<u8>>,
        limit: usize,
    ) -> Result<TaskPointerPage, SchedulerError> {
        if limit == 0 {
            return Err(SchedulerError::InvalidRequest {
                message: "Task pointer page limit must be greater than zero".to_owned(),
            });
        }
        let context = self
            .client
            .context_for_creator(scheduler_package, PackageRole::Scheduler, &[])
            .await
            .map_err(SchedulerError::from)?;
        let owner = self.client.owner().map_err(SchedulerError::from)?;
        let object_type = move_bindings::struct_tag::<MoveTaskPointer>(&context);
        let page = self
            .client
            .crawler()
            .get_owned_object_page::<MoveTaskPointer>(owner, object_type, cursor, limit)
            .await
            .map_err(SchedulerError::transport)?;
        let (objects, next_cursor) = page.into_parts();
        let mut pointers = Vec::with_capacity(objects.len());
        for object in objects {
            let embedded_id = object.data.id.id.bytes;
            if embedded_id != object.object_id {
                return Err(SchedulerError::InconsistentChainState {
                    message: format!(
                        "TaskPointer object '{}' contains UID '{}'",
                        object.object_id, embedded_id
                    ),
                });
            }
            pointers.push(TaskPointer::new(
                object.object_id,
                object.data.task_id.bytes,
            ));
        }
        Ok(TaskPointerPage::new(pointers, next_cursor))
    }
}

pub(super) fn mutation_receipt(
    executed: ExecutedTransaction,
    task_id: sui::types::Address,
) -> Result<TaskMutationReceipt, SchedulerError> {
    let mut scheduled = Vec::new();
    let mut withdrawn = Vec::new();
    let mut advertised = None;

    for event in &executed.events {
        if let Some(observed_task_id) = scheduler_event_task_id(&event.data) {
            if observed_task_id != task_id {
                return Err(SchedulerError::Confirmation {
                    message: format!(
                        "transaction for Task '{task_id}' contained a scheduler event for Task \
                         '{observed_task_id}'"
                    ),
                });
            }
        }

        match &event.data {
            NexusEventKind::OccurrenceAdvertised(event) => {
                advertised = Some(OccurrenceRef::new(task_id, event.occurrence_id));
            }
            NexusEventKind::OccurrenceScheduled(event) => {
                scheduled.push(ScheduledOccurrence::new(
                    OccurrenceRef::new(task_id, event.occurrence_id),
                    event.start_time_ms,
                    event.deadline_ms.copied_option(),
                    event.priority_fee_percentage,
                    occurrence_source(event.source),
                ));
            }
            NexusEventKind::OccurrenceWithdrawn(event) => {
                withdrawn.push(WithdrawnOccurrence::new(
                    OccurrenceRef::new(task_id, event.occurrence_id),
                    withdrawal_reason(event.reason),
                ));
            }
            _ => {}
        }
    }

    Ok(TaskMutationReceipt::new(
        TransactionReference::new(executed.digest, executed.checkpoint),
        task_id,
        ScheduleDelta::new(scheduled, withdrawn, advertised),
    ))
}

/// Produces a [`TaskMutationReceipt`] from one exact settlement event.
///
/// The event proves the transition because a successful transaction may be a no op.
pub(super) fn settlement_receipt(
    executed: ExecutedTransaction,
    occurrence: OccurrenceRef,
    execution_id: sui::types::Address,
) -> Result<TaskMutationReceipt, SchedulerError> {
    let mut settlements = executed
        .events
        .iter()
        .filter_map(|event| match &event.data {
            NexusEventKind::OccurrenceSettled(settled) => Some(settled),
            _ => None,
        });
    let Some(settled) = settlements.next() else {
        return Err(SchedulerError::Confirmation {
            message: format!(
                "settlement transaction for occurrence '{}:{}' did not emit OccurrenceSettled",
                occurrence.task_id(),
                occurrence.occurrence_id(),
            ),
        });
    };
    if settlements.next().is_some() {
        return Err(SchedulerError::Confirmation {
            message: format!(
                "settlement transaction for occurrence '{}:{}' emitted more than one \
                 OccurrenceSettled event",
                occurrence.task_id(),
                occurrence.occurrence_id(),
            ),
        });
    }
    if settled.task_id.bytes != occurrence.task_id()
        || settled.occurrence_id != occurrence.occurrence_id()
        || settled.execution_id.bytes != execution_id
    {
        return Err(SchedulerError::Confirmation {
            message: format!(
                "settlement transaction for occurrence '{}:{}' and runtime object \
                 '{execution_id}' confirmed occurrence '{}:{}' and runtime object '{}'",
                occurrence.task_id(),
                occurrence.occurrence_id(),
                settled.task_id.bytes,
                settled.occurrence_id,
                settled.execution_id.bytes,
            ),
        });
    }

    mutation_receipt(executed, occurrence.task_id())
}

fn created_task_id(executed: &ExecutedTransaction) -> Result<sui::types::Address, SchedulerError> {
    let mut task_ids = executed
        .events
        .iter()
        .filter_map(|event| match &event.data {
            NexusEventKind::TaskCreated(event) => Some(event.task_id.bytes),
            _ => None,
        });
    let Some(task_id) = task_ids.next() else {
        return Err(SchedulerError::Confirmation {
            message: "Task creation did not emit TaskCreated".to_owned(),
        });
    };
    if task_ids.next().is_some() {
        return Err(SchedulerError::Confirmation {
            message: "Task creation emitted more than one Task identifier".to_owned(),
        });
    }
    Ok(task_id)
}

fn scheduler_event_task_id(event: &NexusEventKind) -> Option<sui::types::Address> {
    match event {
        NexusEventKind::OccurrenceAdvertised(event) => Some(event.task_id.bytes),
        NexusEventKind::OccurrenceDispatched(event) => Some(event.task_id.bytes),
        NexusEventKind::OccurrenceMissed(event) => Some(event.task_id.bytes),
        NexusEventKind::OccurrenceScheduled(event) => Some(event.task_id.bytes),
        NexusEventKind::OccurrenceSettled(event) => Some(event.task_id.bytes),
        NexusEventKind::OccurrenceWithdrawn(event) => Some(event.task_id.bytes),
        NexusEventKind::TaskCanceled(event) => Some(event.task_id.bytes),
        NexusEventKind::TaskClosed(event) => Some(event.task_id.bytes),
        NexusEventKind::TaskCreated(event) => Some(event.task_id.bytes),
        NexusEventKind::TaskPaused(event) => Some(event.task_id.bytes),
        NexusEventKind::TaskResumed(event) => Some(event.task_id.bytes),
        _ => None,
    }
}

pub(super) const fn occurrence_source(
    source: crate::move_bindings::scheduler::schedule::OccurrenceSource,
) -> OccurrenceSource {
    match source {
        crate::move_bindings::scheduler::schedule::OccurrenceSource::Standalone => {
            OccurrenceSource::Standalone
        }
        crate::move_bindings::scheduler::schedule::OccurrenceSource::Recurring { iteration } => {
            OccurrenceSource::Recurring { iteration }
        }
    }
}

pub(super) const fn withdrawal_reason(
    reason: crate::move_bindings::scheduler::schedule::OccurrenceWithdrawalReason,
) -> WithdrawalReason {
    match reason {
        crate::move_bindings::scheduler::schedule::OccurrenceWithdrawalReason::RecurrenceReplaced => {
            WithdrawalReason::RecurrenceReplaced
        }
        crate::move_bindings::scheduler::schedule::OccurrenceWithdrawalReason::RecurrenceCleared => {
            WithdrawalReason::RecurrenceCleared
        }
        crate::move_bindings::scheduler::schedule::OccurrenceWithdrawalReason::TaskCanceled => {
            WithdrawalReason::TaskCanceled
        }
        crate::move_bindings::scheduler::schedule::OccurrenceWithdrawalReason::TaskRejected => {
            WithdrawalReason::TaskRejected
        }
    }
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        crate::{
            events::NexusEvent,
            move_bindings::{
                move_std::option::Option as MoveOption,
                scheduler::{
                    schedule::{
                        OccurrenceSource as MoveOccurrenceSource,
                        OccurrenceWithdrawalReason,
                    },
                    scheduler as scheduler_binding,
                    task::{TaskController as MoveTaskController, TaskPointer as MoveTaskPointer},
                },
                sui_framework::object::{ID, UID},
            },
            test_utils::{nexus_mocks, sui_mocks},
        },
    };

    fn address(value: &'static str) -> sui::types::Address {
        sui::types::Address::from_static(value)
    }

    fn event(index: u64, data: NexusEventKind) -> NexusEvent {
        NexusEvent {
            id: (sui::types::Digest::new([9; 32]), index),
            emitting_package: address("0x1"),
            generics: Vec::new(),
            data,
            distribution: None,
        }
    }

    fn executed(events: Vec<NexusEventKind>) -> ExecutedTransaction {
        let digest = sui::types::Digest::new([9; 32]);
        ExecutedTransaction {
            effects: sui::types::TransactionEffectsV2 {
                status: sui::types::ExecutionStatus::Success,
                epoch: 1,
                gas_used: sui::types::GasCostSummary {
                    computation_cost: 0,
                    storage_cost: 0,
                    storage_rebate: 0,
                    non_refundable_storage_fee: 0,
                },
                transaction_digest: digest,
                gas_object_index: None,
                events_digest: None,
                dependencies: Vec::new(),
                lamport_version: 1,
                changed_objects: Vec::new(),
                unchanged_consensus_objects: Vec::new(),
                auxiliary_data_digest: None,
            },
            events: events
                .into_iter()
                .enumerate()
                .map(|(index, data)| event(index as u64, data))
                .collect(),
            objects: Vec::new(),
            digest,
            checkpoint: 14,
        }
    }

    fn task_created(task_id: sui::types::Address) -> NexusEventKind {
        NexusEventKind::TaskCreated(scheduler_binding::TaskCreatedEvent::new(
            ID::new(task_id),
            MoveTaskController::Address {
                pos0: address("0x52"),
            },
            ID::new(address("0x53")),
            0,
        ))
    }

    fn occurrence_settled(
        reference: OccurrenceRef,
        execution_id: sui::types::Address,
    ) -> NexusEventKind {
        NexusEventKind::OccurrenceSettled(scheduler_binding::OccurrenceSettledEvent::new(
            ID::new(reference.task_id()),
            reference.occurrence_id(),
            ID::new(execution_id),
            true,
        ))
    }

    #[test]
    fn settlement_receipt_requires_the_exact_confirmed_transition() {
        let task_id = address("0x50");
        let reference = OccurrenceRef::new(task_id, 8);
        let execution_id = address("0x51");

        for unconfirmed in [
            executed(Vec::new()),
            executed(vec![occurrence_settled(
                OccurrenceRef::new(task_id, 9),
                execution_id,
            )]),
            executed(vec![occurrence_settled(reference, address("0x52"))]),
            executed(vec![
                occurrence_settled(reference, execution_id),
                occurrence_settled(reference, execution_id),
            ]),
        ] {
            assert!(matches!(
                settlement_receipt(unconfirmed, reference, execution_id),
                Err(SchedulerError::Confirmation { .. })
            ));
        }

        let receipt = settlement_receipt(
            executed(vec![occurrence_settled(reference, execution_id)]),
            reference,
            execution_id,
        )
        .expect("exact settlement event confirms the transition");
        assert_eq!(receipt.task_id(), task_id);
        assert_eq!(receipt.transaction().checkpoint(), 14);
    }

    #[test]
    fn mutation_receipt_collects_the_confirmed_schedule_delta() {
        let task_id = address("0x51");
        let executed = executed(vec![
            task_created(task_id),
            NexusEventKind::OccurrenceScheduled(scheduler_binding::OccurrenceScheduledEvent::new(
                ID::new(task_id),
                1,
                100,
                MoveOption::from_option(Some(150)),
                20,
                MoveOccurrenceSource::Standalone,
            )),
            NexusEventKind::OccurrenceScheduled(scheduler_binding::OccurrenceScheduledEvent::new(
                ID::new(task_id),
                2,
                200,
                MoveOption::from_option(None),
                30,
                MoveOccurrenceSource::Recurring { iteration: 3 },
            )),
            NexusEventKind::OccurrenceAdvertised(
                scheduler_binding::OccurrenceAdvertisedEvent::new(
                    ID::new(task_id),
                    1,
                    100,
                    MoveOption::from_option(Some(150)),
                    20,
                ),
            ),
            NexusEventKind::OccurrenceWithdrawn(scheduler_binding::OccurrenceWithdrawnEvent::new(
                ID::new(task_id),
                1,
                OccurrenceWithdrawalReason::RecurrenceCleared,
            )),
        ]);

        assert_eq!(
            created_task_id(&executed).expect("one Task was created"),
            task_id
        );
        let receipt = mutation_receipt(executed, task_id).expect("events agree on Task identity");

        assert_eq!(receipt.task_id(), task_id);
        assert_eq!(receipt.transaction().checkpoint(), 14);
        assert_eq!(receipt.delta().scheduled().len(), 2);
        assert_eq!(
            receipt.delta().scheduled()[0].source(),
            OccurrenceSource::Standalone
        );
        assert_eq!(
            receipt.delta().scheduled()[1].source(),
            OccurrenceSource::Recurring { iteration: 3 }
        );
        assert_eq!(
            receipt.delta().withdrawn()[0].reason(),
            WithdrawalReason::RecurrenceCleared
        );
        assert_eq!(
            receipt.delta().advertised(),
            Some(OccurrenceRef::new(task_id, 1))
        );
    }

    #[test]
    fn confirmation_rejects_missing_duplicate_and_mismatched_task_identity() {
        assert!(matches!(
            created_task_id(&executed(Vec::new())),
            Err(SchedulerError::Confirmation { .. })
        ));

        let task_id = address("0x54");
        assert!(matches!(
            created_task_id(&executed(vec![
                task_created(task_id),
                task_created(task_id),
            ])),
            Err(SchedulerError::Confirmation { .. })
        ));

        let other_task = address("0x55");
        assert!(matches!(
            mutation_receipt(
                executed(vec![NexusEventKind::TaskPaused(
                    scheduler_binding::TaskPausedEvent::new(ID::new(other_task)),
                )]),
                task_id,
            ),
            Err(SchedulerError::Confirmation { .. })
        ));
    }

    #[test]
    fn scheduler_event_identity_covers_every_task_event() {
        let task_id = address("0x56");
        let execution_id = ID::new(address("0x57"));
        let events = [
            NexusEventKind::OccurrenceAdvertised(
                scheduler_binding::OccurrenceAdvertisedEvent::new(
                    ID::new(task_id),
                    1,
                    10,
                    MoveOption::from_option(None),
                    20,
                ),
            ),
            NexusEventKind::OccurrenceDispatched(
                scheduler_binding::OccurrenceDispatchedEvent::new(
                    ID::new(task_id),
                    1,
                    execution_id,
                    11,
                ),
            ),
            NexusEventKind::OccurrenceMissed(scheduler_binding::OccurrenceMissedEvent::new(
                ID::new(task_id),
                1,
                12,
            )),
            NexusEventKind::OccurrenceScheduled(scheduler_binding::OccurrenceScheduledEvent::new(
                ID::new(task_id),
                1,
                10,
                MoveOption::from_option(None),
                20,
                MoveOccurrenceSource::Standalone,
            )),
            NexusEventKind::OccurrenceSettled(scheduler_binding::OccurrenceSettledEvent::new(
                ID::new(task_id),
                1,
                execution_id,
                true,
            )),
            NexusEventKind::OccurrenceWithdrawn(scheduler_binding::OccurrenceWithdrawnEvent::new(
                ID::new(task_id),
                1,
                OccurrenceWithdrawalReason::TaskCanceled,
            )),
            NexusEventKind::TaskCanceled(scheduler_binding::TaskCanceledEvent::new(ID::new(
                task_id,
            ))),
            NexusEventKind::TaskClosed(scheduler_binding::TaskClosedEvent::new(ID::new(task_id))),
            task_created(task_id),
            NexusEventKind::TaskPaused(scheduler_binding::TaskPausedEvent::new(ID::new(task_id))),
            NexusEventKind::TaskResumed(scheduler_binding::TaskResumedEvent::new(ID::new(task_id))),
        ];

        for event in events {
            assert_eq!(scheduler_event_task_id(&event), Some(task_id));
        }
    }

    #[test]
    fn source_and_withdrawal_projections_cover_every_protocol_variant() {
        assert_eq!(
            occurrence_source(MoveOccurrenceSource::Standalone),
            OccurrenceSource::Standalone
        );
        assert_eq!(
            occurrence_source(MoveOccurrenceSource::Recurring { iteration: 4 }),
            OccurrenceSource::Recurring { iteration: 4 }
        );
        for (stored, projected) in [
            (
                OccurrenceWithdrawalReason::RecurrenceReplaced,
                WithdrawalReason::RecurrenceReplaced,
            ),
            (
                OccurrenceWithdrawalReason::RecurrenceCleared,
                WithdrawalReason::RecurrenceCleared,
            ),
            (
                OccurrenceWithdrawalReason::TaskCanceled,
                WithdrawalReason::TaskCanceled,
            ),
            (
                OccurrenceWithdrawalReason::TaskRejected,
                WithdrawalReason::TaskRejected,
            ),
        ] {
            assert_eq!(withdrawal_reason(stored), projected);
        }
    }

    #[tokio::test]
    async fn task_pointer_discovery_reaches_grpc_without_owned_coins() {
        let nexus_objects = sui_mocks::mock_nexus_context();
        let pointer_id = address("0x61");
        let task_id = address("0x62");
        let pointer_ref = sui_mocks::object_ref_for_id(pointer_id);
        let pointer_type = move_bindings::struct_tag::<MoveTaskPointer>(&nexus_objects);
        let expected_type = pointer_type.to_string();
        let request_cursor = Vec::from(&b"request-cursor"[..]);
        let response_cursor = Vec::from(&b"response-cursor"[..]);
        let mut ledger_service = sui_mocks::grpc::MockLedgerService::new();
        let mut package_service = sui_mocks::grpc::MockMovePackageService::new();
        let mut state_service = sui_mocks::grpc::MockStateService::new();
        sui_mocks::grpc::mock_nexus_package_graph(
            &mut ledger_service,
            &mut package_service,
            nexus_objects.packages(),
        );
        state_service
            .expect_list_owned_objects()
            .times(1)
            .return_once({
                let pointer_ref = pointer_ref.clone();
                let request_cursor = request_cursor.clone();
                let response_cursor = response_cursor.clone();
                move |request| {
                    let request = request.get_ref();
                    let owner = request
                        .owner
                        .as_deref()
                        .expect("address owner")
                        .parse::<sui::types::Address>()
                        .expect("valid address owner");
                    assert_eq!(request.object_type.as_deref(), Some(expected_type.as_str()));
                    assert_eq!(request.page_size, Some(7));
                    assert_eq!(
                        request.page_token.as_deref(),
                        Some(request_cursor.as_slice())
                    );

                    let pointer = MoveTaskPointer::new(UID::new(pointer_id), ID::new(task_id));
                    let mut object = sui::grpc::Object::default();
                    object.set_object_id(pointer_id);
                    object.set_owner(sui::types::Owner::Address(owner));
                    object.set_object_type(expected_type);
                    object.set_version(pointer_ref.version());
                    object.set_digest(*pointer_ref.digest());
                    let mut contents = sui::grpc::Bcs::default();
                    contents.set_value(bcs::to_bytes(&pointer).expect("pointer BCS"));
                    object.set_contents(contents);

                    let mut response = sui::grpc::ListOwnedObjectsResponse::default();
                    response.set_objects(vec![object]);
                    response.next_page_token = Some(response_cursor.into());
                    Ok(tonic::Response::new(response))
                }
            });
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger_service),
            package_service_mock: Some(package_service),
            state_service_mock: Some(state_service),
            ..Default::default()
        });
        let client = nexus_mocks::mock_nexus_client_without_coins(&nexus_objects, &rpc_url).await;

        let page = client
            .scheduler()
            .task_pointers(
                nexus_objects
                    .require_package(PackageRole::Scheduler)
                    .unwrap()
                    .storage_id,
                Some(request_cursor),
                7,
            )
            .await
            .expect("TaskPointer page");

        assert_eq!(
            page.task_pointers(),
            &[TaskPointer::new(pointer_id, task_id)]
        );
        assert_eq!(page.next_cursor(), Some(response_cursor.as_slice()));
    }
}