Skip to main content

sui_rpc/client/
transaction_execution.rs

1use super::Client;
2use super::TransactionStreamRequest;
3use super::TransactionStreamStart;
4use crate::field::FieldMaskUtil;
5use crate::proto::TryFromProtoError;
6use crate::proto::sui::rpc::v2::ExecuteTransactionRequest;
7use crate::proto::sui::rpc::v2::ExecuteTransactionResponse;
8use crate::proto::sui::rpc::v2::ExecutionError;
9use crate::proto::sui::rpc::v2::GetEpochRequest;
10use crate::proto::sui::rpc::v2::GetServiceInfoRequest;
11use crate::proto::sui::rpc::v2::GetTransactionRequest;
12use crate::proto::sui::rpc::v2::GetTransactionResponse;
13use crate::proto::sui::rpc::v2::TransactionFilter;
14use crate::proto::sui::rpc::v2::filter::transaction;
15use futures::TryStreamExt;
16use prost_types::FieldMask;
17use std::fmt;
18use std::time::Duration;
19use tonic::Response;
20
21/// Error types that can occur when executing a transaction and waiting for checkpoint
22#[derive(Debug)]
23#[non_exhaustive]
24pub enum ExecuteAndWaitError {
25    /// RPC Error (actual tonic::Status from the client/server)
26    RpcError(tonic::Status),
27    /// Request is missing the required transaction field
28    MissingTransaction,
29    /// Failed to parse/convert the transaction for digest calculation
30    ProtoConversionError(TryFromProtoError),
31    /// Transaction executed but checkpoint wait timed out
32    CheckpointTimeout(Response<ExecuteTransactionResponse>),
33    /// Transaction executed but the stream watching for its checkpoint failed
34    CheckpointStreamError {
35        response: Response<ExecuteTransactionResponse>,
36        error: tonic::Status,
37    },
38}
39
40impl std::fmt::Display for ExecuteAndWaitError {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            Self::RpcError(status) => write!(f, "RPC error: {status}"),
44            Self::MissingTransaction => {
45                write!(f, "Request is missing the required transaction field")
46            }
47            Self::ProtoConversionError(e) => write!(f, "Failed to convert transaction: {e}"),
48            Self::CheckpointTimeout(_) => {
49                write!(f, "Transaction executed but checkpoint wait timed out")
50            }
51            Self::CheckpointStreamError { error, .. } => {
52                write!(
53                    f,
54                    "Transaction executed but checkpoint stream had an error: {error}"
55                )
56            }
57        }
58    }
59}
60
61impl std::error::Error for ExecuteAndWaitError {
62    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
63        match self {
64            Self::RpcError(status) => Some(status),
65            Self::ProtoConversionError(e) => Some(e),
66            Self::CheckpointStreamError { error, .. } => Some(error),
67            Self::MissingTransaction => None,
68            Self::CheckpointTimeout(_) => None,
69        }
70    }
71}
72
73impl Client {
74    /// Executes a transaction and waits for it to be included in a checkpoint.
75    ///
76    /// Returns the execution response with `checkpoint` and `timestamp`
77    /// populated.
78    ///
79    /// The method:
80    /// 1. Reads the node's checkpoint height `C` with `GetServiceInfo`.
81    /// 2. Looks the transaction up with `GetTransaction`. A transaction that is
82    ///    already in a checkpoint (a resubmission, or the same transaction sent
83    ///    by someone else) is returned without being executed again.
84    /// 3. Executes the transaction while following the sender's transactions
85    ///    from checkpoint `C` with [`Client::stream_transactions`], and returns
86    ///    once the transaction appears. The stream replays checkpoints it has
87    ///    not seen and reconnects after transient failures, and the sender
88    ///    filter keeps it to the sender's own transactions.
89    ///
90    /// `timeout` bounds the wait that starts once execution returns. If it
91    /// expires, or the stream fails, the error still carries the execution
92    /// response.
93    ///
94    /// If execution fails, the ledger is checked once more: when the
95    /// transaction is in a checkpoint anyway (for example, a resubmission
96    /// raced the original submission), the committed transaction is returned
97    /// instead of the error.
98    ///
99    /// A response answered from the ledger is assembled from `GetTransaction`
100    /// using the request's read mask, so it carries the same fields an
101    /// execution response would, with `digest`, `checkpoint`, and `timestamp`
102    /// always populated.
103    ///
104    /// # Consistency
105    ///
106    /// The transaction being in a checkpoint does not mean every index
107    /// includes it: the List APIs (`ListTransactions`, `ListEvents`, ...) read
108    /// indexes that can trail the latest checkpoint.
109    ///
110    /// Each step can reach a different node when the client sits behind a load
111    /// balancer. If the lookup in step 2 reaches a node that is behind `C` and
112    /// misses a transaction committed at or before `C`, the stream never sees
113    /// it and the call ends in [`ExecuteAndWaitError::CheckpointTimeout`].
114    /// Sending `C` as the `x-sui-min-checkpoint` floor on these requests closes
115    /// that gap on servers that enforce it; this method does not send it yet.
116    #[allow(clippy::result_large_err)]
117    pub async fn execute_transaction_and_wait_for_checkpoint(
118        &mut self,
119        request: impl tonic::IntoRequest<ExecuteTransactionRequest>,
120        timeout: Duration,
121    ) -> Result<Response<ExecuteTransactionResponse>, ExecuteAndWaitError> {
122        // Calculate digest from the input transaction to avoid relying on response read mask
123        let request = request.into_request();
124        let transaction = request
125            .get_ref()
126            .transaction_opt()
127            .ok_or(ExecuteAndWaitError::MissingTransaction)?;
128        let transaction = sui_sdk_types::Transaction::try_from(transaction)
129            .map_err(ExecuteAndWaitError::ProtoConversionError)?;
130        let digest = transaction.digest().to_string();
131
132        // Lookup for answering from the ledger instead of from execution.
133        // Both RPCs' masks select fields of `ExecutedTransaction`, so the
134        // caller's mask passes through unchanged; when the caller didn't set
135        // one, mirror ExecuteTransaction's documented default. `digest`,
136        // `checkpoint`, and `timestamp` are always included since this
137        // method's contract populates them.
138        let lookup_request = {
139            let caller_paths = match &request.get_ref().read_mask {
140                Some(mask) => mask.paths.clone(),
141                None => vec!["effects.status".to_owned()],
142            };
143            let mask = FieldMask::from_paths(caller_paths.iter().map(String::as_str).chain([
144                "digest",
145                "checkpoint",
146                "timestamp",
147            ]))
148            .normalize();
149            GetTransactionRequest::default()
150                .with_digest(&digest)
151                .with_read_mask(mask)
152        };
153
154        // Read the height before the lookup. `GetTransaction` only finds
155        // transactions in checkpoints up to the node's latest checkpoint,
156        // which is the height `GetServiceInfo` reports and which only rises.
157        // So when the lookup finds nothing, the transaction is in no
158        // checkpoint at or below `start_checkpoint`, and a stream starting
159        // there sees it whenever it lands.
160        let start_checkpoint = self
161            .ledger_client()
162            .get_service_info(GetServiceInfoRequest::default())
163            .await
164            .map_err(ExecuteAndWaitError::RpcError)?
165            .into_inner()
166            .checkpoint_height
167            .ok_or_else(|| {
168                ExecuteAndWaitError::RpcError(tonic::Status::data_loss(
169                    "GetServiceInfo response is missing checkpoint_height",
170                ))
171            })?;
172
173        // A transaction submitted before (a retry, or the same transaction
174        // sent by someone else) can already be in a checkpoint the stream
175        // starts after.
176        match self
177            .ledger_client()
178            .get_transaction(lookup_request.clone())
179            .await
180        {
181            Ok(lookup) if lookup.get_ref().transaction().checkpoint_opt().is_some() => {
182                return Ok(lookup_into_execute_response(lookup));
183            }
184            Ok(_) => {}
185            Err(status) if status.code() == tonic::Code::NotFound => {}
186            Err(status) => return Err(ExecuteAndWaitError::RpcError(status)),
187        }
188
189        // The scan (which holds the stream) and the execution future are
190        // boxed: their combined state would otherwise be inlined into this
191        // method's future, making it large enough to threaten a stack overflow
192        // in callers that hold it in deeply nested or spawned futures.
193        let transactions = self.stream_transactions(
194            TransactionStreamRequest::new()
195                .with_read_mask(FieldMask::from_str(
196                    "digest,checkpoint,transaction_index,timestamp",
197                ))
198                .with_filter(TransactionFilter::matching(transaction::sender(
199                    transaction.sender,
200                )))
201                .with_start(TransactionStreamStart::Checkpoint(start_checkpoint)),
202        );
203        // The scan owns the stream, so the subscription closes as soon as the
204        // scan finishes, instead of staying open unread for the rest of the
205        // call and holding flow-control capacity on the shared connection.
206        let digest = &digest;
207        let mut find_checkpoint = Box::pin(async move {
208            let mut transactions = std::pin::pin!(transactions);
209            while let Some(frame) = transactions.try_next().await? {
210                if let Some(executed) = frame.transaction
211                    && executed.digest() == digest
212                {
213                    return Ok((executed.checkpoint(), executed.timestamp));
214                }
215            }
216            Err(tonic::Status::aborted(
217                "transaction stream ended unexpectedly",
218            ))
219        });
220
221        // Follow the stream while executing: the transaction can land in a
222        // checkpoint before the execution RPC returns, so remember the
223        // outcome; the guard keeps a completed future from being polled
224        // again.
225        let mut execution_client = self.execution_client();
226        let mut execution = Box::pin(execution_client.execute_transaction(request));
227        let mut found = None;
228        let execution_result = loop {
229            tokio::select! {
230                result = &mut execution => break result,
231                result = &mut find_checkpoint, if found.is_none() => found = Some(result),
232            }
233        };
234
235        let mut response = match execution_result {
236            Ok(response) => response,
237            Err(error) => {
238                // Execution can fail for a transaction that nonetheless
239                // committed, for example when a resubmission races the
240                // original submission. Consult the ledger before surfacing
241                // the error. The scan is never polled again, so close its
242                // stream before the lookup.
243                drop(find_checkpoint);
244                if let Ok(lookup) = self.ledger_client().get_transaction(lookup_request).await
245                    && lookup.get_ref().transaction().checkpoint_opt().is_some()
246                {
247                    return Ok(lookup_into_execute_response(lookup));
248                }
249                return Err(ExecuteAndWaitError::RpcError(error));
250            }
251        };
252
253        let found = match found {
254            Some(result) => result,
255            None => tokio::select! {
256                result = &mut find_checkpoint => result,
257                _ = tokio::time::sleep(timeout) => {
258                    return Err(ExecuteAndWaitError::CheckpointTimeout(response));
259                }
260            },
261        };
262        let (checkpoint, timestamp) = match found {
263            Ok(found) => found,
264            Err(error) => {
265                return Err(ExecuteAndWaitError::CheckpointStreamError { response, error });
266            }
267        };
268
269        response
270            .get_mut()
271            .transaction_mut()
272            .set_checkpoint(checkpoint);
273        response.get_mut().transaction_mut().timestamp = timestamp;
274        Ok(response)
275    }
276
277    /// Retrieves the current reference gas price from the latest epoch information.
278    ///
279    /// # Returns
280    /// The reference gas price as a `u64`
281    ///
282    /// # Errors
283    /// Returns an error if there is an RPC error when fetching the epoch information
284    pub async fn get_reference_gas_price(&mut self) -> Result<u64, tonic::Status> {
285        let request = GetEpochRequest::latest()
286            .with_read_mask(FieldMask::from_paths(["reference_gas_price"]));
287        let response = self.ledger_client().get_epoch(request).await?.into_inner();
288        Ok(response.epoch().reference_gas_price())
289    }
290}
291
292/// Builds the response for a transaction answered from the ledger instead of
293/// from execution.
294fn lookup_into_execute_response(
295    response: Response<GetTransactionResponse>,
296) -> Response<ExecuteTransactionResponse> {
297    Response::new(ExecuteTransactionResponse {
298        transaction: response.into_inner().transaction,
299    })
300}
301
302impl fmt::Display for ExecutionError {
303    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304        let description = self.description.as_deref().unwrap_or("No description");
305        write!(
306            f,
307            "ExecutionError: Kind: {}, Description: {}",
308            self.kind().as_str_name(),
309            description
310        )
311    }
312}