Skip to main content

iota_indexer/apis/
write_api.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::sync::Arc;
6
7use async_trait::async_trait;
8use fastcrypto::encoding::Base64;
9use futures::TryFutureExt;
10use iota_grpc_client::{GrpcClient, read_mask_fields::SimulateField};
11use iota_json::IotaJsonValue;
12use iota_json_rpc::IotaRpcModule;
13use iota_json_rpc_api::WriteApiServer;
14use iota_json_rpc_types::{
15    BalanceChange, DevInspectArgs, DevInspectResults, DryRunTransactionBlockResponse,
16    ExecuteTransactionRequestType, IotaExecutionResult, IotaMoveViewCallResults,
17    IotaTransactionBlock, IotaTransactionBlockEffects, IotaTransactionBlockResponse,
18    IotaTransactionBlockResponseOptions, IotaTypeTag, MoveFunctionName, ObjectChange,
19};
20use iota_open_rpc::Module;
21use iota_package_resolver::{Limits, PackageStore, Resolver};
22use iota_sdk_types::{
23    Address, GasPayment, SenderSignedTransaction, Transaction, TransactionEffects,
24    TransactionEvents, TransactionExpiration, TransactionKind, TransactionV1, UserSignature,
25};
26use iota_transaction_builder::TransactionBuilder;
27use iota_types::{
28    effects::TransactionEffectsAPI, error::ExecutionError, iota_serde::BigInt, object::Object,
29};
30use jsonrpsee::{RpcModule, core::RpcResult};
31
32use crate::{
33    errors::{IndexerError, IndexerResult},
34    models::transactions::{StoredTransaction, tx_events_to_iota_tx_events},
35    optimistic_indexing::{IngestionPath, OptimisticTransactionExecutor},
36    read::IndexerReader,
37    store::package_resolver::{IndexerStorePackageResolver, SimulationPackageStore},
38    types::grpc_conversion,
39};
40
41// The fields every simulation reads back, whatever the caller. Anything beyond
42// this is requested through `SimulationFields`; `simulate_transaction` builds
43// the full read mask from both.
44const SIMULATE_CORE_READ_MASK: &[SimulateField] = &[
45    SimulateField::EXECUTED_TRANSACTION_EFFECTS_BCS,
46    SimulateField::EXECUTED_TRANSACTION_EVENTS_EVENTS_BCS,
47    // Needed to resolve types against a package the simulated transaction published.
48    SimulateField::EXECUTED_TRANSACTION_OUTPUT_OBJECTS_BCS,
49    SimulateField::EXECUTION_RESULT_EXECUTION_ERROR_SOURCE,
50];
51
52/// The fields to read back from a simulation beyond the core ones (which are
53/// always returned). Each flag adds the fields it needs to the read mask and
54/// populates the matching field on [`SimulationOutput`]; a flag left `false`
55/// leaves that field empty.
56#[derive(Default)]
57pub struct SimulationFields {
58    /// The transaction the simulation ran, with any gas the caller left unset
59    /// filled in by the node.
60    pub transaction: bool,
61    /// The balance changes the transaction caused.
62    pub balance_changes: bool,
63    /// The gas price the node suggests for the transaction.
64    pub suggested_gas_price: bool,
65    /// The simulated transaction's signatures.
66    pub signatures: bool,
67    /// The node's object changes
68    pub object_changes: bool,
69    /// The simulation's input objects
70    pub input_objects: bool,
71    /// The per-command results (mutated references and return values).
72    pub command_results: bool,
73    /// The full execution error (its kind, command index and source); the
74    /// source alone is a core field and always returned.
75    pub execution_error: bool,
76}
77
78/// The result of a simulation, in the node's native types. The core fields are
79/// always present; the rest are populated only when the matching
80/// [`SimulationFields`] flag was set.
81pub struct SimulationOutput {
82    pub transaction: Option<Transaction>,
83    pub effects: TransactionEffects,
84    pub events: TransactionEvents,
85    pub output_objects: Vec<Object>,
86    pub balance_changes: Vec<BalanceChange>,
87    pub suggested_gas_price: Option<u64>,
88    pub execution_error_source: Option<String>,
89    pub signatures: Vec<UserSignature>,
90    pub object_changes: Vec<ObjectChange>,
91    pub input_objects: Vec<Object>,
92    pub command_results: Option<Vec<IotaExecutionResult>>,
93    pub execution_error: Option<String>,
94}
95
96#[derive(Clone)]
97pub struct WriteApi {
98    fullnode_grpc_client: GrpcClient,
99    transaction_builder: TransactionBuilder,
100    package_resolver: Arc<Resolver<IndexerStorePackageResolver>>,
101}
102
103#[derive(Clone)]
104pub struct OptimisticWriteApi {
105    write_api: WriteApi,
106    optimistic_tx_executor: OptimisticTransactionExecutor,
107}
108
109impl WriteApi {
110    pub fn new(fullnode_grpc_client: GrpcClient, reader: IndexerReader) -> Self {
111        let package_resolver = IndexerStorePackageResolver::new(reader.get_pool());
112        Self {
113            fullnode_grpc_client,
114            transaction_builder: TransactionBuilder::new(Arc::new(reader)),
115            package_resolver: Arc::new(Resolver::new_with_limits(
116                package_resolver,
117                Limits::default(),
118            )),
119        }
120    }
121
122    /// Run a simulation and return its result in the node's native types. The
123    /// read mask is built here from the core fields plus whatever `fields` asks
124    /// for, so callers never deal with it directly. Every dry run and dev
125    /// inspect goes through this, so the simulation and its conversions live in
126    /// one place.
127    pub async fn simulate_transaction(
128        &self,
129        tx: Transaction,
130        skip_checks: bool,
131        fields: SimulationFields,
132    ) -> IndexerResult<SimulationOutput> {
133        let mut read_mask = SIMULATE_CORE_READ_MASK.to_vec();
134        if fields.transaction {
135            read_mask.push(SimulateField::EXECUTED_TRANSACTION_TRANSACTION_BCS);
136        }
137        if fields.balance_changes {
138            read_mask.push(SimulateField::EXECUTED_TRANSACTION_BALANCE_CHANGES);
139        }
140        if fields.suggested_gas_price {
141            read_mask.push(SimulateField::SUGGESTED_GAS_PRICE);
142        }
143        if fields.signatures {
144            read_mask.push(SimulateField::EXECUTED_TRANSACTION_SIGNATURES_BCS);
145        }
146        if fields.object_changes {
147            read_mask.push(SimulateField::EXECUTED_TRANSACTION_OBJECT_CHANGES);
148        }
149        if fields.input_objects {
150            read_mask.push(SimulateField::EXECUTED_TRANSACTION_INPUT_OBJECTS_BCS);
151        }
152        if fields.command_results {
153            read_mask.push(SimulateField::EXECUTION_RESULT_COMMAND_RESULTS_MUTATED_BY_REF);
154            read_mask.push(SimulateField::EXECUTION_RESULT_COMMAND_RESULTS_RETURN_VALUES);
155        }
156        if fields.execution_error {
157            read_mask.push(SimulateField::EXECUTION_RESULT_EXECUTION_ERROR_BCS_KIND);
158            read_mask.push(SimulateField::EXECUTION_RESULT_EXECUTION_ERROR_COMMAND_INDEX);
159        }
160
161        let response = self
162            .fullnode_grpc_client
163            .simulate_transaction(tx)
164            .skip_checks(skip_checks)
165            .read_mask(read_mask)
166            .await?
167            .into_inner();
168        let executed_transaction = response.executed_transaction()?;
169
170        let signatures = if fields.signatures {
171            executed_transaction
172                .signatures()?
173                .signatures
174                .iter()
175                .map(|s| -> IndexerResult<_> { Ok(s.signature()?) })
176                .collect::<IndexerResult<Vec<UserSignature>>>()?
177        } else {
178            vec![]
179        };
180        let object_changes = if fields.object_changes {
181            grpc_conversion::object_changes(executed_transaction.object_changes()?)?
182        } else {
183            vec![]
184        };
185        let input_objects = if fields.input_objects {
186            grpc_conversion::objects(executed_transaction.input_objects()?)?
187        } else {
188            vec![]
189        };
190        let command_results = if fields.command_results {
191            response
192                .command_results()
193                .map(|command_results| grpc_conversion::command_results(command_results.clone()))
194                .transpose()?
195        } else {
196            None
197        };
198        let execution_error = if fields.execution_error {
199            response
200                .execution_error()
201                .map(|execution_error| -> IndexerResult<_> {
202                    let exec_err = execution_error.error_kind()?;
203                    let source = execution_error
204                        .source
205                        .clone()
206                        .map(|s| -> Box<dyn std::error::Error + Send + Sync> { s.into() });
207
208                    let mut error = ExecutionError::new(exec_err, source);
209                    if let Some(command_index) = execution_error.command_index {
210                        error = error.with_command_index(command_index);
211                    }
212                    Ok(error.to_string())
213                })
214                .transpose()?
215        } else {
216            None
217        };
218
219        let transaction = if fields.transaction {
220            // Report the transaction the simulation ran, not the one that was sent: the
221            // node fills in the gas the caller left unset and reports the values it
222            // used, which is how a caller reads back an estimate.
223            Some(executed_transaction.transaction()?.transaction()?)
224        } else {
225            None
226        };
227        let balance_changes = if fields.balance_changes {
228            grpc_conversion::balance_changes(executed_transaction.balance_changes()?)?
229        } else {
230            vec![]
231        };
232        let suggested_gas_price = if fields.suggested_gas_price {
233            response.suggested_gas_price
234        } else {
235            None
236        };
237
238        Ok(SimulationOutput {
239            transaction,
240            effects: executed_transaction.effects()?.effects()?,
241            events: executed_transaction.events()?.events()?,
242            output_objects: grpc_conversion::objects(executed_transaction.output_objects()?)?,
243            balance_changes,
244            suggested_gas_price,
245            execution_error_source: response.execution_error().and_then(|e| e.source.clone()),
246            signatures,
247            object_changes,
248            input_objects,
249            command_results,
250            execution_error,
251        })
252    }
253
254    async fn dry_run_transaction_block_impl(
255        &self,
256        tx_bytes: Base64,
257        package_resolver: &Arc<Resolver<impl PackageStore>>,
258    ) -> IndexerResult<DryRunTransactionBlockResponse> {
259        let tx = bcs::from_bytes::<Transaction>(&tx_bytes.to_vec()?)?;
260        let sim = self
261            .simulate_transaction(
262                tx,
263                false,
264                SimulationFields {
265                    transaction: true,
266                    balance_changes: true,
267                    suggested_gas_price: true,
268                    signatures: true,
269                    object_changes: true,
270                    ..Default::default()
271                },
272            )
273            .await?;
274
275        // The digest of what actually ran, which is the one the effects and the events
276        // are keyed by. It differs from the digest of the transaction as sent whenever
277        // the simulation filled gas in — a mock gas coin changes the transaction it is
278        // taken over.
279        let tx_digest = *sim.effects.transaction_digest();
280        let transaction = sim
281            .transaction
282            .expect("dry run always requests the transaction");
283        let sender_signed_tx = SenderSignedTransaction::new(transaction, sim.signatures);
284
285        // Resolve types against the packages the simulation published before falling
286        // back to the database, so that a transaction publishing a package can decode
287        // the types it introduces — an event from its `init`, for one.
288        let package_resolver = Arc::new(Resolver::new_with_limits(
289            SimulationPackageStore::new(&sim.output_objects, package_resolver.clone()),
290            Limits::default(),
291        ));
292
293        let fut1 = IotaTransactionBlock::try_from_with_package_resolver(
294            sender_signed_tx,
295            &package_resolver,
296            tx_digest,
297        )
298        .map_err(Into::into);
299
300        // timestamp is None because it represent a checkpoint one, on a dry run
301        // operation we don't have this information.
302        let fut2 = tx_events_to_iota_tx_events(sim.events, &package_resolver, tx_digest, None);
303
304        let fut3 = IotaTransactionBlockEffects::from_native_with_clever_error(
305            sim.effects,
306            &package_resolver,
307        )
308        .map_err(IndexerError::from);
309
310        let (transaction_block, events, effects) =
311            futures::future::try_join3(fut1, fut2, fut3).await?;
312
313        Ok(DryRunTransactionBlockResponse {
314            effects,
315            events,
316            object_changes: sim.object_changes,
317            balance_changes: sim.balance_changes,
318            input: transaction_block.data,
319            suggested_gas_price: sim.suggested_gas_price,
320            execution_error_source: sim.execution_error_source,
321        })
322    }
323
324    async fn dev_inspect_transaction_block_impl(
325        &self,
326        sender_address: Address,
327        tx_bytes: Base64,
328        gas_price: Option<BigInt<u64>>,
329        additional_args: Option<DevInspectArgs>,
330        package_resolver: &Arc<Resolver<impl PackageStore>>,
331    ) -> IndexerResult<DevInspectResults> {
332        let DevInspectArgs {
333            gas_sponsor,
334            gas_budget,
335            gas_objects,
336            show_raw_txn_data_and_effects,
337            skip_checks,
338        } = additional_args.unwrap_or_default();
339
340        let show_raw_txn_data_and_effects = show_raw_txn_data_and_effects.unwrap_or(false);
341        let skip_checks = skip_checks.unwrap_or(true);
342
343        let kind = bcs::from_bytes::<TransactionKind>(&tx_bytes.to_vec()?)?;
344
345        let tx = Transaction::V1(TransactionV1 {
346            kind,
347            sender: sender_address,
348            gas_payment: GasPayment {
349                // Any of these the caller leaves out is filled in by the simulation on
350                // the node: an empty payment gets a mock gas coin, a zero price gets the
351                // epoch's reference gas price, and a zero budget gets the protocol
352                // maximum.
353                objects: gas_objects.unwrap_or_default(),
354                owner: gas_sponsor.unwrap_or(sender_address),
355                price: gas_price.map(BigInt::into_inner).unwrap_or_default(),
356                budget: gas_budget.unwrap_or_default(),
357            },
358            expiration: TransactionExpiration::None,
359        });
360
361        let simulation = self
362            .simulate_transaction(
363                tx,
364                skip_checks,
365                SimulationFields {
366                    transaction: show_raw_txn_data_and_effects,
367                    command_results: true,
368                    execution_error: true,
369                    ..Default::default()
370                },
371            )
372            .await?;
373
374        let tx_digest = *simulation.effects.transaction_digest();
375
376        // Report the transaction the simulation ran, not the one that was sent: the
377        // node fills in the gas the caller left unset.
378        let raw_txn_data = simulation
379            .transaction
380            .as_ref()
381            .map(bcs::to_bytes)
382            .transpose()?
383            .unwrap_or_default();
384        let raw_effects = show_raw_txn_data_and_effects
385            .then(|| bcs::to_bytes(&simulation.effects))
386            .transpose()?
387            .unwrap_or_default();
388
389        // Resolve types against the packages the simulation published before falling
390        // back to the database, so that a transaction publishing a package can decode
391        // the types it introduces — an event from its `init`, for one.
392        let package_resolver = Arc::new(Resolver::new_with_limits(
393            SimulationPackageStore::new(&simulation.output_objects, package_resolver.clone()),
394            Limits::default(),
395        ));
396        // timestamp is None because it represent a checkpoint one, on a dev inspect
397        // operation we don't have this information.
398        let events =
399            tx_events_to_iota_tx_events(simulation.events, &package_resolver, tx_digest, None)
400                .await?;
401
402        Ok(DevInspectResults {
403            effects: simulation.effects.try_into()?,
404            events,
405            results: simulation.command_results,
406            error: simulation.execution_error,
407            raw_txn_data,
408            raw_effects,
409        })
410    }
411}
412
413impl OptimisticWriteApi {
414    pub fn new(write_api: WriteApi, optimistic_tx_executor: OptimisticTransactionExecutor) -> Self {
415        Self {
416            write_api,
417            optimistic_tx_executor,
418        }
419    }
420
421    async fn build_response(
422        &self,
423        ingestion_path: IngestionPath,
424        options: IotaTransactionBlockResponseOptions,
425    ) -> Result<IotaTransactionBlockResponse, IndexerError> {
426        let package_resolver = self.write_api.package_resolver.clone();
427        let stored_transaction = StoredTransaction::from(ingestion_path);
428        stored_transaction
429            .try_into_iota_transaction_block_response(options, &package_resolver)
430            .await
431    }
432
433    pub fn executor(&self) -> &OptimisticTransactionExecutor {
434        &self.optimistic_tx_executor
435    }
436
437    pub async fn simulate_transaction(
438        &self,
439        tx: Transaction,
440        skip_checks: bool,
441        fields: SimulationFields,
442    ) -> IndexerResult<SimulationOutput> {
443        self.write_api
444            .simulate_transaction(tx, skip_checks, fields)
445            .await
446    }
447}
448
449#[async_trait]
450impl WriteApiServer for WriteApi {
451    /// This method will always return an error. The user shall use the
452    /// [`OptimisticWriteApi`] to execute transactions.
453    async fn execute_transaction_block(
454        &self,
455        _tx_bytes: Base64,
456        _signatures: Vec<Base64>,
457        _options: Option<IotaTransactionBlockResponseOptions>,
458        _request_type: Option<ExecuteTransactionRequestType>,
459    ) -> RpcResult<IotaTransactionBlockResponse> {
460        Err(IndexerError::Generic(
461            "execute_transaction_block should be called from OptimisticWriteApi".into(),
462        )
463        .into())
464    }
465
466    async fn dev_inspect_transaction_block(
467        &self,
468        sender_address: Address,
469        tx_bytes: Base64,
470        gas_price: Option<BigInt<u64>>,
471        _epoch: Option<BigInt<u64>>,
472        additional_args: Option<DevInspectArgs>,
473    ) -> RpcResult<DevInspectResults> {
474        self.dev_inspect_transaction_block_impl(
475            sender_address,
476            tx_bytes,
477            gas_price,
478            additional_args,
479            &self.package_resolver,
480        )
481        .await
482        .map_err(Into::into)
483    }
484
485    async fn dry_run_transaction_block(
486        &self,
487        tx_bytes: Base64,
488    ) -> RpcResult<DryRunTransactionBlockResponse> {
489        self.dry_run_transaction_block_impl(tx_bytes, &self.package_resolver)
490            .await
491            .map_err(Into::into)
492    }
493
494    async fn view_function_call(
495        &self,
496        function_name: String,
497        type_args: Option<Vec<IotaTypeTag>>,
498        arguments: Vec<IotaJsonValue>,
499    ) -> RpcResult<IotaMoveViewCallResults> {
500        let MoveFunctionName {
501            package,
502            module,
503            function,
504        } = function_name.as_str().parse().map_err(IndexerError::from)?;
505        let sender = Address::ZERO;
506        let tx_kind = self
507            .transaction_builder
508            .move_view_call_tx_kind(
509                package,
510                &module,
511                &function,
512                type_args.unwrap_or_default(),
513                arguments,
514            )
515            .await
516            .map_err(IndexerError::from)?;
517        let tx_bytes = Base64::from_bytes(&tx_kind.to_bcs());
518        let dev_inspect_results = self
519            .dev_inspect_transaction_block(sender, tx_bytes, None, None, None)
520            .await?;
521        Ok(IotaMoveViewCallResults::from_dev_inspect_results(
522            self.package_resolver.package_store().clone(),
523            dev_inspect_results,
524        )
525        .await
526        .map_err(IndexerError::from)?)
527    }
528}
529
530#[async_trait]
531impl WriteApiServer for OptimisticWriteApi {
532    async fn execute_transaction_block(
533        &self,
534        tx_bytes: Base64,
535        signatures: Vec<Base64>,
536        options: Option<IotaTransactionBlockResponseOptions>,
537        _request_type: Option<ExecuteTransactionRequestType>,
538    ) -> RpcResult<IotaTransactionBlockResponse> {
539        let ingestion_path = self
540            .optimistic_tx_executor
541            .execute_and_index_transaction(tx_bytes, signatures)
542            .await?;
543        Ok(self
544            .build_response(ingestion_path, options.unwrap_or_default())
545            .await?)
546    }
547
548    async fn dev_inspect_transaction_block(
549        &self,
550        sender_address: Address,
551        tx_bytes: Base64,
552        gas_price: Option<BigInt<u64>>,
553        epoch: Option<BigInt<u64>>,
554        additional_args: Option<DevInspectArgs>,
555    ) -> RpcResult<DevInspectResults> {
556        self.write_api
557            .dev_inspect_transaction_block(
558                sender_address,
559                tx_bytes,
560                gas_price,
561                epoch,
562                additional_args,
563            )
564            .await
565    }
566
567    async fn dry_run_transaction_block(
568        &self,
569        tx_bytes: Base64,
570    ) -> RpcResult<DryRunTransactionBlockResponse> {
571        self.write_api.dry_run_transaction_block(tx_bytes).await
572    }
573
574    async fn view_function_call(
575        &self,
576        function_name: String,
577        type_args: Option<Vec<IotaTypeTag>>,
578        arguments: Vec<IotaJsonValue>,
579    ) -> RpcResult<IotaMoveViewCallResults> {
580        self.write_api
581            .view_function_call(function_name, type_args, arguments)
582            .await
583    }
584}
585
586impl IotaRpcModule for WriteApi {
587    fn rpc(self) -> RpcModule<Self> {
588        self.into_rpc()
589    }
590
591    fn rpc_doc_module() -> Module {
592        iota_json_rpc_api::WriteApiOpenRpc::module_doc()
593    }
594}
595
596impl IotaRpcModule for OptimisticWriteApi {
597    fn rpc(self) -> RpcModule<Self> {
598        self.into_rpc()
599    }
600
601    fn rpc_doc_module() -> Module {
602        iota_json_rpc_api::WriteApiOpenRpc::module_doc()
603    }
604}