Skip to main content

canton_token/
scan.rs

1//! Splice Scan's HTTP API, asked directly or through a validator's scan-proxy.
2//!
3//! Scan is the service each Super Validator runs to publish what the DSO
4//! decided and what happened on the network: the DSO party, the Amulet rules,
5//! the mining rounds, traffic balances, the update history, snapshots of the
6//! active contracts. The paths and payloads here come from Splice's OpenAPI
7//! documents, `scan.yaml` and `scan-proxy.yaml` (vendored under
8//! `testdata/openapi/`), and the methods are named after what they return.
9//!
10//! # Two ways in
11//!
12//! - [`ScanClient::new`] asks a Scan itself, at `<scan>/api/scan`. It serves
13//!   everything here.
14//! - [`ScanClient::through_validator`] asks a validator's scan-proxy, at
15//!   `<validator>/api/validator`. The validator reads from several Super
16//!   Validators' Scans and answers when enough of them agree, and it
17//!   authenticates every request, so this route needs a token
18//!   ([`with_token`](ScanClient::with_token),
19//!   [`with_token_source`](ScanClient::with_token_source)). It serves the
20//!   part of the API a wallet or an application backend needs, not the
21//!   traffic, history and snapshot-page reads, which are refused before
22//!   anything is sent; of the snapshot reads it serves only
23//!   [`holdings_summary`](ScanClient::holdings_summary).
24//!
25//! A Scan asked directly is one Super Validator's word. This client does not
26//! compare several Scans; the scan-proxy is the route that does.
27//!
28//! # Why an application needs it
29//!
30//! Some choices take contracts the DSO owns: the `AmuletRules`, the open
31//! mining round, a provider's `FeaturedAppRight`. Creating a
32//! `TransferPreapproval` is one such choice. The submitting party does not
33//! see those contracts, so they are passed as disclosed contracts, and Scan
34//! is where they are published. [`ScanClient::amulet_rules`] and
35//! [`ScanClient::latest_open_mining_round`] return them with
36//! [`disclosed`](ContractWithState::disclosed), which is what a submission
37//! attaches. [`ScanClient::featured_app_right`] returns its contract without
38//! a synchronizer: disclose it on the rules' one, with
39//! [`ScanContract::disclosed`].
40//!
41//! # Splice versions
42//!
43//! Written against the documents of Splice 0.10.3. On an older Scan or
44//! validator: [`dso`](ScanClient::dso) falls back to the `/v0/dso` every
45//! release serves; the two snapshot page reads
46//! ([`acs_snapshot`](ScanClient::acs_snapshot),
47//! [`holdings_state`](ScanClient::holdings_state)) need Splice 0.7.5, which
48//! is where their `/v2` paths appeared;
49//! [`holdings_summary`](ScanClient::holdings_summary) needs 0.6.3. Everything
50//! else is served by Splice 0.6.0 and later.
51//!
52//! # Stability
53//!
54//! Splice tags each Scan endpoint `external` or `internal`. The external ones
55//! are its public API. The internal ones may change in any Splice release,
56//! and two of them are the only source of a contract an application may
57//! need: [`featured_app_right`](ScanClient::featured_app_right) and
58//! [`transfer_preapproval_by_party`](ScanClient::transfer_preapproval_by_party).
59//! Asked of a Scan directly, these are refused unless the client was built
60//! with [`with_internal_endpoints`](ScanClient::with_internal_endpoints),
61//! which is the caller accepting that. Through a validator's scan-proxy they
62//! are part of the proxy's own API and need no opt-in.
63//!
64//! [`amulet_rules`](ScanClient::amulet_rules) needs no opt-in either way:
65//! the external API publishes the rules with the rest of the DSO's contracts,
66//! and that is where a Scan is asked for them. With the opt-in it asks the
67//! internal endpoint, which returns the one contract and nothing else.
68//!
69//! Contract payloads, choice arguments and results stay JSON
70//! ([`serde_json::Value`]): they are Daml values of whatever template the
71//! contract has, in the compact encoding the Ledger JSON API uses.
72
73use std::collections::BTreeMap;
74use std::time::Duration;
75
76use base64::Engine as _;
77use canton_core::{Auth, Error, Result, TokenSource};
78use canton_daml::Timestamp;
79use canton_proto::com::daml::ledger::api::v2 as pb;
80use serde::{Deserialize, Serialize};
81use serde_json::Value;
82
83use crate::registry::{
84    ErrorResponse, MAX_RESPONSE_BYTES, read_body_from, read_error_body, transport_error, truncate,
85};
86
87/// How Scan is named in an error.
88const SCAN: &str = "Scan";
89
90/// How long to wait on a Scan that accepts the connection and then says
91/// nothing. `reqwest`'s own default is unbounded.
92const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
93
94/// The most contracts a history or snapshot page may ask for.
95const MAX_PAGE_SIZE: u32 = 1000;
96
97/// Where the client's base URL points.
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99enum Route {
100    /// A Scan: `<scan>/api/scan`, paths `/<version>/…`.
101    Scan,
102    /// A validator: `<validator>/api/validator`, paths
103    /// `/<version>/scan-proxy/…`.
104    ScanProxy,
105}
106
107/// A client for one Scan, or for one validator's scan-proxy.
108#[derive(Clone, Debug)]
109pub struct ScanClient {
110    base: reqwest::Url,
111    http: reqwest::Client,
112    auth: Auth,
113    route: Route,
114    internal_endpoints: bool,
115}
116
117/// A contract as Scan publishes it.
118#[derive(Clone, Debug, Deserialize)]
119#[non_exhaustive]
120pub struct ScanContract {
121    /// `<package id>:<Module>:<Entity>`.
122    pub template_id: String,
123    /// The contract id.
124    pub contract_id: String,
125    /// The contract's arguments, as Daml JSON.
126    pub payload: Value,
127    /// The created-event blob, base64 as JSON requires. This is what a
128    /// participant needs to accept the contract as disclosed.
129    pub created_event_blob: String,
130    /// When the contract was created.
131    pub created_at: String,
132}
133
134/// A contract and the synchronizer it is assigned to.
135#[derive(Clone, Debug, Deserialize)]
136#[non_exhaustive]
137pub struct ContractWithState {
138    /// The contract.
139    pub contract: ScanContract,
140    /// The synchronizer the contract is assigned to. `None` while it is
141    /// being reassigned from one synchronizer to another.
142    #[serde(rename = "domain_id", default)]
143    pub synchronizer_id: Option<String>,
144}
145
146impl ScanContract {
147    /// The contract as a disclosed contract for a gRPC submission, on
148    /// `synchronizer_id`.
149    ///
150    /// # Errors
151    /// [`Error::UnexpectedResponse`] if the template id is not
152    /// `<package>:<Module>:<Entity>` or the blob is not base64.
153    pub fn disclosed(&self, synchronizer_id: &str) -> Result<pb::DisclosedContract> {
154        let created_event_blob = base64::engine::general_purpose::STANDARD
155            .decode(&self.created_event_blob)
156            .map_err(|e| {
157                Error::UnexpectedResponse(format!(
158                    "Scan published contract `{}` with a created-event blob that is not \
159                     base64: {e}",
160                    self.contract_id
161                ))
162            })?;
163        Ok(pb::DisclosedContract {
164            template_id: Some(identifier(&self.template_id)?),
165            contract_id: self.contract_id.clone(),
166            created_event_blob,
167            synchronizer_id: synchronizer_id.to_string(),
168        })
169    }
170
171    /// The contract as a disclosed contract for the JSON Ledger API, which
172    /// takes the blob as the base64 Scan already sent.
173    #[must_use]
174    pub fn disclosed_json(&self, synchronizer_id: &str) -> Value {
175        serde_json::json!({
176            "templateId": self.template_id,
177            "contractId": self.contract_id,
178            "createdEventBlob": self.created_event_blob,
179            "synchronizerId": synchronizer_id,
180        })
181    }
182}
183
184impl ContractWithState {
185    /// The contract as a disclosed contract for a gRPC submission, on the
186    /// synchronizer it is assigned to.
187    ///
188    /// # Errors
189    /// As [`ScanContract::disclosed`], plus [`Error::Connection`], which is
190    /// retriable, if the contract is between synchronizers and so has none to
191    /// be disclosed on. That passes in seconds.
192    pub fn disclosed(&self) -> Result<pb::DisclosedContract> {
193        self.contract.disclosed(self.assigned()?)
194    }
195
196    /// The contract as a disclosed contract for the JSON Ledger API.
197    ///
198    /// # Errors
199    /// [`Error::Connection`] if the contract is between synchronizers.
200    pub fn disclosed_json(&self) -> Result<Value> {
201        Ok(self.contract.disclosed_json(self.assigned()?))
202    }
203
204    fn assigned(&self) -> Result<&str> {
205        self.synchronizer_id.as_deref().ok_or_else(|| {
206            Error::Connection(format!(
207                "contract `{}` is being reassigned between synchronizers, so there is none to \
208                 disclose it on yet; retry shortly",
209                self.contract.contract_id
210            ))
211        })
212    }
213}
214
215/// `<package>:<Module>:<Entity>` as the Ledger API's three fields. A module
216/// name has dots and never colons, so exactly three parts is the only
217/// well-formed shape.
218fn identifier(template_id: &str) -> Result<pb::Identifier> {
219    let mut parts = template_id.split(':');
220    match (parts.next(), parts.next(), parts.next(), parts.next()) {
221        (Some(package_id), Some(module_name), Some(entity_name), None)
222            if !package_id.is_empty() && !module_name.is_empty() && !entity_name.is_empty() =>
223        {
224            Ok(pb::Identifier {
225                package_id: package_id.to_string(),
226                module_name: module_name.to_string(),
227                entity_name: entity_name.to_string(),
228            })
229        }
230        _ => Err(Error::UnexpectedResponse(format!(
231            "Scan published a contract with template id `{template_id}`, which is not \
232             `<package>:<Module>:<Entity>`"
233        ))),
234    }
235}
236
237/// What the DSO is and the contracts that say how it runs.
238#[derive(Clone, Debug, Deserialize)]
239#[non_exhaustive]
240pub struct DsoInfo {
241    /// The party that represents the DSO as a whole.
242    pub dso_party_id: String,
243    /// How many Super Validators must agree for a vote to pass.
244    pub voting_threshold: u32,
245    /// The `OpenMiningRound` with the highest round number. It may not have
246    /// opened yet: see [`MiningRounds::latest_open`] for the one to use.
247    pub latest_mining_round: ContractWithState,
248    /// The `AmuletRules` contract.
249    pub amulet_rules: ContractWithState,
250    /// The `DsoRules` contract.
251    pub dso_rules: ContractWithState,
252    /// One `SvNodeState` contract per Super Validator in the DSO rules.
253    pub sv_node_states: Vec<ContractWithState>,
254    /// The round the network started from, where Scan reports it.
255    #[serde(default)]
256    pub initial_round: Option<String>,
257}
258
259/// The Scans the Super Validators run for one synchronizer.
260#[derive(Clone, Debug, Deserialize)]
261#[non_exhaustive]
262pub struct SynchronizerScans {
263    /// The synchronizer.
264    #[serde(rename = "domainId")]
265    pub synchronizer_id: String,
266    /// Its Scans.
267    pub scans: Vec<ScanInfo>,
268}
269
270/// One Super Validator's Scan.
271#[derive(Clone, Debug, Deserialize)]
272#[serde(rename_all = "camelCase")]
273#[non_exhaustive]
274pub struct ScanInfo {
275    /// The Scan's public URL, without `/api/scan`.
276    pub public_url: String,
277    /// The Super Validator that runs it.
278    pub sv_name: String,
279}
280
281/// The mining rounds that rewards can be registered in, and the ones whose
282/// rewards are being computed.
283#[derive(Clone, Debug)]
284#[non_exhaustive]
285pub struct MiningRounds {
286    /// `OpenMiningRound` contracts. Several are open at once, and the newest
287    /// may not have reached its opening time.
288    pub open: Vec<ContractWithState>,
289    /// `IssuingMiningRound` contracts.
290    pub issuing: Vec<ContractWithState>,
291}
292
293/// The two fields of an `OpenMiningRound` that decide whether it is the one
294/// to use.
295#[derive(Deserialize)]
296struct OpenRound {
297    round: Round,
298    #[serde(rename = "opensAt")]
299    opens_at: Timestamp,
300}
301
302#[derive(Deserialize)]
303struct Round {
304    #[serde(deserialize_with = "int64")]
305    number: i64,
306}
307
308/// A Daml `Int` in JSON: a string, since a JSON number cannot hold every
309/// `i64`, though a number is accepted too.
310fn int64<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<i64, D::Error> {
311    #[derive(Deserialize)]
312    #[serde(untagged)]
313    enum Int {
314        Text(String),
315        Number(i64),
316    }
317    match Int::deserialize(deserializer)? {
318        Int::Text(text) => text.parse().map_err(serde::de::Error::custom),
319        Int::Number(number) => Ok(number),
320    }
321}
322
323impl MiningRounds {
324    /// The open round to pass to a choice at `now`: of the rounds whose
325    /// opening time has come, the one with the highest number.
326    ///
327    /// This is the round Splice's own applications pick
328    /// (`selectLatestOpenMiningRound`). The round with the lowest number is
329    /// open too, but it is the next to be archived, and a transaction built
330    /// on it fails if the archival lands first.
331    ///
332    /// # Errors
333    /// [`Error::UnexpectedResponse`] if a round's payload has no `round` or
334    /// `opensAt`, and [`Error::Connection`], which is retriable, if no round
335    /// has opened yet.
336    pub fn latest_open(&self, now: Timestamp) -> Result<&ContractWithState> {
337        let mut latest: Option<(i64, &ContractWithState)> = None;
338        for round in &self.open {
339            let fields: OpenRound = serde_json::from_value(round.contract.payload.clone())
340                .map_err(|e| {
341                    Error::UnexpectedResponse(format!(
342                        "Scan published open mining round `{}` with a payload that is not an \
343                         OpenMiningRound: {e}",
344                        round.contract.contract_id
345                    ))
346                })?;
347            if fields.opens_at > now {
348                continue;
349            }
350            if latest.is_none_or(|(number, _)| fields.round.number > number) {
351                latest = Some((fields.round.number, round));
352            }
353        }
354        latest.map(|(_, round)| round).ok_or_else(|| {
355            Error::Connection(format!(
356                "none of the {} open mining rounds Scan published has reached its opening time; \
357                 retry shortly",
358                self.open.len()
359            ))
360        })
361    }
362}
363
364/// How much traffic a member has bought and used on a synchronizer.
365#[derive(Clone, Copy, Debug, PartialEq, Eq)]
366#[non_exhaustive]
367pub struct TrafficStatus {
368    /// Bytes of extra traffic the member has consumed, as the sequencers
369    /// account it.
370    pub total_consumed: i64,
371    /// Bytes of extra traffic the member may consume in total, as the
372    /// sequencers account it.
373    pub total_limit: i64,
374    /// Bytes of extra traffic the member has purchased, as the DSO records
375    /// it. The limit catches up with this once the purchase is processed.
376    pub total_purchased: i64,
377}
378
379/// An entry in the Amulet Name Service.
380#[derive(Clone, Debug, Deserialize)]
381#[non_exhaustive]
382pub struct AnsEntry {
383    /// The entry's contract, where it has one. Entries the DSO defines for
384    /// itself and the Super Validators have none.
385    #[serde(default)]
386    pub contract_id: Option<String>,
387    /// The party the name belongs to.
388    pub user: String,
389    /// The name.
390    pub name: String,
391    /// The URL the owner gave.
392    pub url: String,
393    /// The description the owner gave.
394    pub description: String,
395    /// When the entry expires, where it does.
396    #[serde(default)]
397    pub expires_at: Option<String>,
398}
399
400/// A point in Scan's history: everything up to and including it has been
401/// read. Pass it back to read on from there.
402#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
403pub struct HistoryPosition {
404    /// The migration the record time belongs to. Record times start over
405    /// after a hard synchronizer migration, so one alone does not order
406    /// history.
407    #[serde(rename = "after_migration_id")]
408    pub migration_id: i64,
409    /// The record time.
410    #[serde(rename = "after_record_time")]
411    pub record_time: String,
412}
413
414/// One entry of the update history.
415#[derive(Clone, Debug)]
416#[non_exhaustive]
417pub enum ScanUpdate {
418    /// A transaction.
419    Transaction(ScanTransaction),
420    /// A contract leaving one synchronizer or arriving on another.
421    Reassignment(ScanReassignment),
422}
423
424impl ScanUpdate {
425    /// Where this update is in history, to read on from.
426    #[must_use]
427    pub fn position(&self) -> HistoryPosition {
428        match self {
429            Self::Transaction(transaction) => HistoryPosition {
430                migration_id: transaction.migration_id,
431                record_time: transaction.record_time.clone(),
432            },
433            Self::Reassignment(reassignment) => HistoryPosition {
434                migration_id: match &reassignment.event {
435                    ReassignmentEvent::Assignment(assignment) => assignment.migration_id,
436                    ReassignmentEvent::Unassignment(unassignment) => unassignment.migration_id,
437                },
438                record_time: reassignment.record_time.clone(),
439            },
440        }
441    }
442
443    /// The update id.
444    #[must_use]
445    pub fn update_id(&self) -> &str {
446        match self {
447            Self::Transaction(transaction) => &transaction.update_id,
448            Self::Reassignment(reassignment) => &reassignment.update_id,
449        }
450    }
451}
452
453/// The API gives the two kinds of update no tag to tell them by: a
454/// transaction is the one with events, a reassignment the one with an event.
455impl<'de> Deserialize<'de> for ScanUpdate {
456    fn deserialize<D: serde::Deserializer<'de>>(
457        deserializer: D,
458    ) -> std::result::Result<Self, D::Error> {
459        use serde::de::Error as _;
460        let value = Value::deserialize(deserializer)?;
461        if value.get("events_by_id").is_some() {
462            serde_json::from_value(value)
463                .map(Self::Transaction)
464                .map_err(D::Error::custom)
465        } else if value.get("event").is_some() {
466            serde_json::from_value(value)
467                .map(Self::Reassignment)
468                .map_err(D::Error::custom)
469        } else {
470            Err(D::Error::custom(
471                "an update with neither `events_by_id` (a transaction) nor `event` (a \
472                 reassignment)",
473            ))
474        }
475    }
476}
477
478/// A transaction in the update history.
479#[derive(Clone, Debug, Deserialize)]
480#[non_exhaustive]
481pub struct ScanTransaction {
482    /// The update id.
483    pub update_id: String,
484    /// The migration the transaction was recorded in.
485    pub migration_id: i64,
486    /// The workflow id the submitter gave, empty when it gave none.
487    pub workflow_id: String,
488    /// When the sequencer recorded it.
489    pub record_time: String,
490    /// The synchronizer it was sequenced on.
491    pub synchronizer_id: String,
492    /// The ledger effective time.
493    pub effective_at: String,
494    /// The ids of the root events, in execution order.
495    pub root_event_ids: Vec<String>,
496    /// Every event of the transaction by its id.
497    pub events_by_id: BTreeMap<String, ScanEvent>,
498    /// The hash an external party signed, for an externally signed
499    /// transaction.
500    #[serde(default)]
501    pub external_transaction_hash: Option<String>,
502}
503
504/// An event of a transaction.
505#[derive(Clone, Debug, Deserialize)]
506#[serde(tag = "event_type")]
507#[non_exhaustive]
508pub enum ScanEvent {
509    /// A contract was created.
510    #[serde(rename = "created_event")]
511    Created(ScanCreatedEvent),
512    /// A choice was exercised.
513    #[serde(rename = "exercised_event")]
514    Exercised(ScanExercisedEvent),
515}
516
517/// A contract's creation.
518#[derive(Clone, Debug, Deserialize)]
519#[non_exhaustive]
520pub struct ScanCreatedEvent {
521    /// The event id.
522    pub event_id: String,
523    /// The contract id.
524    pub contract_id: String,
525    /// `<package id>:<Module>:<Entity>`.
526    pub template_id: String,
527    /// The name of the package the template is in.
528    pub package_name: String,
529    /// The contract's arguments, as Daml JSON.
530    pub create_arguments: Value,
531    /// When the contract was created.
532    pub created_at: String,
533    /// The contract's signatories.
534    pub signatories: Vec<String>,
535    /// The contract's observers.
536    pub observers: Vec<String>,
537}
538
539/// A choice exercised on a contract.
540#[derive(Clone, Debug, Deserialize)]
541#[non_exhaustive]
542pub struct ScanExercisedEvent {
543    /// The event id.
544    pub event_id: String,
545    /// The contract the choice was exercised on.
546    pub contract_id: String,
547    /// `<package id>:<Module>:<Entity>`.
548    pub template_id: String,
549    /// The name of the package the template is in.
550    pub package_name: String,
551    /// The choice.
552    pub choice: String,
553    /// The choice's argument, as Daml JSON.
554    pub choice_argument: Value,
555    /// The ids of the events the choice caused, in execution order.
556    pub child_event_ids: Vec<String>,
557    /// What the choice returned, as Daml JSON.
558    pub exercise_result: Value,
559    /// Whether the choice archived the contract.
560    pub consuming: bool,
561    /// The parties that exercised it.
562    pub acting_parties: Vec<String>,
563    /// The interface the choice was exercised through, where it was.
564    #[serde(default)]
565    pub interface_id: Option<String>,
566}
567
568/// A contract leaving one synchronizer or arriving on another.
569#[derive(Clone, Debug, Deserialize)]
570#[non_exhaustive]
571pub struct ScanReassignment {
572    /// The update id.
573    pub update_id: String,
574    /// The offset on the Scan's own participant. It means nothing to another
575    /// participant.
576    pub offset: String,
577    /// When the sequencer recorded it.
578    pub record_time: String,
579    /// Which half of the reassignment this is.
580    pub event: ReassignmentEvent,
581}
582
583/// The two halves of a reassignment.
584#[derive(Clone, Debug)]
585#[non_exhaustive]
586pub enum ReassignmentEvent {
587    /// The contract arrived on the target synchronizer.
588    Assignment(ScanAssignment),
589    /// The contract left the source synchronizer.
590    Unassignment(ScanUnassignment),
591}
592
593/// As [`ScanUpdate`]: untagged in the API, and told apart by the one field
594/// each has that the other does not.
595impl<'de> Deserialize<'de> for ReassignmentEvent {
596    fn deserialize<D: serde::Deserializer<'de>>(
597        deserializer: D,
598    ) -> std::result::Result<Self, D::Error> {
599        use serde::de::Error as _;
600        let value = Value::deserialize(deserializer)?;
601        if value.get("created_event").is_some() {
602            serde_json::from_value(value)
603                .map(Self::Assignment)
604                .map_err(D::Error::custom)
605        } else if value.get("contract_id").is_some() {
606            serde_json::from_value(value)
607                .map(Self::Unassignment)
608                .map_err(D::Error::custom)
609        } else {
610            Err(D::Error::custom(
611                "a reassignment event with neither `created_event` (an assignment) nor \
612                 `contract_id` (an unassignment)",
613            ))
614        }
615    }
616}
617
618/// A contract arriving on a synchronizer.
619#[derive(Clone, Debug, Deserialize)]
620#[non_exhaustive]
621pub struct ScanAssignment {
622    /// The party that submitted the reassignment.
623    pub submitter: String,
624    /// The synchronizer the contract left.
625    pub source_synchronizer: String,
626    /// The synchronizer it arrived on.
627    pub target_synchronizer: String,
628    /// The migration it was recorded in.
629    pub migration_id: i64,
630    /// The id that ties this half to the unassignment.
631    pub unassign_id: String,
632    /// The contract, as created on the target synchronizer.
633    pub created_event: ScanCreatedEvent,
634    /// How many times the contract has been reassigned.
635    pub reassignment_counter: i64,
636}
637
638/// A contract leaving a synchronizer.
639#[derive(Clone, Debug, Deserialize)]
640#[non_exhaustive]
641pub struct ScanUnassignment {
642    /// The party that submitted the reassignment.
643    pub submitter: String,
644    /// The synchronizer the contract left.
645    pub source_synchronizer: String,
646    /// The migration it was recorded in.
647    pub migration_id: i64,
648    /// The synchronizer it is going to.
649    pub target_synchronizer: String,
650    /// The id that ties this half to the assignment.
651    pub unassign_id: String,
652    /// How many times the contract has been reassigned.
653    pub reassignment_counter: i64,
654    /// The contract.
655    pub contract_id: String,
656}
657
658/// One entry of the event history: an update, the mediator's verdict on it,
659/// or both.
660#[derive(Clone, Debug, Deserialize)]
661#[non_exhaustive]
662pub struct ScanEventItem {
663    /// The update, where Scan's participant saw it. A transaction the
664    /// mediator rejected has a verdict and no update.
665    #[serde(default)]
666    pub update: Option<ScanUpdate>,
667    /// The mediator's verdict, as Scan publishes it.
668    #[serde(default)]
669    pub verdict: Option<Value>,
670    /// The traffic the update cost, where Scan reports it.
671    #[serde(default)]
672    pub traffic_summary: Option<Value>,
673    /// The application activity records the update produced, where Scan
674    /// reports them.
675    #[serde(default)]
676    pub app_activity_records: Option<Value>,
677    /// The asset activity records the update produced, where Scan reports
678    /// them.
679    #[serde(default)]
680    pub asset_activity_records: Option<Value>,
681    /// The application provider the submission was made through, where Scan
682    /// reports one.
683    #[serde(default)]
684    pub submitting_app_provider: Option<String>,
685}
686
687impl ScanEventItem {
688    /// Where this entry is in history, to read on from: the update's
689    /// position, or the verdict's where there is no update, as for a
690    /// transaction the mediator rejected. `None` only for an entry with
691    /// neither, or a verdict without its migration and record time.
692    #[must_use]
693    pub fn position(&self) -> Option<HistoryPosition> {
694        if let Some(update) = &self.update {
695            return Some(update.position());
696        }
697        let verdict = self.verdict.as_ref()?;
698        Some(HistoryPosition {
699            migration_id: verdict.get("migration_id")?.as_i64()?,
700            record_time: verdict.get("record_time")?.as_str()?.to_string(),
701        })
702    }
703}
704
705/// Which snapshot of the active contracts to read, and which part of it.
706///
707/// Scan takes a snapshot every few hours.
708/// [`ScanClient::acs_snapshot_timestamp`] gives the record time of the one
709/// before a moment; [`at_or_before`](Self::at_or_before) lets Scan find it
710/// instead.
711#[derive(Clone, Debug)]
712pub struct SnapshotRequest {
713    migration_id: i64,
714    record_time: String,
715    at_or_before: bool,
716    after: Option<String>,
717    page_size: u32,
718    parties: Vec<String>,
719    templates: Vec<String>,
720}
721
722impl SnapshotRequest {
723    /// The snapshot taken at exactly `record_time` in `migration_id`.
724    pub fn at(migration_id: i64, record_time: impl Into<String>) -> Self {
725        Self {
726            migration_id,
727            record_time: record_time.into(),
728            at_or_before: false,
729            after: None,
730            page_size: 100,
731            parties: Vec::new(),
732            templates: Vec::new(),
733        }
734    }
735
736    /// Take the most recent snapshot at or before the record time, where the
737    /// default is to require one at exactly that time.
738    #[must_use]
739    pub fn at_or_before(mut self) -> Self {
740        self.at_or_before = true;
741        self
742    }
743
744    /// How many contracts a page holds. Defaults to 100; Scan allows 1000.
745    #[must_use]
746    pub fn with_page_size(mut self, page_size: u32) -> Self {
747        self.page_size = page_size;
748        self
749    }
750
751    /// Read the page after the one that returned this token.
752    #[must_use]
753    pub fn after(mut self, next_page_token: impl Into<String>) -> Self {
754        self.after = Some(next_page_token.into());
755        self
756    }
757
758    /// Only contracts these parties are stakeholders of. For the holdings
759    /// reads these are the owners, and at least one is required.
760    #[must_use]
761    pub fn for_parties<I, S>(mut self, parties: I) -> Self
762    where
763        I: IntoIterator<Item = S>,
764        S: Into<String>,
765    {
766        self.parties = parties.into_iter().map(Into::into).collect();
767        self
768    }
769
770    /// Only contracts of these templates, each as
771    /// `<package name>:<Module>:<Entity>`. Ignored by the holdings reads.
772    #[must_use]
773    pub fn for_templates<I, S>(mut self, templates: I) -> Self
774    where
775        I: IntoIterator<Item = S>,
776        S: Into<String>,
777    {
778        self.templates = templates.into_iter().map(Into::into).collect();
779        self
780    }
781
782    fn record_time_match(&self) -> &'static str {
783        if self.at_or_before {
784            "at_or_before"
785        } else {
786            "exact"
787        }
788    }
789
790    fn owners(&self, read: &str) -> Result<&[String]> {
791        if self.parties.is_empty() {
792            return Err(Error::InvalidRequest(format!(
793                "{read} needs at least one owner party (SnapshotRequest::for_parties)"
794            )));
795        }
796        Ok(&self.parties)
797    }
798}
799
800/// A page of a snapshot of the active contracts.
801#[derive(Clone, Debug, Deserialize)]
802#[non_exhaustive]
803pub struct AcsSnapshot {
804    /// The record time of the snapshot that was read.
805    pub record_time: String,
806    /// The migration it belongs to.
807    pub migration_id: i64,
808    /// The contracts on this page.
809    pub created_events: Vec<ActiveContract>,
810    /// The token for the next page, absent on the last one.
811    #[serde(default)]
812    pub next_page_token: Option<String>,
813}
814
815/// A contract in a snapshot.
816#[derive(Clone, Debug, Deserialize)]
817#[non_exhaustive]
818pub struct ActiveContract {
819    /// The update that created it, where Scan reports it.
820    #[serde(default)]
821    pub created_in_update_id: Option<String>,
822    /// The contract id.
823    pub contract_id: String,
824    /// `<package id>:<Module>:<Entity>`.
825    pub template_id: String,
826    /// The name of the package the template is in.
827    pub package_name: String,
828    /// The contract's arguments, as Daml JSON.
829    pub create_arguments: Value,
830    /// When the contract was created.
831    pub created_at: String,
832    /// The contract's signatories.
833    pub signatories: Vec<String>,
834    /// The contract's observers.
835    pub observers: Vec<String>,
836}
837
838/// What some parties held at a snapshot.
839#[derive(Clone, Debug, Deserialize)]
840#[non_exhaustive]
841pub struct HoldingsSummaries {
842    /// The record time of the snapshot that was read.
843    pub record_time: String,
844    /// The migration it belongs to.
845    pub migration_id: i64,
846    /// One summary per owner that held anything.
847    pub summaries: Vec<HoldingsSummary>,
848}
849
850/// What one party held at a snapshot. Amounts are decimal strings, as Daml
851/// JSON writes a `Decimal`.
852#[derive(Clone, Debug, Deserialize)]
853#[non_exhaustive]
854pub struct HoldingsSummary {
855    /// The owner.
856    pub party_id: String,
857    /// The Amulet the party could spend.
858    pub total_unlocked_coin: String,
859    /// The Amulet locked in its name.
860    pub total_locked_coin: String,
861    /// Both together.
862    pub total_coin_holdings: String,
863}
864
865impl ScanClient {
866    /// A client for the Scan served at `base_url`, which ends in `/api/scan`.
867    ///
868    /// # Errors
869    /// [`Error::InvalidRequest`] if `base_url` is not a URL, or an HTTP client
870    /// cannot be built.
871    pub fn new(base_url: &str) -> Result<Self> {
872        Self::with_http_client(base_url, default_http_client()?)
873    }
874
875    /// [`new`](Self::new) with an HTTP client the caller has configured:
876    /// timeouts, proxies, a custom TLS root store. Configure it with
877    /// `reqwest::redirect::Policy::none()`, as [`new`](Self::new) does: what
878    /// Scan answers goes into commands the caller signs, so it must come from
879    /// the Scan the caller named and not from wherever a 3xx points.
880    ///
881    /// # Errors
882    /// [`Error::InvalidRequest`] if `base_url` is not a URL.
883    pub fn with_http_client(base_url: &str, http: reqwest::Client) -> Result<Self> {
884        Self::build(base_url, http, Route::Scan)
885    }
886
887    /// A client for the scan-proxy of the validator served at `base_url`,
888    /// which ends in `/api/validator`.
889    ///
890    /// The proxy authenticates every request: give the client a token with
891    /// [`with_token`](Self::with_token) or
892    /// [`with_token_source`](Self::with_token_source).
893    ///
894    /// # Errors
895    /// [`Error::InvalidRequest`] if `base_url` is not a URL, or an HTTP client
896    /// cannot be built.
897    pub fn through_validator(base_url: &str) -> Result<Self> {
898        Self::through_validator_with_http_client(base_url, default_http_client()?)
899    }
900
901    /// [`through_validator`](Self::through_validator) with an HTTP client the
902    /// caller has configured. See [`with_http_client`](Self::with_http_client).
903    ///
904    /// # Errors
905    /// [`Error::InvalidRequest`] if `base_url` is not a URL.
906    pub fn through_validator_with_http_client(
907        base_url: &str,
908        http: reqwest::Client,
909    ) -> Result<Self> {
910        Self::build(base_url, http, Route::ScanProxy)
911    }
912
913    fn build(base_url: &str, http: reqwest::Client, route: Route) -> Result<Self> {
914        // A trailing slash matters to `Url::join`, and the paths below are
915        // relative, so it is normalised here once.
916        let normalised = format!("{}/", base_url.trim_end_matches('/'));
917        let base = reqwest::Url::parse(&normalised)
918            .map_err(|e| Error::InvalidRequest(format!("`{base_url}` is not a Scan URL: {e}")))?;
919        Ok(Self {
920            base,
921            http,
922            auth: Auth::None,
923            route,
924            internal_endpoints: false,
925        })
926    }
927
928    /// Send a bearer token with every request. A validator's scan-proxy
929    /// requires one; a Scan does not.
930    #[must_use]
931    pub fn with_token(mut self, token: impl Into<String>) -> Self {
932        self.auth = Auth::Static(token.into());
933        self
934    }
935
936    /// Send a bearer token from a source that refreshes it, such as
937    /// `canton_auth::TokenProvider`.
938    #[must_use]
939    pub fn with_token_source(mut self, source: impl TokenSource + 'static) -> Self {
940        self.auth = Auth::Dynamic(std::sync::Arc::new(source));
941        self
942    }
943
944    /// Allow the calls that reach endpoints Splice tags `internal` when the
945    /// client asks a Scan directly:
946    /// [`featured_app_right`](Self::featured_app_right) and
947    /// [`transfer_preapproval_by_party`](Self::transfer_preapproval_by_party),
948    /// and the lighter of the two ways to read
949    /// [`amulet_rules`](Self::amulet_rules).
950    ///
951    /// Splice may change an internal endpoint in any release, and these
952    /// methods change with it. Through a validator's scan-proxy the same
953    /// calls are part of the proxy's API, and this is not needed.
954    #[must_use]
955    pub fn with_internal_endpoints(mut self) -> Self {
956        self.internal_endpoints = true;
957        self
958    }
959
960    /// Build a URL from an API version and path segments, under the
961    /// scan-proxy prefix where the client goes through a validator. Every
962    /// segment is percent-encoded, so a party or a name cannot change which
963    /// resource is addressed.
964    fn url(&self, version: &str, segments: &[&str]) -> Result<reqwest::Url> {
965        let mut url = self.base.clone();
966        {
967            let mut path = url.path_segments_mut().map_err(|()| {
968                Error::InvalidRequest("the Scan URL cannot have a path".to_string())
969            })?;
970            path.pop_if_empty().push(version);
971            if self.route == Route::ScanProxy {
972                path.push("scan-proxy");
973            }
974            path.extend(segments);
975        }
976        Ok(url)
977    }
978
979    /// Refuse a read the validator's scan-proxy does not serve.
980    fn scan_only(&self, read: &str) -> Result<()> {
981        if self.route == Route::ScanProxy {
982            return Err(Error::InvalidRequest(format!(
983                "a validator's scan-proxy does not serve {read}; ask a Scan for it \
984                 (ScanClient::new)"
985            )));
986        }
987        Ok(())
988    }
989
990    /// Refuse an internal endpoint of a Scan the caller did not opt into.
991    fn internal(&self, read: &str) -> Result<()> {
992        if self.route == Route::Scan && !self.internal_endpoints {
993            return Err(Error::InvalidRequest(format!(
994                "{read} is an endpoint Scan tags internal, which Splice may change in any \
995                 release; opt in with ScanClient::with_internal_endpoints(), or go through a \
996                 validator's scan-proxy (ScanClient::through_validator), which serves it as \
997                 part of its API"
998            )));
999        }
1000        Ok(())
1001    }
1002
1003    /// The party that represents the DSO.
1004    ///
1005    /// # Errors
1006    /// As any HTTP call, plus [`Error::UnexpectedResponse`] on a body that is
1007    /// not what Splice specifies.
1008    pub async fn dso_party_id(&self) -> Result<String> {
1009        #[derive(Deserialize)]
1010        struct Reply {
1011            dso_party_id: String,
1012        }
1013        let reply: Reply = self.get(self.url("v0", &["dso-party-id"])?).await?;
1014        Ok(reply.dso_party_id)
1015    }
1016
1017    /// The DSO: its party, its voting threshold, and the contracts that hold
1018    /// its rules.
1019    ///
1020    /// Asked at `/v1/dso`, which Splice 0.10 added. A Scan or a validator
1021    /// older than that answers `404` there and serves `/v0/dso`, which
1022    /// carries the same contracts, so that is asked next.
1023    ///
1024    /// # Errors
1025    /// As [`dso_party_id`](Self::dso_party_id).
1026    pub async fn dso(&self) -> Result<DsoInfo> {
1027        match self.get(self.url("v1", &["dso"])?).await {
1028            Err(Error::Http { status: 404, .. }) => self.get(self.url("v0", &["dso"])?).await,
1029            answer => answer,
1030        }
1031    }
1032
1033    /// Every Super Validator's Scan, per synchronizer.
1034    ///
1035    /// # Errors
1036    /// As [`dso_party_id`](Self::dso_party_id), and
1037    /// [`Error::InvalidRequest`] through a validator's scan-proxy, which does
1038    /// not serve it.
1039    pub async fn scans(&self) -> Result<Vec<SynchronizerScans>> {
1040        #[derive(Deserialize)]
1041        struct Reply {
1042            scans: Vec<SynchronizerScans>,
1043        }
1044        self.scan_only("the list of Scans")?;
1045        let reply: Reply = self.get(self.url("v0", &["scans"])?).await?;
1046        Ok(reply.scans)
1047    }
1048
1049    /// The open and the issuing mining rounds.
1050    ///
1051    /// # Errors
1052    /// As [`dso_party_id`](Self::dso_party_id).
1053    pub async fn open_and_issuing_mining_rounds(&self) -> Result<MiningRounds> {
1054        // A Scan answers with only the rounds the caller does not say it has
1055        // cached, keyed by contract id; the proxy answers with them all.
1056        #[derive(Serialize)]
1057        struct Cached {
1058            cached_open_mining_round_contract_ids: [String; 0],
1059            cached_issuing_round_contract_ids: [String; 0],
1060        }
1061        #[derive(Deserialize)]
1062        struct MaybeCached {
1063            #[serde(default)]
1064            contract: Option<ScanContract>,
1065            #[serde(default)]
1066            domain_id: Option<String>,
1067        }
1068        #[derive(Deserialize)]
1069        struct FromScan {
1070            open_mining_rounds: BTreeMap<String, MaybeCached>,
1071            issuing_mining_rounds: BTreeMap<String, MaybeCached>,
1072        }
1073        #[derive(Deserialize)]
1074        struct FromProxy {
1075            open_mining_rounds: Vec<ContractWithState>,
1076            issuing_mining_rounds: Vec<ContractWithState>,
1077        }
1078        fn all(rounds: BTreeMap<String, MaybeCached>) -> Result<Vec<ContractWithState>> {
1079            rounds
1080                .into_iter()
1081                .map(|(contract_id, round)| {
1082                    let contract = round.contract.ok_or_else(|| {
1083                        Error::UnexpectedResponse(format!(
1084                            "Scan left out mining round `{contract_id}` as cached, where this \
1085                             client told it nothing was"
1086                        ))
1087                    })?;
1088                    Ok(ContractWithState {
1089                        contract,
1090                        synchronizer_id: round.domain_id,
1091                    })
1092                })
1093                .collect()
1094        }
1095
1096        let url = self.url("v0", &["open-and-issuing-mining-rounds"])?;
1097        match self.route {
1098            Route::Scan => {
1099                let reply: FromScan = self
1100                    .post(
1101                        url,
1102                        &Cached {
1103                            cached_open_mining_round_contract_ids: [],
1104                            cached_issuing_round_contract_ids: [],
1105                        },
1106                    )
1107                    .await?;
1108                Ok(MiningRounds {
1109                    open: all(reply.open_mining_rounds)?,
1110                    issuing: all(reply.issuing_mining_rounds)?,
1111                })
1112            }
1113            Route::ScanProxy => {
1114                let reply: FromProxy = self.get(url).await?;
1115                Ok(MiningRounds {
1116                    open: reply.open_mining_rounds,
1117                    issuing: reply.issuing_mining_rounds,
1118                })
1119            }
1120        }
1121    }
1122
1123    /// The open mining round to pass to a choice now: see
1124    /// [`MiningRounds::latest_open`].
1125    ///
1126    /// # Errors
1127    /// As [`open_and_issuing_mining_rounds`](Self::open_and_issuing_mining_rounds)
1128    /// and [`MiningRounds::latest_open`].
1129    pub async fn latest_open_mining_round(&self) -> Result<ContractWithState> {
1130        let rounds = self.open_and_issuing_mining_rounds().await?;
1131        let now = std::time::SystemTime::now()
1132            .duration_since(std::time::UNIX_EPOCH)
1133            .ok()
1134            .and_then(|since| i64::try_from(since.as_micros()).ok())
1135            .ok_or_else(|| {
1136                Error::InvalidRequest("the system clock is not a time after 1970".to_string())
1137            })?;
1138        rounds.latest_open(Timestamp(now)).cloned()
1139    }
1140
1141    /// The closed mining rounds that have not been archived yet.
1142    ///
1143    /// # Errors
1144    /// As [`scans`](Self::scans).
1145    pub async fn closed_rounds(&self) -> Result<Vec<ScanContract>> {
1146        #[derive(Deserialize)]
1147        struct Reply {
1148            rounds: Vec<ScanContract>,
1149        }
1150        self.scan_only("the closed mining rounds")?;
1151        let reply: Reply = self.get(self.url("v0", &["closed-rounds"])?).await?;
1152        Ok(reply.rounds)
1153    }
1154
1155    /// The `AmuletRules` contract.
1156    ///
1157    /// A Scan publishes it twice: with the rest of the DSO's contracts in the
1158    /// external API ([`dso`](Self::dso)), and alone at an internal endpoint.
1159    /// The external one is asked, unless the client opted into the internal
1160    /// endpoints ([`with_internal_endpoints`](Self::with_internal_endpoints)),
1161    /// whose reply is the one contract. A validator's scan-proxy serves it as
1162    /// part of its own API.
1163    ///
1164    /// # Errors
1165    /// As [`dso_party_id`](Self::dso_party_id).
1166    pub async fn amulet_rules(&self) -> Result<ContractWithState> {
1167        #[derive(Deserialize)]
1168        struct MaybeCached {
1169            #[serde(default)]
1170            contract: Option<ScanContract>,
1171            #[serde(default)]
1172            domain_id: Option<String>,
1173        }
1174        #[derive(Deserialize)]
1175        struct FromScan {
1176            amulet_rules_update: MaybeCached,
1177        }
1178        #[derive(Deserialize)]
1179        struct FromProxy {
1180            amulet_rules: ContractWithState,
1181        }
1182        if self.route == Route::Scan && !self.internal_endpoints {
1183            return Ok(self.dso().await?.amulet_rules);
1184        }
1185        let url = self.url("v0", &["amulet-rules"])?;
1186        match self.route {
1187            Route::Scan => {
1188                // The body names the contract the caller has cached, so that
1189                // Scan can leave it out. None is named here.
1190                let reply: FromScan = self.post(url, &serde_json::json!({})).await?;
1191                let contract = reply.amulet_rules_update.contract.ok_or_else(|| {
1192                    Error::UnexpectedResponse(
1193                        "Scan left out the Amulet rules as cached, where this client told it \
1194                         nothing was"
1195                            .to_string(),
1196                    )
1197                })?;
1198                Ok(ContractWithState {
1199                    contract,
1200                    synchronizer_id: reply.amulet_rules_update.domain_id,
1201                })
1202            }
1203            Route::ScanProxy => {
1204                let reply: FromProxy = self.get(url).await?;
1205                Ok(reply.amulet_rules)
1206            }
1207        }
1208    }
1209
1210    /// A provider's `FeaturedAppRight` contract, or `None` if the provider is
1211    /// not a featured application.
1212    ///
1213    /// The contract comes without a synchronizer: disclose it on the one the
1214    /// Amulet rules are on ([`ScanContract::disclosed`]).
1215    ///
1216    /// On a Scan this is an internal endpoint: see
1217    /// [`with_internal_endpoints`](Self::with_internal_endpoints).
1218    ///
1219    /// # Errors
1220    /// As [`dso_party_id`](Self::dso_party_id), and
1221    /// [`Error::InvalidRequest`] on a Scan without the opt-in.
1222    pub async fn featured_app_right(&self, provider: &str) -> Result<Option<ScanContract>> {
1223        #[derive(Deserialize)]
1224        struct Reply {
1225            #[serde(default)]
1226            featured_app_right: Option<ScanContract>,
1227        }
1228        self.internal("a featured application right")?;
1229        let reply: Reply = self
1230            .get(self.url("v0", &["featured-apps", provider])?)
1231            .await?;
1232        Ok(reply.featured_app_right)
1233    }
1234
1235    /// The `TransferPreapproval` contract that lets `party` receive Amulet
1236    /// without accepting each transfer, or `None` if it has none.
1237    ///
1238    /// On a Scan this is an internal endpoint: see
1239    /// [`with_internal_endpoints`](Self::with_internal_endpoints).
1240    ///
1241    /// # Errors
1242    /// As [`featured_app_right`](Self::featured_app_right).
1243    pub async fn transfer_preapproval_by_party(
1244        &self,
1245        party: &str,
1246    ) -> Result<Option<ContractWithState>> {
1247        #[derive(Deserialize)]
1248        struct Reply {
1249            transfer_preapproval: ContractWithState,
1250        }
1251        self.internal("a transfer preapproval")?;
1252        let url = self.url("v0", &["transfer-preapprovals", "by-party", party])?;
1253        let reply: Option<Reply> = self.get_optional(url).await?;
1254        Ok(reply.map(|reply| reply.transfer_preapproval))
1255    }
1256
1257    /// How much traffic `member` has bought and used on a synchronizer. A
1258    /// member is a participant or a mediator, by its id (`PAR::…`, `MED::…`).
1259    ///
1260    /// # Errors
1261    /// As [`scans`](Self::scans).
1262    pub async fn member_traffic_status(
1263        &self,
1264        synchronizer_id: &str,
1265        member_id: &str,
1266    ) -> Result<TrafficStatus> {
1267        #[derive(Deserialize)]
1268        struct Reply {
1269            traffic_status: Status,
1270        }
1271        #[derive(Deserialize)]
1272        struct Status {
1273            actual: Actual,
1274            target: Target,
1275        }
1276        #[derive(Deserialize)]
1277        struct Actual {
1278            total_consumed: i64,
1279            total_limit: i64,
1280        }
1281        #[derive(Deserialize)]
1282        struct Target {
1283            total_purchased: i64,
1284        }
1285        self.scan_only("a member's traffic status")?;
1286        let url = self.url(
1287            "v0",
1288            &[
1289                "domains",
1290                synchronizer_id,
1291                "members",
1292                member_id,
1293                "traffic-status",
1294            ],
1295        )?;
1296        let reply: Reply = self.get(url).await?;
1297        Ok(TrafficStatus {
1298            total_consumed: reply.traffic_status.actual.total_consumed,
1299            total_limit: reply.traffic_status.actual.total_limit,
1300            total_purchased: reply.traffic_status.target.total_purchased,
1301        })
1302    }
1303
1304    /// The Amulet Name Service entry of `party`, or `None` if it has none.
1305    ///
1306    /// # Errors
1307    /// As [`dso_party_id`](Self::dso_party_id).
1308    pub async fn ans_entry_by_party(&self, party: &str) -> Result<Option<AnsEntry>> {
1309        self.ans_entry(&["ans-entries", "by-party", party]).await
1310    }
1311
1312    /// The Amulet Name Service entry for `name`, or `None` if there is none.
1313    ///
1314    /// # Errors
1315    /// As [`dso_party_id`](Self::dso_party_id).
1316    pub async fn ans_entry_by_name(&self, name: &str) -> Result<Option<AnsEntry>> {
1317        self.ans_entry(&["ans-entries", "by-name", name]).await
1318    }
1319
1320    async fn ans_entry(&self, segments: &[&str]) -> Result<Option<AnsEntry>> {
1321        #[derive(Deserialize)]
1322        struct Reply {
1323            entry: AnsEntry,
1324        }
1325        let reply: Option<Reply> = self.get_optional(self.url("v0", segments)?).await?;
1326        Ok(reply.map(|reply| reply.entry))
1327    }
1328
1329    /// Up to `page_size` unexpired Amulet Name Service entries, those whose
1330    /// name starts with `name_prefix` where one is given.
1331    ///
1332    /// # Errors
1333    /// As [`dso_party_id`](Self::dso_party_id).
1334    pub async fn ans_entries(
1335        &self,
1336        name_prefix: Option<&str>,
1337        page_size: u32,
1338    ) -> Result<Vec<AnsEntry>> {
1339        #[derive(Deserialize)]
1340        struct Reply {
1341            entries: Vec<AnsEntry>,
1342        }
1343        let mut url = self.url("v0", &["ans-entries"])?;
1344        {
1345            let mut query = url.query_pairs_mut();
1346            if let Some(name_prefix) = name_prefix {
1347                query.append_pair("name_prefix", name_prefix);
1348            }
1349            query.append_pair("page_size", &page_size.to_string());
1350        }
1351        let reply: Reply = self.get(url).await?;
1352        Ok(reply.entries)
1353    }
1354
1355    /// Up to `page_size` updates after `after`, oldest first, or from the
1356    /// beginning of history where `after` is `None`.
1357    ///
1358    /// The last update's [`position`](ScanUpdate::position) is the `after` of
1359    /// the next page, and fewer than `page_size` updates means the end of
1360    /// what Scan has so far. Every Scan returns the same updates in the same
1361    /// order.
1362    ///
1363    /// # Errors
1364    /// As [`scans`](Self::scans).
1365    pub async fn updates(
1366        &self,
1367        after: Option<&HistoryPosition>,
1368        page_size: u32,
1369    ) -> Result<Vec<ScanUpdate>> {
1370        #[derive(Deserialize)]
1371        struct Reply {
1372            transactions: Vec<ScanUpdate>,
1373        }
1374        self.scan_only("the update history")?;
1375        let reply: Reply = self
1376            .post(
1377                self.url("v2", &["updates"])?,
1378                &history_request(after, page_size)?,
1379            )
1380            .await?;
1381        Ok(reply.transactions)
1382    }
1383
1384    /// The update with this id, or `None` if Scan has none.
1385    ///
1386    /// # Errors
1387    /// As [`scans`](Self::scans).
1388    pub async fn update(&self, update_id: &str) -> Result<Option<ScanUpdate>> {
1389        self.scan_only("an update")?;
1390        self.get_optional(self.url("v2", &["updates", update_id])?)
1391            .await
1392    }
1393
1394    /// Up to `page_size` entries of the event history after `after`: each
1395    /// update with the mediator's verdict on it. Paged as
1396    /// [`updates`](Self::updates), from the last entry's
1397    /// [`position`](ScanEventItem::position), which an entry has also when it
1398    /// is a verdict with no update.
1399    ///
1400    /// # Errors
1401    /// As [`scans`](Self::scans).
1402    pub async fn events(
1403        &self,
1404        after: Option<&HistoryPosition>,
1405        page_size: u32,
1406    ) -> Result<Vec<ScanEventItem>> {
1407        #[derive(Deserialize)]
1408        struct Reply {
1409            events: Vec<ScanEventItem>,
1410        }
1411        self.scan_only("the event history")?;
1412        let reply: Reply = self
1413            .post(
1414                self.url("v0", &["events"])?,
1415                &history_request(after, page_size)?,
1416            )
1417            .await?;
1418        Ok(reply.events)
1419    }
1420
1421    /// The record time of the most recent snapshot of the active contracts
1422    /// taken before `before` (an RFC 3339 time) in `migration_id`, or `None`
1423    /// if there is none.
1424    ///
1425    /// # Errors
1426    /// As [`scans`](Self::scans).
1427    pub async fn acs_snapshot_timestamp(
1428        &self,
1429        before: &str,
1430        migration_id: i64,
1431    ) -> Result<Option<String>> {
1432        #[derive(Deserialize)]
1433        struct Reply {
1434            record_time: String,
1435        }
1436        self.scan_only("the snapshot times")?;
1437        let mut url = self.url("v0", &["state", "acs", "snapshot-timestamp"])?;
1438        url.query_pairs_mut()
1439            .append_pair("before", before)
1440            .append_pair("migration_id", &migration_id.to_string());
1441        let reply: Option<Reply> = self.get_optional(url).await?;
1442        Ok(reply.map(|reply| reply.record_time))
1443    }
1444
1445    /// A page of a snapshot of the active contracts.
1446    ///
1447    /// Splice 0.7.5 and later: an older Scan has no `/v2/state/acs` and
1448    /// answers `404`.
1449    ///
1450    /// # Errors
1451    /// As [`scans`](Self::scans), and [`Error::InvalidRequest`] for a page
1452    /// size Scan does not allow.
1453    pub async fn acs_snapshot(&self, request: &SnapshotRequest) -> Result<AcsSnapshot> {
1454        self.scan_only("the snapshots of the active contracts")?;
1455        let mut body = serde_json::json!({
1456            "migration_id": request.migration_id,
1457            "record_time": request.record_time,
1458            "record_time_match": request.record_time_match(),
1459            "page_size": page_size(request.page_size)?,
1460        });
1461        if let Some(after) = &request.after {
1462            set(&mut body, "after", Value::from(after.as_str()));
1463        }
1464        if !request.parties.is_empty() {
1465            set(&mut body, "party_ids", Value::from(request.parties.clone()));
1466        }
1467        if !request.templates.is_empty() {
1468            set(
1469                &mut body,
1470                "templates",
1471                Value::from(request.templates.clone()),
1472            );
1473        }
1474        self.post(self.url("v2", &["state", "acs"])?, &body).await
1475    }
1476
1477    /// A page of the Amulet and locked Amulet contracts the request's parties
1478    /// owned at a snapshot. Splice 0.7.5 and later, as
1479    /// [`acs_snapshot`](Self::acs_snapshot).
1480    ///
1481    /// # Errors
1482    /// As [`acs_snapshot`](Self::acs_snapshot), and
1483    /// [`Error::InvalidRequest`] if the request names no party.
1484    pub async fn holdings_state(&self, request: &SnapshotRequest) -> Result<AcsSnapshot> {
1485        self.scan_only("the holdings at a snapshot")?;
1486        let mut body = serde_json::json!({
1487            "migration_id": request.migration_id,
1488            "record_time": request.record_time,
1489            "record_time_match": request.record_time_match(),
1490            "page_size": page_size(request.page_size)?,
1491            "owner_party_ids": request.owners("a holdings read")?,
1492        });
1493        if let Some(after) = &request.after {
1494            set(&mut body, "after", Value::from(after.as_str()));
1495        }
1496        self.post(self.url("v2", &["holdings", "state"])?, &body)
1497            .await
1498    }
1499
1500    /// The Amulet totals the request's parties held at a snapshot. The page
1501    /// size, page token and templates of the request are not used. Splice
1502    /// 0.6.3 and later.
1503    ///
1504    /// # Errors
1505    /// As [`dso_party_id`](Self::dso_party_id), and
1506    /// [`Error::InvalidRequest`] if the request names no party.
1507    pub async fn holdings_summary(&self, request: &SnapshotRequest) -> Result<HoldingsSummaries> {
1508        let body = serde_json::json!({
1509            "migration_id": request.migration_id,
1510            "record_time": request.record_time,
1511            "record_time_match": request.record_time_match(),
1512            "owner_party_ids": request.owners("a holdings summary")?,
1513        });
1514        self.post(self.url("v1", &["holdings", "summary"])?, &body)
1515            .await
1516    }
1517
1518    /// `GET` a path this client has no method for, and return the JSON as it
1519    /// came. `version` is the first path segment (`v0`, `v1`, …).
1520    ///
1521    /// For the rest of Splice's API: the same transport as every other call
1522    /// here (the token, no redirects, a bounded reply, encoded segments) and
1523    /// nothing checked about what comes back. Through a validator the path is
1524    /// taken under its `scan-proxy` prefix.
1525    ///
1526    /// # Errors
1527    /// As any HTTP call.
1528    pub async fn get_json(
1529        &self,
1530        version: &str,
1531        segments: &[&str],
1532        query: &[(&str, &str)],
1533    ) -> Result<Value> {
1534        let mut url = self.url(version, segments)?;
1535        if !query.is_empty() {
1536            url.query_pairs_mut().extend_pairs(query);
1537        }
1538        self.get(url).await
1539    }
1540
1541    /// `POST` a JSON body to a path this client has no method for, and return
1542    /// the JSON as it came. See [`get_json`](Self::get_json).
1543    ///
1544    /// # Errors
1545    /// As any HTTP call.
1546    pub async fn post_json(&self, version: &str, segments: &[&str], body: &Value) -> Result<Value> {
1547        self.post(self.url(version, segments)?, body).await
1548    }
1549
1550    /// Send a request with the bearer token, when one is configured.
1551    async fn send(&self, request: reqwest::RequestBuilder) -> Result<reqwest::Response> {
1552        let request = match self.auth.bearer().await? {
1553            Some(token) => request.bearer_auth(token),
1554            None => request,
1555        };
1556        request.send().await.map_err(|e| transport_error(e, SCAN))
1557    }
1558
1559    async fn get<T: serde::de::DeserializeOwned>(&self, url: reqwest::Url) -> Result<T> {
1560        let response = self.send(self.http.get(url.clone())).await?;
1561        decode(response, url.as_str()).await
1562    }
1563
1564    async fn post<T: serde::de::DeserializeOwned>(
1565        &self,
1566        url: reqwest::Url,
1567        body: &(impl Serialize + ?Sized),
1568    ) -> Result<T> {
1569        let response = self.send(self.http.post(url.clone()).json(body)).await?;
1570        decode(response, url.as_str()).await
1571    }
1572
1573    /// A `GET` whose `404` is an answer: there is no such entry.
1574    ///
1575    /// Only when Scan is the one answering. A `404` whose body is not JSON did
1576    /// not come from a Scan handler: it is a base URL one path component off,
1577    /// or a gateway in front of one, and reporting that as "no such entry"
1578    /// would be a steady, quiet `None` where every other call fails loudly.
1579    async fn get_optional<T: serde::de::DeserializeOwned>(
1580        &self,
1581        url: reqwest::Url,
1582    ) -> Result<Option<T>> {
1583        let response = self.send(self.http.get(url.clone())).await?;
1584        if response.status() == reqwest::StatusCode::NOT_FOUND {
1585            let body = read_error_body(response, url.as_str(), SCAN).await?;
1586            let trimmed = body.trim();
1587            if serde_json::from_str::<ErrorResponse>(trimmed).is_ok() {
1588                return Ok(None);
1589            }
1590            tracing::warn!(%url, "a 404 that is not Scan's own — check the base URL");
1591            return Err(Error::http_at(404, truncate(trimmed), url.as_str()));
1592        }
1593        Ok(Some(decode(response, url.as_str()).await?))
1594    }
1595}
1596
1597/// The HTTP client every [`ScanClient`] starts from: a deadline, and no
1598/// redirects.
1599fn default_http_client() -> Result<reqwest::Client> {
1600    reqwest::Client::builder()
1601        .timeout(DEFAULT_TIMEOUT)
1602        .redirect(reqwest::redirect::Policy::none())
1603        .build()
1604        .map_err(|e| Error::InvalidRequest(format!("cannot build an HTTP client: {e}")))
1605}
1606
1607fn page_size(page_size: u32) -> Result<u32> {
1608    if page_size == 0 || page_size > MAX_PAGE_SIZE {
1609        return Err(Error::InvalidRequest(format!(
1610            "a page of {page_size} is not one Scan serves: it takes 1 to {MAX_PAGE_SIZE}"
1611        )));
1612    }
1613    Ok(page_size)
1614}
1615
1616/// Set a field of a JSON object built on the line above. `object[key] = …`
1617/// does the same and panics when `object` is not an object.
1618fn set(object: &mut Value, key: &str, value: Value) {
1619    if let Some(fields) = object.as_object_mut() {
1620        fields.insert(key.to_string(), value);
1621    }
1622}
1623
1624/// The body of a history read: where to read on from, and how much.
1625fn history_request(after: Option<&HistoryPosition>, size: u32) -> Result<Value> {
1626    let mut body = serde_json::json!({ "page_size": page_size(size)? });
1627    if let Some(after) = after {
1628        let after = serde_json::to_value(after).map_err(|e| {
1629            Error::InvalidRequest(format!("a history position that is not JSON: {e}"))
1630        })?;
1631        set(&mut body, "after", after);
1632    }
1633    Ok(body)
1634}
1635
1636/// One place where a non-success status becomes an error and a body becomes a
1637/// value, so every call reports failure the same way.
1638async fn decode<T: serde::de::DeserializeOwned>(
1639    response: reqwest::Response,
1640    url: &str,
1641) -> Result<T> {
1642    let status = response.status();
1643    let body = if status.is_success() {
1644        read_body_from(response, MAX_RESPONSE_BYTES, url, SCAN).await?
1645    } else {
1646        read_error_body(response, url, SCAN).await?
1647    };
1648    if !status.is_success() {
1649        // Splice's error body is `{"error": "…"}`; anything else is passed
1650        // through. The body stays the body, since the shared error model
1651        // reads it; the URL is in the log line.
1652        tracing::warn!(%url, status = status.as_u16(), "Scan answered with an error");
1653        let message = serde_json::from_str::<ErrorResponse>(&body)
1654            .map(|e| e.error)
1655            .unwrap_or(body);
1656        return Err(Error::http_at(status.as_u16(), truncate(&message), url));
1657    }
1658    serde_json::from_str(&body).map_err(|e| {
1659        Error::UnexpectedResponse(format!(
1660            "{url} returned a body this does not understand: {e}"
1661        ))
1662    })
1663}
1664
1665#[cfg(test)]
1666#[allow(clippy::unwrap_used, clippy::expect_used)]
1667mod tests {
1668    use super::*;
1669
1670    fn contract(contract_id: &str, payload: Value) -> ContractWithState {
1671        ContractWithState {
1672            contract: ScanContract {
1673                template_id: "pkg:Splice.Round:OpenMiningRound".to_string(),
1674                contract_id: contract_id.to_string(),
1675                payload,
1676                created_event_blob: base64::engine::general_purpose::STANDARD.encode([1, 2, 3]),
1677                created_at: "2026-11-26T10:00:00Z".to_string(),
1678            },
1679            synchronizer_id: Some("global-domain::1220aa".to_string()),
1680        }
1681    }
1682
1683    fn round(number: i64, opens_at: &str) -> ContractWithState {
1684        contract(
1685            &format!("00round{number}"),
1686            serde_json::json!({
1687                "round": { "number": number.to_string() },
1688                "opensAt": opens_at,
1689                "targetClosesAt": "2026-11-26T12:00:00Z",
1690            }),
1691        )
1692    }
1693
1694    fn at(time: &str) -> Timestamp {
1695        serde_json::from_value(Value::from(time)).unwrap()
1696    }
1697
1698    /// Several rounds are open at once and the newest has usually not reached
1699    /// its opening time. The one to use is the highest that has: the lowest
1700    /// is archived next, and the one above the highest is not usable yet.
1701    #[test]
1702    fn the_latest_open_round_is_the_highest_one_whose_opening_time_has_come() {
1703        let rounds = MiningRounds {
1704            open: vec![
1705                round(11, "2026-11-26T10:10:00.000000Z"),
1706                round(10, "2026-11-26T10:00:00.000000Z"),
1707                round(12, "2026-11-26T10:20:00.000000Z"),
1708            ],
1709            issuing: Vec::new(),
1710        };
1711        let pick = |now: &str| {
1712            rounds
1713                .latest_open(at(now))
1714                .map(|round| round.contract.contract_id.clone())
1715        };
1716        assert_eq!(pick("2026-11-26T10:15:00Z").unwrap(), "00round11");
1717        assert_eq!(pick("2026-11-26T10:05:00Z").unwrap(), "00round10");
1718        // The opening time itself counts as open.
1719        assert_eq!(pick("2026-11-26T10:20:00Z").unwrap(), "00round12");
1720        assert_eq!(pick("2026-11-27T00:00:00Z").unwrap(), "00round12");
1721
1722        // Before any round opens there is none, and that passes by itself.
1723        let error = pick("2026-11-26T09:00:00Z").unwrap_err();
1724        assert!(error.is_retriable(), "{error:?}");
1725        assert!(
1726            error.to_string().contains("3 open mining rounds"),
1727            "{error}"
1728        );
1729    }
1730
1731    /// A round number is a Daml `Int`, which JSON writes as a string, and
1732    /// compares as a number: round 9 is before round 10.
1733    #[test]
1734    fn round_numbers_compare_as_numbers_whether_written_as_text_or_not() {
1735        let mut as_number = round(9, "2026-11-26T09:50:00Z");
1736        as_number.contract.payload["round"]["number"] = Value::from(9);
1737        let rounds = MiningRounds {
1738            open: vec![round(10, "2026-11-26T10:00:00Z"), as_number],
1739            issuing: Vec::new(),
1740        };
1741        let latest = rounds.latest_open(at("2026-11-26T11:00:00Z")).unwrap();
1742        assert_eq!(latest.contract.contract_id, "00round10");
1743    }
1744
1745    #[test]
1746    fn a_round_that_is_not_an_open_mining_round_is_an_unexpected_response() {
1747        let rounds = MiningRounds {
1748            open: vec![contract("00odd", serde_json::json!({ "round": {} }))],
1749            issuing: Vec::new(),
1750        };
1751        let error = rounds.latest_open(at("2026-11-26T11:00:00Z")).unwrap_err();
1752        assert!(matches!(error, Error::UnexpectedResponse(_)), "{error:?}");
1753        assert!(error.to_string().contains("00odd"), "{error}");
1754    }
1755
1756    /// gRPC takes the blob as bytes and the JSON API as the base64 Scan sent,
1757    /// and both name the synchronizer the contract is on.
1758    #[test]
1759    fn a_contract_is_disclosed_as_bytes_for_grpc_and_base64_for_json() {
1760        let rules = contract("00rules", serde_json::json!({}));
1761        let disclosed = rules.disclosed().unwrap();
1762        assert_eq!(disclosed.contract_id, "00rules");
1763        assert_eq!(disclosed.created_event_blob, [1, 2, 3]);
1764        assert_eq!(disclosed.synchronizer_id, "global-domain::1220aa");
1765        let template = disclosed.template_id.unwrap();
1766        assert_eq!(
1767            (
1768                template.package_id.as_str(),
1769                template.module_name.as_str(),
1770                template.entity_name.as_str()
1771            ),
1772            ("pkg", "Splice.Round", "OpenMiningRound")
1773        );
1774
1775        let json = rules.disclosed_json().unwrap();
1776        assert_eq!(json["createdEventBlob"], "AQID");
1777        assert_eq!(json["synchronizerId"], "global-domain::1220aa");
1778        assert_eq!(json["templateId"], "pkg:Splice.Round:OpenMiningRound");
1779    }
1780
1781    #[test]
1782    fn a_contract_that_cannot_be_disclosed_says_why() {
1783        let mut in_transit = contract("00moving", serde_json::json!({}));
1784        in_transit.synchronizer_id = None;
1785        let error = in_transit.disclosed().unwrap_err();
1786        assert!(error.is_retriable(), "{error:?}");
1787        assert!(in_transit.disclosed_json().is_err());
1788
1789        for template_id in ["pkg:Module", "pkg:Module:Entity:Extra", "::", ""] {
1790            let mut odd = contract("00odd", serde_json::json!({}));
1791            odd.contract.template_id = template_id.to_string();
1792            let error = odd.disclosed().unwrap_err();
1793            assert!(matches!(error, Error::UnexpectedResponse(_)), "{error:?}");
1794        }
1795
1796        let mut odd = contract("00blob", serde_json::json!({}));
1797        odd.contract.created_event_blob = "not base64!!".to_string();
1798        let error = odd.disclosed().unwrap_err();
1799        assert!(error.to_string().contains("00blob"), "{error}");
1800    }
1801
1802    /// The two kinds of update carry no tag: a transaction is the one with
1803    /// events, a reassignment the one with an event.
1804    #[test]
1805    fn updates_are_told_apart_by_their_fields() {
1806        let transaction: ScanUpdate = serde_json::from_value(serde_json::json!({
1807            "update_id": "1220tx",
1808            "migration_id": 4,
1809            "workflow_id": "",
1810            "record_time": "2026-11-26T10:00:00.000000Z",
1811            "synchronizer_id": "global-domain::1220aa",
1812            "effective_at": "2026-11-26T09:59:59.000000Z",
1813            "root_event_ids": ["1220tx:0"],
1814            "events_by_id": {
1815                "1220tx:0": {
1816                    "event_type": "exercised_event",
1817                    "event_id": "1220tx:0",
1818                    "contract_id": "00rules",
1819                    "template_id": "pkg:Splice.AmuletRules:AmuletRules",
1820                    "package_name": "splice-amulet",
1821                    "choice": "AmuletRules_Transfer",
1822                    "choice_argument": {},
1823                    "child_event_ids": ["1220tx:1"],
1824                    "exercise_result": {},
1825                    "consuming": false,
1826                    "acting_parties": ["alice::1220"],
1827                },
1828                "1220tx:1": {
1829                    "event_type": "created_event",
1830                    "event_id": "1220tx:1",
1831                    "contract_id": "00amulet",
1832                    "template_id": "pkg:Splice.Amulet:Amulet",
1833                    "package_name": "splice-amulet",
1834                    "create_arguments": { "owner": "bob::1220" },
1835                    "created_at": "2026-11-26T09:59:59.000000Z",
1836                    "signatories": ["DSO::1220"],
1837                    "observers": [],
1838                },
1839            },
1840        }))
1841        .unwrap();
1842        assert_eq!(transaction.update_id(), "1220tx");
1843        assert_eq!(
1844            transaction.position(),
1845            HistoryPosition {
1846                migration_id: 4,
1847                record_time: "2026-11-26T10:00:00.000000Z".to_string(),
1848            }
1849        );
1850        let ScanUpdate::Transaction(transaction) = transaction else {
1851            panic!("a transaction");
1852        };
1853        assert!(matches!(
1854            transaction.events_by_id["1220tx:0"],
1855            ScanEvent::Exercised(_)
1856        ));
1857        assert!(matches!(
1858            transaction.events_by_id["1220tx:1"],
1859            ScanEvent::Created(_)
1860        ));
1861
1862        let unassigned: ScanUpdate = serde_json::from_value(serde_json::json!({
1863            "update_id": "1220out",
1864            "offset": "000a",
1865            "record_time": "2026-11-26T10:01:00.000000Z",
1866            "event": {
1867                "submitter": "alice::1220",
1868                "source_synchronizer": "one::1220",
1869                "target_synchronizer": "two::1220",
1870                "migration_id": 5,
1871                "unassign_id": "u1",
1872                "reassignment_counter": 1,
1873                "contract_id": "00moving",
1874            },
1875        }))
1876        .unwrap();
1877        assert_eq!(unassigned.position().migration_id, 5);
1878        assert!(matches!(
1879            unassigned,
1880            ScanUpdate::Reassignment(ScanReassignment {
1881                event: ReassignmentEvent::Unassignment(_),
1882                ..
1883            })
1884        ));
1885
1886        let neither = serde_json::from_value::<ScanUpdate>(serde_json::json!({
1887            "update_id": "1220odd",
1888        }))
1889        .unwrap_err();
1890        assert!(neither.to_string().contains("events_by_id"), "{neither}");
1891    }
1892
1893    /// The last entry of an event page is what the next page is read from,
1894    /// and it can be a verdict with no update: a transaction the mediator
1895    /// rejected. Its position comes from the verdict then.
1896    #[test]
1897    fn an_event_entry_has_a_position_with_or_without_an_update() {
1898        let rejected: ScanEventItem = serde_json::from_value(serde_json::json!({
1899            "update": null,
1900            "verdict": {
1901                "update_id": "1220rejected",
1902                "migration_id": 4,
1903                "domain_id": "global-domain::1220aa",
1904                "record_time": "2026-11-26T10:02:00.000000Z",
1905                "finalization_time": "2026-11-26T10:02:01.000000Z",
1906                "submitting_parties": ["alice::1220"],
1907                "submitting_participant_uid": "participant::1220",
1908                "verdict_result": "VERDICT_RESULT_REJECTED",
1909                "mediator_group": 0,
1910                "transaction_views": { "views": [], "root_views": [] },
1911            },
1912            "asset_activity_records": [],
1913            "submitting_app_provider": "provider::1220",
1914        }))
1915        .unwrap();
1916        assert!(rejected.update.is_none());
1917        assert_eq!(
1918            rejected.position(),
1919            Some(HistoryPosition {
1920                migration_id: 4,
1921                record_time: "2026-11-26T10:02:00.000000Z".to_string(),
1922            })
1923        );
1924        assert_eq!(
1925            rejected.submitting_app_provider.as_deref(),
1926            Some("provider::1220")
1927        );
1928        assert!(rejected.asset_activity_records.is_some());
1929
1930        let empty: ScanEventItem = serde_json::from_value(serde_json::json!({})).unwrap();
1931        assert_eq!(empty.position(), None);
1932    }
1933
1934    /// The position serializes as the `after` object the history reads take.
1935    #[test]
1936    fn a_history_position_is_the_after_of_the_next_page() {
1937        let after = HistoryPosition {
1938            migration_id: 4,
1939            record_time: "2026-11-26T10:00:00.000000Z".to_string(),
1940        };
1941        assert_eq!(
1942            history_request(Some(&after), 50).unwrap(),
1943            serde_json::json!({
1944                "page_size": 50,
1945                "after": {
1946                    "after_migration_id": 4,
1947                    "after_record_time": "2026-11-26T10:00:00.000000Z",
1948                },
1949            })
1950        );
1951        assert_eq!(
1952            history_request(None, 1).unwrap(),
1953            serde_json::json!({ "page_size": 1 })
1954        );
1955        for size in [0, 1001] {
1956            let error = history_request(None, size).unwrap_err();
1957            assert!(matches!(error, Error::InvalidRequest(_)), "{error:?}");
1958        }
1959    }
1960}