Skip to main content

talus_sui_move_runtime/
lib.rs

1#![doc = include_str!("../README.md")]
2#![deny(missing_docs)]
3
4mod effects;
5mod handles;
6mod tx;
7
8pub use crate::effects::TombstoneReason;
9pub use crate::handles::{CursorSnapshot, Object, ReceivingObject, SharedObject};
10pub use crate::tx::{
11    BcsValue, CheckpointWaitOutcome, CommandOutputs, EnsureSuccessError, Finality, InspectOptions,
12    InspectReceipt, ObservedFinality, Receipt, SimulateOptions, SimulationReceipt, TxOptions,
13};
14
15use std::time::Duration;
16
17/// Public alias for `sui_crypto::SuiSigner` used by [`Runtime`] and [`Tx`].
18///
19/// This lets generated bindings name the signer bound as `talus_sui_move_runtime::SuiSigner` without
20/// requiring consumers to depend on `sui-crypto` directly.
21pub use sui_crypto::SuiSigner;
22use sui_sdk_types::{Address, Mutability, ProgrammableTransaction, TransactionEffects, TypeTag};
23
24/// Errors produced by `talus-sui-move-runtime`.
25///
26/// This is a small umbrella enum that preserves the main failure boundary:
27/// - building a PTB (`Build`)
28/// - submitting/waiting (`Tx`)
29/// - fetching objects for handles over Sui gRPC (`Grpc`)
30/// - simulation/inspection (`Simulate`)
31#[derive(thiserror::Error, Debug)]
32pub enum Error {
33    /// Building a PTB failed.
34    #[error(transparent)]
35    Build(#[from] talus_sui_move_ptb::BuildError),
36
37    /// Constructing a generated Move call failed.
38    #[error(transparent)]
39    CallSpec(#[from] talus_sui_move_call::CallSpecError),
40
41    /// Signing or submitting failed.
42    #[error(transparent)]
43    Tx(#[from] tx::TxError),
44
45    /// Fetching data from Sui gRPC failed.
46    #[error(transparent)]
47    Grpc(#[from] tx::GrpcError),
48
49    /// Simulating or inspecting failed.
50    #[error(transparent)]
51    Simulate(#[from] tx::SimulateError),
52
53    /// The transaction executed with failure.
54    #[error(transparent)]
55    Execution(#[from] EnsureSuccessError),
56
57    /// Decoding Move contents failed.
58    #[error("decode object {object_id}: {source}")]
59    Decode {
60        /// Object id that was being decoded.
61        object_id: Address,
62        /// Underlying verification/BCS error.
63        #[source]
64        source: talus_sui_move::DecodeError,
65    },
66
67    /// The requested object kind does not match on chain ownership.
68    #[error("object {object_id} is {actual}, expected {expected}")]
69    ObjectKind {
70        /// Object id that was fetched.
71        object_id: Address,
72        /// Expected kind (for the API used).
73        expected: &'static str,
74        /// Actual kind from gRPC.
75        actual: &'static str,
76    },
77}
78
79/// Sui gRPC client used by the runtime.
80pub type GrpcClient = sui_rpc::Client;
81
82/// Runtime that owns a Sui gRPC client, signer, and handle cursor.
83///
84/// This is the entry point for the Read → Tx → Commit mental model:
85/// - [`Runtime::read`] for fetching/constructing typed handles
86/// - [`Runtime::tx`] for simulating/inspecting/committing PTBs
87///
88/// # Runtime handles
89///
90/// Handles returned by [`Read::object`] and [`Read::receiving_object`] are **interned** in the
91/// runtime’s cursor (your local frontier) by `object_id`. Clones of the same handle share the same
92/// internal cell, so they all see updates.
93///
94/// After [`Tx::commit`], the runtime decodes `TransactionEffects` from gRPC, derives a patch from
95/// those effects, and applies it to the cursor. This updates any live handle cells whose object id
96/// appears in the effects.
97///
98/// This is the core ergonomic win: you can store typed handles in normal Rust structs without
99/// threading `&mut` everywhere just to keep `ObjectReference`s current.
100///
101/// # Example
102/// ```rust,no_run
103/// use talus_sui_move_runtime::prelude::*;
104/// use sui_sdk_types::{PersonalMessage, Transaction, UserSignature};
105///
106/// # #[derive(Clone)]
107/// # struct DummySigner;
108/// # impl sui_crypto::SuiSigner for DummySigner {
109/// #     fn sign_transaction(&self, _tx: &Transaction) -> Result<UserSignature, sui_crypto::SignatureError> {
110/// #         unimplemented!("provide a real signer")
111/// #     }
112/// #     fn sign_personal_message(&self, _msg: &PersonalMessage<'_>) -> Result<UserSignature, sui_crypto::SignatureError> {
113/// #         unimplemented!("provide a real signer")
114/// #     }
115/// # }
116///
117/// let client = GrpcClient::new(GrpcClient::TESTNET_FULLNODE).unwrap();
118/// let signer = DummySigner;
119/// let mut rt = Runtime::new(client, signer);
120/// # let _ = &mut rt;
121/// ```
122pub struct Runtime<S> {
123    client: GrpcClient,
124    signer: S,
125    cursor: handles::Cursor,
126    wait_timeout: Duration,
127    default_gas_budget: u64,
128}
129
130impl<S: SuiSigner> Runtime<S> {
131    /// Create a runtime from a Sui gRPC client and a signer.
132    pub fn new(client: GrpcClient, signer: S) -> Self {
133        Self {
134            client,
135            signer,
136            cursor: handles::Cursor::default(),
137            wait_timeout: Duration::from_secs(30),
138            default_gas_budget: 2_000_000,
139        }
140    }
141
142    /// Replace the runtime cursor with a previously captured snapshot.
143    ///
144    /// Prefer calling this immediately after [`Runtime::new`] and before creating any handles owned
145    /// by the runtime.
146    pub fn with_cursor_snapshot(mut self, snapshot: CursorSnapshot) -> Self {
147        self.cursor = handles::Cursor::from_snapshot(snapshot);
148        self
149    }
150
151    /// Snapshot the runtime cursor (your local frontier).
152    pub fn cursor_snapshot(&self) -> CursorSnapshot {
153        self.cursor.snapshot()
154    }
155
156    /// Fetch transaction effects by digest and advance the runtime cursor.
157    ///
158    /// This is the recovery escape hatch for cases where you have a transaction digest but do not
159    /// have effects locally (for example, a receipt that was persisted without `effects`, or
160    /// a receipt returned by a gRPC node that did not include `effects.bcs`).
161    ///
162    /// If the transaction effects are returned by gRPC, the runtime derives an effects patch and
163    /// applies it to its cursor, updating any matching handles owned by the runtime.
164    pub async fn sync_transaction(
165        &mut self,
166        digest: sui_sdk_types::Digest,
167    ) -> Result<Option<TransactionEffects>, Error> {
168        let effects = tx::fetch_transaction_effects(&mut self.client, digest).await?;
169        if let Some(effects) = &effects {
170            self.apply_patch(effects);
171        }
172        Ok(effects)
173    }
174
175    /// Override the default checkpoint wait timeout used by [`Tx::commit`].
176    pub fn with_wait_timeout(mut self, timeout: Duration) -> Self {
177        self.wait_timeout = timeout;
178        self
179    }
180
181    /// Override the default gas budget used when none is provided.
182    pub fn with_default_gas_budget(mut self, budget: u64) -> Self {
183        self.default_gas_budget = budget;
184        self
185    }
186
187    /// Create a read view for fetching typed handles.
188    pub fn read(&mut self) -> Read<'_, S> {
189        Read { rt: self }
190    }
191
192    /// Create a transaction view for the given sender.
193    ///
194    /// The returned [`Tx`] view contains the execution actions:
195    /// - [`Tx::simulate`] (checks enabled, no mutation)
196    /// - [`Tx::inspect`] (checks disabled + command outputs)
197    /// - [`Tx::commit`] (sign/submit/wait + update handles)
198    pub fn tx(&mut self, sender: Address) -> Tx<'_, S> {
199        Tx {
200            rt: self,
201            sender,
202            ptb: talus_sui_move_ptb::PtbBuilder::new(),
203        }
204    }
205
206    fn apply_patch(&self, effects: &TransactionEffects) {
207        self.cursor.apply_patch(effects);
208    }
209}
210
211/// Read view: read/fetch helpers and handle construction.
212///
213/// This view is intentionally read only with respect to the chain: it fetches data from gRPC and
214/// constructs typed handles, but it does not submit transactions.
215pub struct Read<'a, S> {
216    rt: &'a mut Runtime<S>,
217}
218
219impl<'a, S: SuiSigner> Read<'a, S> {
220    /// Mutable access to the underlying Sui gRPC client (escape hatch).
221    pub fn grpc_client_mut(&mut self) -> &mut GrpcClient {
222        &mut self.rt.client
223    }
224
225    /// Refresh the reference and owner information for an object id in the runtime cursor.
226    ///
227    /// This is the explicit escape hatch for external drift: if other transactions mutate an
228    /// object you care about, your local cursor does not update until you either commit through
229    /// this runtime or refresh explicitly.
230    ///
231    /// If the object does not exist, the cursor is tombstoned (if it was being tracked).
232    pub async fn refresh_id(&mut self, object_id: Address) -> Result<(), Error> {
233        match tx::fetch_object_reference_and_owner(&mut self.rt.client, object_id).await {
234            Ok(fetched) => {
235                self.rt
236                    .cursor
237                    .intern_untyped(fetched.reference, fetched.owner);
238                Ok(())
239            }
240            Err(err @ tx::GrpcError::Missing(_)) => {
241                self.rt
242                    .cursor
243                    .tombstone(object_id, TombstoneReason::NotExist);
244                Err(Error::Grpc(err))
245            }
246            Err(err) => Err(Error::Grpc(err)),
247        }
248    }
249
250    /// Refresh multiple object ids in sequence.
251    ///
252    /// This calls [`Read::refresh_id`] for each provided id.
253    pub async fn refresh_ids(
254        &mut self,
255        object_ids: impl IntoIterator<Item = Address>,
256    ) -> Result<(), Error> {
257        for object_id in object_ids {
258            self.refresh_id(object_id).await?;
259        }
260        Ok(())
261    }
262
263    /// Refresh the reference and owner information for a handle owned by the runtime.
264    ///
265    /// This is the explicit escape hatch for external drift: if another transaction changes an
266    /// owned object (or rotates its `ObjectReference`), your local cursor does not update until you
267    /// either commit through this runtime or refresh explicitly.
268    pub async fn refresh<T: talus_sui_move::MoveStruct + talus_sui_move::HasKey>(
269        &mut self,
270        obj: &Object<T>,
271    ) -> Result<(), Error> {
272        self.refresh_id(obj.object_id()).await
273    }
274
275    /// Construct an object handle owned by the runtime by fetching its latest `ObjectReference` and
276    /// owner kind.
277    ///
278    /// The returned [`Object<T>`] is the default handle type used throughout this crate:
279    /// - owned/immutable objects convert to `Input::ImmutableOrOwned(ObjectReference)`
280    /// - objects with a shared input shape convert to `Input::Shared(SharedInput)` (immutable by default)
281    ///
282    /// If you need an explicit input mode, derive a view from the handle at the moment it matters:
283    /// - `obj.shared_immutable()?` / `obj.shared_mutable()?`
284    /// - `obj.receiving()?`
285    pub async fn object<T: talus_sui_move::MoveStruct + talus_sui_move::HasKey>(
286        &mut self,
287        object_id: Address,
288    ) -> Result<Object<T>, Error> {
289        let fetched =
290            match tx::fetch_object_reference_and_owner(&mut self.rt.client, object_id).await {
291                Ok(fetched) => fetched,
292                Err(err @ tx::GrpcError::Missing(_)) => {
293                    self.rt
294                        .cursor
295                        .tombstone(object_id, TombstoneReason::NotExist);
296                    return Err(Error::Grpc(err));
297                }
298                Err(err) => return Err(Error::Grpc(err)),
299            };
300
301        let kind = tx::classify_owner(&fetched.owner);
302        match kind {
303            tx::OwnerKind::Immutable | tx::OwnerKind::AddressOwned => {}
304            kind if kind.is_shared_like() => {}
305            other => {
306                return Err(Error::ObjectKind {
307                    object_id,
308                    expected: "immutable-or-owned or shared",
309                    actual: other.label(),
310                });
311            }
312        }
313
314        Ok(self
315            .rt
316            .cursor
317            .intern_object::<T>(fetched.reference, fetched.owner))
318    }
319
320    /// Fetch an object and decode its Move contents into `T`.
321    ///
322    /// This performs a tag check (`T::type_tag_static()` must match the on chain `TypeTag`) and
323    /// returns both:
324    /// - a handle owned by the runtime (`Object<T>`) and
325    /// - the decoded value (`T`).
326    pub async fn get<T: talus_sui_move::MoveStruct + talus_sui_move::HasKey>(
327        &mut self,
328        object_id: Address,
329    ) -> Result<(Object<T>, T), Error> {
330        let fetched =
331            match tx::fetch_object_reference_and_owner(&mut self.rt.client, object_id).await {
332                Ok(fetched) => fetched,
333                Err(err @ tx::GrpcError::Missing(_)) => {
334                    self.rt
335                        .cursor
336                        .tombstone(object_id, TombstoneReason::NotExist);
337                    return Err(Error::Grpc(err));
338                }
339                Err(err) => return Err(Error::Grpc(err)),
340            };
341
342        let obj = self
343            .rt
344            .cursor
345            .intern_object::<T>(fetched.reference, fetched.owner);
346
347        let got = TypeTag::Struct(Box::new(fetched.struct_tag));
348        let decoded = talus_sui_move::MoveInstance::<T>::from_raw_type(got, &fetched.contents)
349            .map_err(|source| Error::Decode { object_id, source })?
350            .value;
351
352        Ok((obj, decoded))
353    }
354
355    /// Fetch an object and decode its contents as `T` without verifying the on chain type tag.
356    pub async fn get_unchecked<T: talus_sui_move::MoveStruct + talus_sui_move::HasKey>(
357        &mut self,
358        object_id: Address,
359    ) -> Result<(Object<T>, T), Error> {
360        let fetched =
361            match tx::fetch_object_reference_and_owner(&mut self.rt.client, object_id).await {
362                Ok(fetched) => fetched,
363                Err(err @ tx::GrpcError::Missing(_)) => {
364                    self.rt
365                        .cursor
366                        .tombstone(object_id, TombstoneReason::NotExist);
367                    return Err(Error::Grpc(err));
368                }
369                Err(err) => return Err(Error::Grpc(err)),
370            };
371
372        let obj = self
373            .rt
374            .cursor
375            .intern_object::<T>(fetched.reference, fetched.owner);
376        let decoded = T::from_bcs(&fetched.contents).map_err(|err| Error::Decode {
377            object_id,
378            source: err.into(),
379        })?;
380
381        Ok((obj, decoded))
382    }
383
384    /// Fetch and decode the latest on chain contents for an object handle owned by the runtime.
385    ///
386    /// This performs a tag check and refreshes the handle reference and owner information in the
387    /// cursor.
388    pub async fn decode<T: talus_sui_move::MoveStruct + talus_sui_move::HasKey>(
389        &mut self,
390        obj: &Object<T>,
391    ) -> Result<T, Error> {
392        let object_id = obj.object_id();
393        let fetched =
394            match tx::fetch_object_reference_and_owner(&mut self.rt.client, object_id).await {
395                Ok(fetched) => fetched,
396                Err(err @ tx::GrpcError::Missing(_)) => {
397                    self.rt
398                        .cursor
399                        .tombstone(object_id, TombstoneReason::NotExist);
400                    return Err(Error::Grpc(err));
401                }
402                Err(err) => return Err(Error::Grpc(err)),
403            };
404
405        self.rt
406            .cursor
407            .intern_object::<T>(fetched.reference, fetched.owner);
408
409        let got = TypeTag::Struct(Box::new(fetched.struct_tag));
410        let decoded = talus_sui_move::MoveInstance::<T>::from_raw_type(got, &fetched.contents)
411            .map_err(|source| Error::Decode { object_id, source })?
412            .value;
413
414        Ok(decoded)
415    }
416
417    /// Fetch and decode the latest on chain contents for an object handle owned by the runtime,
418    /// without tag verification.
419    ///
420    /// This refreshes the reference and owner information for the handle in the cursor.
421    pub async fn decode_unchecked<T: talus_sui_move::MoveStruct + talus_sui_move::HasKey>(
422        &mut self,
423        obj: &Object<T>,
424    ) -> Result<T, Error> {
425        let object_id = obj.object_id();
426        let fetched =
427            match tx::fetch_object_reference_and_owner(&mut self.rt.client, object_id).await {
428                Ok(fetched) => fetched,
429                Err(err @ tx::GrpcError::Missing(_)) => {
430                    self.rt
431                        .cursor
432                        .tombstone(object_id, TombstoneReason::NotExist);
433                    return Err(Error::Grpc(err));
434                }
435                Err(err) => return Err(Error::Grpc(err)),
436            };
437
438        self.rt
439            .cursor
440            .intern_object::<T>(fetched.reference, fetched.owner);
441
442        T::from_bcs(&fetched.contents).map_err(|err| Error::Decode {
443            object_id,
444            source: err.into(),
445        })
446    }
447
448    /// Construct a receiving object handle by fetching the latest `ObjectReference`.
449    ///
450    /// This corresponds to Sui's `Input::Receiving`.
451    ///
452    /// Receiving is a transaction input mode (the Move framework type
453    /// `sui::transfer::Receiving<T>`), not an on chain owner kind. This helper only fetches the
454    /// latest reference and does not validate that the object is valid to receive in the current
455    /// transaction.
456    pub async fn receiving_object<T: talus_sui_move::MoveStruct + talus_sui_move::HasKey>(
457        &mut self,
458        object_id: Address,
459    ) -> Result<ReceivingObject<T>, Error> {
460        let fetched =
461            match tx::fetch_object_reference_and_owner(&mut self.rt.client, object_id).await {
462                Ok(fetched) => fetched,
463                Err(err @ tx::GrpcError::Missing(_)) => {
464                    self.rt
465                        .cursor
466                        .tombstone(object_id, TombstoneReason::NotExist);
467                    return Err(Error::Grpc(err));
468                }
469                Err(err) => return Err(Error::Grpc(err)),
470            };
471        Ok(self
472            .rt
473            .cursor
474            .intern_receiving_object::<T>(fetched.reference, fetched.owner))
475    }
476
477    /// Construct a shared object handle by fetching its initial shared version.
478    ///
479    /// This corresponds to Sui's `Input::Shared`.
480    pub async fn shared_object<T: talus_sui_move::MoveStruct + talus_sui_move::HasKey>(
481        &mut self,
482        object_id: Address,
483        mutability: Mutability,
484    ) -> Result<SharedObject<T>, Error> {
485        let fetched =
486            match tx::fetch_object_reference_and_owner(&mut self.rt.client, object_id).await {
487                Ok(fetched) => fetched,
488                Err(err @ tx::GrpcError::Missing(_)) => {
489                    self.rt
490                        .cursor
491                        .tombstone(object_id, TombstoneReason::NotExist);
492                    return Err(Error::Grpc(err));
493                }
494                Err(err) => return Err(Error::Grpc(err)),
495            };
496
497        let kind = tx::classify_owner(&fetched.owner);
498        let Some(initial_shared_version) = kind.shared_start_version() else {
499            return Err(Error::ObjectKind {
500                object_id,
501                expected: "shared",
502                actual: kind.label(),
503            });
504        };
505
506        Ok(SharedObject::new(
507            object_id,
508            initial_shared_version,
509            mutability,
510        ))
511    }
512
513    /// Convenience: immutable shared input.
514    pub async fn shared_immutable<T: talus_sui_move::MoveStruct + talus_sui_move::HasKey>(
515        &mut self,
516        object_id: Address,
517    ) -> Result<SharedObject<T>, Error> {
518        self.shared_object(object_id, Mutability::Immutable).await
519    }
520
521    /// Convenience: mutable shared input.
522    pub async fn shared_mutable<T: talus_sui_move::MoveStruct + talus_sui_move::HasKey>(
523        &mut self,
524        object_id: Address,
525    ) -> Result<SharedObject<T>, Error> {
526        self.shared_object(object_id, Mutability::Mutable).await
527    }
528}
529
530/// Transaction builder: build, simulate/inspect, and commit a PTB.
531pub struct Tx<'a, S> {
532    rt: &'a mut Runtime<S>,
533    sender: Address,
534    ptb: talus_sui_move_ptb::PtbBuilder,
535}
536
537impl<'a, S: SuiSigner> Tx<'a, S> {
538    /// Borrow the underlying PTB builder.
539    ///
540    /// This is useful for accessing less common PTB commands without this crate adding extra
541    /// wrappers.
542    pub fn ptb(&self) -> &talus_sui_move_ptb::PtbBuilder {
543        &self.ptb
544    }
545
546    /// Mutably borrow the underlying PTB builder (escape hatch).
547    pub fn ptb_mut(&mut self) -> &mut talus_sui_move_ptb::PtbBuilder {
548        &mut self.ptb
549    }
550
551    /// Add a raw input to the transaction and return its `Argument::Input`.
552    pub fn input(
553        &mut self,
554        input: talus_sui_move_call::CallArg,
555    ) -> Result<sui_sdk_types::Argument, Error> {
556        Ok(self.ptb.input(input)?)
557    }
558
559    /// Convert a typed value into an input and return its `Argument::Input`.
560    pub fn arg<A: talus_sui_move_call::ToCallArg>(
561        &mut self,
562        value: &A,
563    ) -> Result<sui_sdk_types::Argument, Error> {
564        Ok(self.ptb.arg(value)?)
565    }
566
567    /// Add a Move call command from a typed [`talus_sui_move_call::CallSpec`].
568    pub fn call(
569        &mut self,
570        spec: talus_sui_move_call::CallSpec,
571    ) -> Result<sui_sdk_types::Argument, Error> {
572        Ok(self.ptb.call(spec)?)
573    }
574
575    /// The gas argument (`Argument::Gas`).
576    ///
577    /// This is useful when building native PTB commands that can refer to the gas coin.
578    pub fn gas(&self) -> sui_sdk_types::Argument {
579        self.ptb.gas()
580    }
581
582    /// Add a `TransferObjects` command.
583    pub fn transfer_objects(
584        &mut self,
585        objects: Vec<sui_sdk_types::Argument>,
586        address: sui_sdk_types::Argument,
587    ) -> Result<(), Error> {
588        Ok(self.ptb.transfer_objects(objects, address)?)
589    }
590
591    /// Add a `SplitCoins` command.
592    pub fn split_coins(
593        &mut self,
594        coin: sui_sdk_types::Argument,
595        amounts: Vec<sui_sdk_types::Argument>,
596    ) -> Result<sui_sdk_types::Argument, Error> {
597        Ok(self.ptb.split_coins(coin, amounts)?)
598    }
599
600    /// Add a `MergeCoins` command.
601    pub fn merge_coins(
602        &mut self,
603        destination: sui_sdk_types::Argument,
604        sources: Vec<sui_sdk_types::Argument>,
605    ) -> Result<(), Error> {
606        Ok(self.ptb.merge_coins(destination, sources)?)
607    }
608
609    /// Add a `MakeMoveVector` command.
610    pub fn make_move_vector(
611        &mut self,
612        type_: Option<TypeTag>,
613        elements: Vec<sui_sdk_types::Argument>,
614    ) -> Result<sui_sdk_types::Argument, Error> {
615        Ok(self.ptb.make_move_vector(type_, elements)?)
616    }
617
618    /// Add a `Publish` command.
619    pub fn publish(
620        &mut self,
621        modules: Vec<Vec<u8>>,
622        dependencies: Vec<Address>,
623    ) -> Result<sui_sdk_types::Argument, Error> {
624        Ok(self.ptb.publish(modules, dependencies)?)
625    }
626
627    /// Finish and return the built PTB without submitting it.
628    pub fn finish_ptb(self) -> ProgrammableTransaction {
629        self.ptb.finish()
630    }
631
632    /// Commit the built PTB and wait for checkpoint inclusion.
633    ///
634    /// If checkpoint waiting times out (or the checkpoint stream errors), this still returns a
635    /// [`Receipt`] with `digest` and any decoded effects, and marks the observed finality as
636    /// `Executed`.
637    ///
638    /// On success, the runtime applies a patch derived from effects to its cursor, updating
639    /// all live [`Object`] and [`ReceivingObject`] handles that match changed objects.
640    pub async fn commit(self) -> Result<Receipt, Error> {
641        self.commit_with(TxOptions::default()).await
642    }
643
644    /// Commit the built PTB using explicit transaction options.
645    pub async fn commit_with(self, opts: TxOptions) -> Result<Receipt, Error> {
646        let Tx { rt, sender, ptb } = self;
647        Self::commit_ptb_with_inner(rt, sender, ptb.finish(), opts).await
648    }
649
650    /// Commit an already built PTB and wait for checkpoint inclusion.
651    ///
652    /// This is the escape hatch for advanced PTB building (coin ops, wiring, etc).
653    pub async fn commit_ptb(self, ptb: ProgrammableTransaction) -> Result<Receipt, Error> {
654        self.commit_ptb_with(ptb, TxOptions::default()).await
655    }
656
657    /// Commit an already built PTB using explicit transaction options.
658    pub async fn commit_ptb_with(
659        self,
660        ptb: ProgrammableTransaction,
661        opts: TxOptions,
662    ) -> Result<Receipt, Error> {
663        let Tx { rt, sender, .. } = self;
664        Self::commit_ptb_with_inner(rt, sender, ptb, opts).await
665    }
666
667    async fn commit_ptb_with_inner(
668        rt: &mut Runtime<S>,
669        sender: Address,
670        ptb: ProgrammableTransaction,
671        opts: TxOptions,
672    ) -> Result<Receipt, Error> {
673        let receipt = tx::submit_and_wait(
674            &mut rt.client,
675            &rt.signer,
676            sender,
677            ptb,
678            opts,
679            rt.default_gas_budget,
680            rt.wait_timeout,
681        )
682        .await?;
683
684        if let Some(effects) = &receipt.effects {
685            rt.apply_patch(effects);
686        }
687
688        Ok(receipt)
689    }
690
691    /// Simulate the built PTB (checks enabled) without mutating chain state.
692    ///
693    /// This does not update handles owned by the runtime.
694    pub async fn simulate(&mut self) -> Result<SimulationReceipt, Error> {
695        self.simulate_with(SimulateOptions::default()).await
696    }
697
698    /// Simulate the built PTB with explicit simulation options.
699    ///
700    /// This does not update handles owned by the runtime.
701    pub async fn simulate_with(
702        &mut self,
703        opts: SimulateOptions,
704    ) -> Result<SimulationReceipt, Error> {
705        let ptb = self.ptb.clone().finish();
706        self.simulate_ptb_with(ptb, opts).await
707    }
708
709    /// Simulate an already built PTB, with checks enabled, without mutating chain state.
710    ///
711    /// This does not update handles owned by the runtime.
712    pub async fn simulate_ptb(
713        &mut self,
714        ptb: ProgrammableTransaction,
715    ) -> Result<SimulationReceipt, Error> {
716        self.simulate_ptb_with(ptb, SimulateOptions::default())
717            .await
718    }
719
720    /// Simulate an already built PTB with explicit simulation options.
721    ///
722    /// This does not update handles owned by the runtime.
723    pub async fn simulate_ptb_with(
724        &mut self,
725        ptb: ProgrammableTransaction,
726        opts: SimulateOptions,
727    ) -> Result<SimulationReceipt, Error> {
728        Ok(tx::simulate_ptb(&mut self.rt.client, self.sender, ptb, opts).await?)
729    }
730
731    /// Inspect the built PTB (checks disabled) to retrieve command outputs for debugging.
732    ///
733    /// This does not update handles owned by the runtime.
734    pub async fn inspect(&mut self) -> Result<InspectReceipt, Error> {
735        self.inspect_with(InspectOptions::default()).await
736    }
737
738    /// Inspect the built PTB with explicit inspect options.
739    ///
740    /// This does not update handles owned by the runtime.
741    pub async fn inspect_with(&mut self, opts: InspectOptions) -> Result<InspectReceipt, Error> {
742        let ptb = self.ptb.clone().finish();
743        self.inspect_ptb_with(ptb, opts).await
744    }
745
746    /// Inspect an already built PTB, with checks disabled, to retrieve command outputs for debugging.
747    ///
748    /// This does not update handles owned by the runtime.
749    pub async fn inspect_ptb(
750        &mut self,
751        ptb: ProgrammableTransaction,
752    ) -> Result<InspectReceipt, Error> {
753        self.inspect_ptb_with(ptb, InspectOptions::default()).await
754    }
755
756    /// Inspect an already built PTB with explicit inspect options.
757    ///
758    /// This does not update handles owned by the runtime.
759    pub async fn inspect_ptb_with(
760        &mut self,
761        ptb: ProgrammableTransaction,
762        opts: InspectOptions,
763    ) -> Result<InspectReceipt, Error> {
764        Ok(tx::inspect_ptb(&mut self.rt.client, self.sender, ptb, opts).await?)
765    }
766}
767
768/// Common exports for downstream code.
769///
770/// This prelude is meant for application code and examples. It includes:
771/// - `talus-sui-move-runtime` core types
772/// - `talus-sui-move-call` prelude (call building)
773/// - `talus-sui-move-ptb` prelude (PTB building)
774pub mod prelude {
775    pub use crate::{
776        BcsValue, CheckpointWaitOutcome, CommandOutputs, CursorSnapshot, EnsureSuccessError, Error,
777        Finality, GrpcClient, InspectOptions, InspectReceipt, Object, ObservedFinality, Read,
778        Receipt, ReceivingObject, Runtime, SharedObject, SimulateOptions, SimulationReceipt,
779        TombstoneReason, Tx, TxOptions,
780    };
781    pub use sui_sdk_types::Mutability;
782    pub use talus_sui_move_call::prelude::*;
783    pub use talus_sui_move_ptb::prelude::*;
784}
785
786/// Build and run a transaction in the Read → Tx → Commit mental model.
787///
788/// This macro is a small ergonomic wrapper around [`Runtime::tx`]. It builds a transaction using a
789/// temporary [`Tx`] builder and then runs exactly one action:
790/// - commit (default),
791/// - simulate (checks enabled), or
792/// - inspect (checks disabled + command outputs).
793///
794/// The macro returns a **future**, so callers use `.await`:
795///
796/// ```rust,no_run
797/// use talus_sui_move_runtime::prelude::*;
798///
799/// # async fn demo(mut rt: Runtime<impl sui_crypto::SuiSigner>, sender: sui_sdk_types::Address) -> Result<(), Error> {
800/// let receipt = talus_sui_move_runtime::tx!(&mut rt, sender => {
801///     CallSpec::new("0x1".parse().unwrap(), "m", "f").unwrap();
802/// })
803/// .await?;
804/// receipt.ensure_success()?;
805/// # Ok(())
806/// # }
807/// ```
808///
809/// # Forms
810///
811/// **Call list (default commit)**: each statement expression must evaluate to a `CallSpec`.
812///
813/// ```rust,no_run
814/// # use talus_sui_move_runtime::prelude::*;
815/// # async fn demo(mut rt: Runtime<impl sui_crypto::SuiSigner>, sender: sui_sdk_types::Address) -> Result<(), Error> {
816/// let _receipt = talus_sui_move_runtime::tx!(&mut rt, sender => {
817///     CallSpec::new("0x1".parse().unwrap(), "m", "f").unwrap();
818///     CallSpec::new("0x1".parse().unwrap(), "m", "g").unwrap();
819/// })
820/// .await?;
821/// # Ok(())
822/// # }
823/// ```
824///
825/// **Builder form**: opt into direct access to `Tx` (escape hatch for PTB wiring).
826///
827/// ```rust,no_run
828/// # use talus_sui_move_runtime::prelude::*;
829/// # async fn demo(mut rt: Runtime<impl sui_crypto::SuiSigner>, sender: sui_sdk_types::Address) -> Result<(), Error> {
830/// let _receipt = talus_sui_move_runtime::tx!(&mut rt, sender, tx => {
831///     let _out = tx.call(CallSpec::new("0x1".parse().unwrap(), "m", "f").unwrap())?;
832/// })
833/// .await?;
834/// # Ok(())
835/// # }
836/// ```
837///
838/// **Action variants**:
839///
840/// ```rust,no_run
841/// # use talus_sui_move_runtime::prelude::*;
842/// # async fn demo(mut rt: Runtime<impl sui_crypto::SuiSigner>, sender: sui_sdk_types::Address) -> Result<(), Error> {
843/// let _sim = talus_sui_move_runtime::tx!(simulate, &mut rt, sender => {
844///     CallSpec::new("0x1".parse().unwrap(), "m", "f").unwrap();
845/// })
846/// .await?;
847///
848/// let _dbg = talus_sui_move_runtime::tx!(inspect, &mut rt, sender => {
849///     CallSpec::new("0x1".parse().unwrap(), "m", "f").unwrap();
850/// })
851/// .await?;
852///
853/// let _receipt = talus_sui_move_runtime::tx!(
854///     commit_with(TxOptions { finality: Finality::Executed, ..Default::default() }),
855///     &mut rt,
856///     sender => {
857///         CallSpec::new("0x1".parse().unwrap(), "m", "f").unwrap();
858///     }
859/// )
860/// .await?;
861/// # Ok(())
862/// # }
863/// ```
864#[macro_export]
865macro_rules! tx {
866    (commit, $rt:expr, $sender:expr => { $($spec:expr);+ $(;)? }) => {{
867        async {
868            let mut __tx = ($rt).tx($sender);
869            $(
870                __tx.call($spec)?;
871            )+
872            __tx.commit().await
873        }
874    }};
875    (commit, $rt:expr, $sender:expr, $tx:ident => { $($body:tt)* }) => {{
876        async {
877            let mut $tx = ($rt).tx($sender);
878            { $($body)* }
879            $tx.commit().await
880        }
881    }};
882
883    (commit_with($opts:expr), $rt:expr, $sender:expr => { $($spec:expr);+ $(;)? }) => {{
884        async {
885            let mut __tx = ($rt).tx($sender);
886            $(
887                __tx.call($spec)?;
888            )+
889            __tx.commit_with($opts).await
890        }
891    }};
892    (commit_with($opts:expr), $rt:expr, $sender:expr, $tx:ident => { $($body:tt)* }) => {{
893        async {
894            let mut $tx = ($rt).tx($sender);
895            { $($body)* }
896            $tx.commit_with($opts).await
897        }
898    }};
899
900    (simulate, $rt:expr, $sender:expr => { $($spec:expr);+ $(;)? }) => {{
901        async {
902            let mut __tx = ($rt).tx($sender);
903            $(
904                __tx.call($spec)?;
905            )+
906            __tx.simulate().await
907        }
908    }};
909    (simulate, $rt:expr, $sender:expr, $tx:ident => { $($body:tt)* }) => {{
910        async {
911            let mut $tx = ($rt).tx($sender);
912            { $($body)* }
913            $tx.simulate().await
914        }
915    }};
916
917    (simulate_with($opts:expr), $rt:expr, $sender:expr => { $($spec:expr);+ $(;)? }) => {{
918        async {
919            let mut __tx = ($rt).tx($sender);
920            $(
921                __tx.call($spec)?;
922            )+
923            __tx.simulate_with($opts).await
924        }
925    }};
926    (simulate_with($opts:expr), $rt:expr, $sender:expr, $tx:ident => { $($body:tt)* }) => {{
927        async {
928            let mut $tx = ($rt).tx($sender);
929            { $($body)* }
930            $tx.simulate_with($opts).await
931        }
932    }};
933
934    (inspect, $rt:expr, $sender:expr => { $($spec:expr);+ $(;)? }) => {{
935        async {
936            let mut __tx = ($rt).tx($sender);
937            $(
938                __tx.call($spec)?;
939            )+
940            __tx.inspect().await
941        }
942    }};
943    (inspect, $rt:expr, $sender:expr, $tx:ident => { $($body:tt)* }) => {{
944        async {
945            let mut $tx = ($rt).tx($sender);
946            { $($body)* }
947            $tx.inspect().await
948        }
949    }};
950
951    (inspect_with($opts:expr), $rt:expr, $sender:expr => { $($spec:expr);+ $(;)? }) => {{
952        async {
953            let mut __tx = ($rt).tx($sender);
954            $(
955                __tx.call($spec)?;
956            )+
957            __tx.inspect_with($opts).await
958        }
959    }};
960    (inspect_with($opts:expr), $rt:expr, $sender:expr, $tx:ident => { $($body:tt)* }) => {{
961        async {
962            let mut $tx = ($rt).tx($sender);
963            { $($body)* }
964            $tx.inspect_with($opts).await
965        }
966    }};
967
968    ($rt:expr, $sender:expr => { $($spec:expr);+ $(;)? }) => {{
969        $crate::tx!(commit, $rt, $sender => { $($spec);+ })
970    }};
971    ($rt:expr, $sender:expr, $tx:ident => { $($body:tt)* }) => {{
972        $crate::tx!(commit, $rt, $sender, $tx => { $($body)* })
973    }};
974}