1use 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
41const SIMULATE_CORE_READ_MASK: &[SimulateField] = &[
45 SimulateField::EXECUTED_TRANSACTION_EFFECTS_BCS,
46 SimulateField::EXECUTED_TRANSACTION_EVENTS_EVENTS_BCS,
47 SimulateField::EXECUTED_TRANSACTION_OUTPUT_OBJECTS_BCS,
49 SimulateField::EXECUTION_RESULT_EXECUTION_ERROR_SOURCE,
50];
51
52#[derive(Default)]
57pub struct SimulationFields {
58 pub transaction: bool,
61 pub balance_changes: bool,
63 pub suggested_gas_price: bool,
65 pub signatures: bool,
67 pub object_changes: bool,
69 pub input_objects: bool,
71 pub command_results: bool,
73 pub execution_error: bool,
76}
77
78pub 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 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 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 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 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 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 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 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 let package_resolver = Arc::new(Resolver::new_with_limits(
393 SimulationPackageStore::new(&simulation.output_objects, package_resolver.clone()),
394 Limits::default(),
395 ));
396 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 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}