linera_sdk/test/
chain.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A reference to a single microchain inside a [`TestValidator`].
5//!
6//! This allows manipulating a test microchain.
7
8use std::{
9    collections::HashMap,
10    io,
11    path::{Path, PathBuf},
12    sync::Arc,
13};
14
15use cargo_toml::Manifest;
16use futures::future;
17use linera_base::{
18    crypto::{AccountPublicKey, AccountSecretKey},
19    data_types::{
20        Amount, ApplicationDescription, Blob, BlockHeight, Bytecode, ChainDescription,
21        CompressedBytecode, Epoch,
22    },
23    identifiers::{AccountOwner, ApplicationId, ChainId, ModuleId, OwnerSpender},
24    vm::VmRuntime,
25};
26use linera_chain::{types::ConfirmedBlockCertificate, ChainExecutionContext};
27use linera_core::{data_types::ChainInfoQuery, worker::WorkerError};
28use linera_execution::{
29    system::{SystemOperation, SystemQuery, SystemResponse},
30    ExecutionError, Operation, Query, QueryOutcome, QueryResponse, ResourceTracker,
31};
32use linera_storage::Storage as _;
33use serde::Serialize;
34use tokio::{fs, sync::Mutex};
35
36use super::{BlockBuilder, TestValidator};
37use crate::{abis::fungible::FungibleTokenAbi, ContractAbi, ServiceAbi};
38
39/// A reference to a single microchain inside a [`TestValidator`].
40pub struct ActiveChain {
41    key_pair: AccountSecretKey,
42    description: ChainDescription,
43    tip: Arc<Mutex<Option<ConfirmedBlockCertificate>>>,
44    validator: TestValidator,
45}
46
47impl Clone for ActiveChain {
48    fn clone(&self) -> Self {
49        ActiveChain {
50            key_pair: self.key_pair.copy(),
51            description: self.description.clone(),
52            tip: self.tip.clone(),
53            validator: self.validator.clone(),
54        }
55    }
56}
57
58impl ActiveChain {
59    /// Creates a new [`ActiveChain`] instance referencing a new empty microchain in the
60    /// `validator`.
61    ///
62    /// The microchain has a single owner that uses the `key_pair` to produce blocks. The
63    /// `description` is used as the identifier of the microchain.
64    pub fn new(
65        key_pair: AccountSecretKey,
66        description: ChainDescription,
67        validator: TestValidator,
68    ) -> Self {
69        ActiveChain {
70            key_pair,
71            description,
72            tip: Arc::default(),
73            validator,
74        }
75    }
76
77    /// Returns the [`ChainId`] of this microchain.
78    pub fn id(&self) -> ChainId {
79        self.description.id()
80    }
81
82    /// Returns the [`AccountPublicKey`] of the active owner of this microchain.
83    pub fn public_key(&self) -> AccountPublicKey {
84        self.key_pair.public()
85    }
86
87    /// Returns the [`AccountSecretKey`] of the active owner of this microchain.
88    pub fn key_pair(&self) -> &AccountSecretKey {
89        &self.key_pair
90    }
91
92    /// Sets the [`AccountSecretKey`] to use for signing new blocks.
93    pub fn set_key_pair(&mut self, key_pair: AccountSecretKey) {
94        self.key_pair = key_pair
95    }
96
97    /// Returns the current [`Epoch`] the chain is in.
98    pub async fn epoch(&self) -> Epoch {
99        *Box::pin(self.validator.worker().chain_state_view(self.id()))
100            .await
101            .expect("Failed to load chain")
102            .execution_state
103            .system
104            .epoch
105            .get()
106    }
107
108    /// Reads the current shared balance available to all of the owners of this microchain.
109    pub async fn chain_balance(&self) -> Amount {
110        let query = Query::System(SystemQuery);
111
112        let (QueryOutcome { response, .. }, _) = self
113            .validator
114            .worker()
115            .query_application(self.id(), query, None)
116            .await
117            .expect("Failed to query chain's balance");
118
119        let QueryResponse::System(SystemResponse { balance, .. }) = response else {
120            panic!("Unexpected response from system application");
121        };
122
123        balance
124    }
125
126    /// Reads the current account balance on this microchain of an [`AccountOwner`].
127    pub async fn owner_balance(&self, owner: &AccountOwner) -> Option<Amount> {
128        let chain_state = Box::pin(self.validator.worker().chain_state_view(self.id()))
129            .await
130            .expect("Failed to read chain state");
131
132        chain_state
133            .execution_state
134            .system
135            .balances
136            .get(owner)
137            .await
138            .expect("Failed to read owner balance")
139    }
140
141    /// Reads the current account balance on this microchain of all [`AccountOwner`]s.
142    pub async fn owner_balances(
143        &self,
144        owners: impl IntoIterator<Item = AccountOwner>,
145    ) -> HashMap<AccountOwner, Option<Amount>> {
146        let chain_state = Box::pin(self.validator.worker().chain_state_view(self.id()))
147            .await
148            .expect("Failed to read chain state");
149
150        let mut balances = HashMap::new();
151
152        for owner in owners {
153            let balance = chain_state
154                .execution_state
155                .system
156                .balances
157                .get(&owner)
158                .await
159                .expect("Failed to read an owner's balance");
160
161            balances.insert(owner, balance);
162        }
163
164        balances
165    }
166
167    /// Reads a list of [`AccountOwner`]s that have a non-zero balance on this microchain.
168    pub async fn accounts(&self) -> Vec<AccountOwner> {
169        let chain_state = Box::pin(self.validator.worker().chain_state_view(self.id()))
170            .await
171            .expect("Failed to read chain state");
172
173        chain_state
174            .execution_state
175            .system
176            .balances
177            .indices()
178            .await
179            .expect("Failed to list accounts on the chain")
180    }
181
182    /// Reads all the non-zero account balances on this microchain.
183    pub async fn all_owner_balances(&self) -> HashMap<AccountOwner, Amount> {
184        self.owner_balances(self.accounts().await)
185            .await
186            .into_iter()
187            .map(|(owner, balance)| {
188                (
189                    owner,
190                    balance.expect("`accounts` should only return accounts with non-zero balance"),
191                )
192            })
193            .collect()
194    }
195
196    /// Adds a block to this microchain.
197    ///
198    /// The `block_builder` parameter is a closure that should use the [`BlockBuilder`] parameter
199    /// to provide the block's contents.
200    ///
201    /// Returns the block certificate and a [`ResourceTracker`] containing execution costs.
202    pub async fn add_block(
203        &self,
204        block_builder: impl FnOnce(&mut BlockBuilder),
205    ) -> (ConfirmedBlockCertificate, ResourceTracker) {
206        self.try_add_block(block_builder)
207            .await
208            .expect("Failed to execute block.")
209    }
210
211    /// Adds a block to this microchain, passing the blobs to be used during certificate handling.
212    ///
213    /// The `block_builder` parameter is a closure that should use the [`BlockBuilder`] parameter
214    /// to provide the block's contents.
215    ///
216    /// Returns the block certificate and a [`ResourceTracker`] containing execution costs.
217    pub async fn add_block_with_blobs(
218        &self,
219        block_builder: impl FnOnce(&mut BlockBuilder),
220        blobs: Vec<Blob>,
221    ) -> (ConfirmedBlockCertificate, ResourceTracker) {
222        self.try_add_block_with_blobs(block_builder, blobs)
223            .await
224            .expect("Failed to execute block.")
225    }
226
227    /// Tries to add a block to this microchain.
228    ///
229    /// The `block_builder` parameter is a closure that should use the [`BlockBuilder`] parameter
230    /// to provide the block's contents.
231    ///
232    /// Returns the block certificate and a [`ResourceTracker`] containing execution costs.
233    pub async fn try_add_block(
234        &self,
235        block_builder: impl FnOnce(&mut BlockBuilder),
236    ) -> Result<(ConfirmedBlockCertificate, ResourceTracker), WorkerError> {
237        self.try_add_block_with_blobs(block_builder, vec![]).await
238    }
239
240    /// Tries to add a block to this microchain, writing some `blobs` to storage if needed.
241    ///
242    /// The `block_builder` parameter is a closure that should use the [`BlockBuilder`] parameter
243    /// to provide the block's contents.
244    ///
245    /// The blobs are either all written to storage, if executing the block fails due to a missing
246    /// blob, or none are written to storage if executing the block succeeds without the blobs.
247    ///
248    /// Returns the block certificate and a [`ResourceTracker`] containing execution costs.
249    async fn try_add_block_with_blobs(
250        &self,
251        block_builder: impl FnOnce(&mut BlockBuilder),
252        blobs: Vec<Blob>,
253    ) -> Result<(ConfirmedBlockCertificate, ResourceTracker), WorkerError> {
254        let mut tip = self.tip.lock().await;
255        let mut block = BlockBuilder::new(
256            self.description.id(),
257            self.key_pair.public().into(),
258            Box::pin(self.epoch()).await,
259            tip.as_ref(),
260            self.validator.clone(),
261        );
262
263        block_builder(&mut block);
264
265        // TODO(#2066): Remove boxing once call-stack is shallower
266        let (certificate, resource_tracker) = Box::pin(block.try_sign(&blobs)).await?;
267
268        let result = self
269            .validator
270            .worker()
271            .fully_handle_certificate_with_notifications(certificate.clone(), &())
272            .await;
273        if let Err(WorkerError::BlobsNotFound(_)) = &result {
274            self.validator.storage().maybe_write_blobs(&blobs).await?;
275            self.validator
276                .worker()
277                .fully_handle_certificate_with_notifications(certificate.clone(), &())
278                .await
279                .expect("Rejected certificate");
280        } else {
281            result.expect("Rejected certificate");
282        }
283
284        *tip = Some(certificate.clone());
285
286        Ok((certificate, resource_tracker))
287    }
288
289    /// Receives all queued messages in all inboxes of this microchain.
290    ///
291    /// Adds a block to this microchain that receives all queued messages in the microchains
292    /// inboxes.
293    ///
294    /// Returns the certificate and resource tracker of the latest block added to the chain, if
295    /// any.
296    pub async fn handle_received_messages(
297        &self,
298    ) -> Option<(ConfirmedBlockCertificate, ResourceTracker)> {
299        let chain_id = self.id();
300        let (information, _) = self
301            .validator
302            .worker()
303            .handle_chain_info_query(ChainInfoQuery::new(chain_id).with_pending_message_bundles())
304            .await
305            .expect("Failed to query chain's pending messages");
306        let messages = information.info.requested_pending_message_bundles;
307        // Empty blocks are not allowed.
308        // Return early if there are no messages to process and we'd end up with an empty proposal.
309        if messages.is_empty() {
310            return None;
311        }
312        let result = Box::pin(self.add_block(|block| {
313            block.with_incoming_bundles(messages);
314        }))
315        .await;
316        Some(result)
317    }
318
319    /// Processes all new events from streams this chain subscribes to.
320    ///
321    /// Adds a block to this microchain that processes the new events.
322    ///
323    /// Returns the certificate and resource tracker of the block added to the chain.
324    pub async fn handle_new_events(&self) -> (ConfirmedBlockCertificate, ResourceTracker) {
325        let chain_id = self.id();
326        let worker = self.validator.worker();
327        let subscription_map = Box::pin(worker.chain_state_view(chain_id))
328            .await
329            .expect("Failed to query chain state view")
330            .execution_state
331            .system
332            .event_subscriptions
333            .index_values()
334            .await
335            .expect("Failed to query chain's event subscriptions");
336        // Collect the indices of all new events.
337        let futures = subscription_map
338            .into_iter()
339            .map(|((chain_id, stream_id), subscriptions)| {
340                let worker = worker.clone();
341                async move {
342                    Box::pin(worker.chain_state_view(chain_id))
343                        .await
344                        .expect("Failed to query chain state view")
345                        .execution_state
346                        .system
347                        .stream_event_counts
348                        .get(&stream_id)
349                        .await
350                        .expect("Failed to query chain's event counts")
351                        .filter(|next_index| *next_index > subscriptions.next_index)
352                        .map(|next_index| (chain_id, stream_id, next_index))
353                }
354            });
355        let updates = future::join_all(futures)
356            .await
357            .into_iter()
358            .flatten()
359            .collect::<Vec<_>>();
360        assert!(!updates.is_empty(), "No new events to process");
361
362        Box::pin(self.add_block(|block| {
363            block.with_system_operation(SystemOperation::UpdateStreams(updates));
364        }))
365        .await
366    }
367
368    /// Publishes the module in the crate calling this method to this microchain.
369    ///
370    /// Searches the Cargo manifest for binaries that end with `contract` and `service`, builds
371    /// them for WebAssembly and uses the generated binaries as the contract and service bytecode files
372    /// to be published on this chain. Returns the module ID to reference the published module.
373    pub async fn publish_current_module<Abi, Parameters, InstantiationArgument>(
374        &self,
375    ) -> ModuleId<Abi, Parameters, InstantiationArgument> {
376        Box::pin(self.publish_bytecode_files_in(".")).await
377    }
378
379    /// Publishes the bytecode files in the crate at `repository_path`.
380    ///
381    /// Searches the Cargo manifest for binaries that end with `contract` and `service`, builds
382    /// them for WebAssembly and uses the generated binaries as the contract and service bytecode files
383    /// to be published on this chain. Returns the module ID to reference the published module.
384    pub async fn publish_bytecode_files_in<Abi, Parameters, InstantiationArgument>(
385        &self,
386        repository_path: impl AsRef<Path>,
387    ) -> ModuleId<Abi, Parameters, InstantiationArgument> {
388        let repository_path = fs::canonicalize(repository_path)
389            .await
390            .expect("Failed to obtain absolute application repository path");
391        Self::build_bytecode_files_in(&repository_path);
392        let (contract, service) = Self::find_compressed_bytecode_files_in(&repository_path).await;
393        let contract_blob = Blob::new_contract_bytecode(contract);
394        let service_blob = Blob::new_service_bytecode(service);
395        let contract_blob_hash = contract_blob.id().hash;
396        let service_blob_hash = service_blob.id().hash;
397        let vm_runtime = VmRuntime::Wasm;
398
399        let module_id = ModuleId::new(contract_blob_hash, service_blob_hash, vm_runtime);
400
401        let (certificate, _) = Box::pin(self.add_block_with_blobs(
402            |block| {
403                block.with_system_operation(SystemOperation::PublishModule { module_id });
404            },
405            vec![contract_blob, service_blob],
406        ))
407        .await;
408
409        let block = certificate.inner().block();
410        assert_eq!(block.messages().len(), 1);
411        assert_eq!(block.messages()[0].len(), 0);
412
413        module_id.with_abi()
414    }
415
416    /// Compiles the crate in the `repository` path.
417    pub fn build_bytecode_files_in(repository: &Path) {
418        let output = std::process::Command::new("cargo")
419            .args(["build", "--release", "--target", "wasm32-unknown-unknown"])
420            .current_dir(repository)
421            .output()
422            .expect("Failed to build Wasm binaries");
423
424        assert!(
425            output.status.success(),
426            "Failed to build bytecode binaries.\nstdout: {}\nstderr: {}",
427            String::from_utf8_lossy(&output.stdout),
428            String::from_utf8_lossy(&output.stderr)
429        );
430    }
431
432    /// Searches the Cargo manifest of the crate calling this method for binaries to use as the
433    /// contract and service bytecode files.
434    ///
435    /// Returns a tuple with the loaded contract and service [`Bytecode`]s,
436    /// ready to be published.
437    pub async fn find_bytecode_files_in(repository: &Path) -> (Bytecode, Bytecode) {
438        let manifest_path = repository.join("Cargo.toml");
439        let cargo_manifest =
440            Manifest::from_path(manifest_path).expect("Failed to load Cargo.toml manifest");
441
442        let binaries = cargo_manifest
443            .bin
444            .into_iter()
445            .filter_map(|binary| binary.name)
446            .filter(|name| name.ends_with("service") || name.ends_with("contract"))
447            .collect::<Vec<_>>();
448
449        assert_eq!(
450            binaries.len(),
451            2,
452            "Could not figure out contract and service bytecode binaries.\
453            Please specify them manually using `publish_module`."
454        );
455
456        let (contract_binary, service_binary) = if binaries[0].ends_with("contract") {
457            (&binaries[0], &binaries[1])
458        } else {
459            (&binaries[1], &binaries[0])
460        };
461
462        let base_path = Self::find_output_directory_of(repository)
463            .await
464            .expect("Failed to look for output binaries");
465        let contract_path = base_path.join(format!("{}.wasm", contract_binary));
466        let service_path = base_path.join(format!("{}.wasm", service_binary));
467
468        let contract = Bytecode::load_from_file(contract_path)
469            .await
470            .expect("Failed to load contract bytecode from file");
471        let service = Bytecode::load_from_file(service_path)
472            .await
473            .expect("Failed to load service bytecode from file");
474        (contract, service)
475    }
476
477    /// Returns a tuple with the loaded contract and service [`CompressedBytecode`]s,
478    /// ready to be published.
479    pub async fn find_compressed_bytecode_files_in(
480        repository: &Path,
481    ) -> (CompressedBytecode, CompressedBytecode) {
482        let (contract, service) = Self::find_bytecode_files_in(repository).await;
483        tokio::task::spawn_blocking(move || (contract.compress(), service.compress()))
484            .await
485            .expect("Failed to compress bytecode files")
486    }
487
488    /// Searches for the directory where the built WebAssembly binaries should be.
489    ///
490    /// Assumes that the binaries will be built and placed inside a
491    /// `target/wasm32-unknown-unknown/release` sub-directory. However, since the crate with the
492    /// binaries could be part of a workspace, that output sub-directory must be searched in parent
493    /// directories as well.
494    async fn find_output_directory_of(repository: &Path) -> Result<PathBuf, io::Error> {
495        let output_sub_directory = Path::new("target/wasm32-unknown-unknown/release");
496        let mut current_directory = repository;
497        let mut output_path = current_directory.join(output_sub_directory);
498
499        while !fs::try_exists(&output_path).await? {
500            current_directory = current_directory.parent().unwrap_or_else(|| {
501                panic!(
502                    "Failed to find Wasm binary output directory in {}",
503                    repository.display()
504                )
505            });
506
507            output_path = current_directory.join(output_sub_directory);
508        }
509
510        Ok(output_path)
511    }
512
513    /// Returns the height of the tip of this microchain.
514    pub async fn get_tip_height(&self) -> BlockHeight {
515        self.tip
516            .lock()
517            .await
518            .as_ref()
519            .expect("Block was not successfully added")
520            .inner()
521            .block()
522            .header
523            .height
524    }
525
526    /// Creates an application on this microchain, using the module referenced by `module_id`.
527    ///
528    /// Returns the [`ApplicationId`] of the created application.
529    ///
530    /// If necessary, this microchain will subscribe to the microchain that published the
531    /// module to use, and fetch it.
532    ///
533    /// The application is instantiated using the instantiation parameters, which consist of the
534    /// global static `parameters`, the one time `instantiation_argument` and the
535    /// `required_application_ids` of the applications that the new application will depend on.
536    pub async fn create_application<Abi, Parameters, InstantiationArgument>(
537        &mut self,
538        module_id: ModuleId<Abi, Parameters, InstantiationArgument>,
539        parameters: Parameters,
540        instantiation_argument: InstantiationArgument,
541        required_application_ids: Vec<ApplicationId>,
542    ) -> ApplicationId<Abi>
543    where
544        Abi: ContractAbi,
545        Parameters: Serialize,
546        InstantiationArgument: Serialize,
547    {
548        let parameters = serde_json::to_vec(&parameters).unwrap();
549        let instantiation_argument = serde_json::to_vec(&instantiation_argument).unwrap();
550
551        let (creation_certificate, _) = Box::pin(self.add_block(|block| {
552            block.with_system_operation(SystemOperation::CreateApplication {
553                module_id: module_id.forget_abi(),
554                parameters: parameters.clone(),
555                instantiation_argument,
556                required_application_ids: required_application_ids.clone(),
557            });
558        }))
559        .await;
560
561        let block = creation_certificate.inner().block();
562        assert_eq!(block.messages().len(), 1);
563
564        let description = ApplicationDescription {
565            module_id: module_id.forget_abi(),
566            creator_chain_id: block.header.chain_id,
567            block_height: block.header.height,
568            application_index: 0,
569            parameters,
570            required_application_ids,
571        };
572
573        ApplicationId::<()>::from(&description).with_abi()
574    }
575
576    /// Returns whether this chain has been closed.
577    pub async fn is_closed(&self) -> bool {
578        let chain = Box::pin(self.validator.worker().chain_state_view(self.id()))
579            .await
580            .expect("Failed to load chain");
581        *chain.execution_state.system.closed.get()
582    }
583
584    /// Executes a `query` on an `application`'s state on this microchain.
585    ///
586    /// Returns the deserialized response from the `application`.
587    pub async fn query<Abi>(
588        &self,
589        application_id: ApplicationId<Abi>,
590        query: Abi::Query,
591    ) -> QueryOutcome<Abi::QueryResponse>
592    where
593        Abi: ServiceAbi,
594    {
595        self.try_query(application_id, query)
596            .await
597            .expect("Failed to execute application service query")
598    }
599
600    /// Attempts to execute a `query` on an `application`'s state on this microchain.
601    ///
602    /// Returns the deserialized response from the `application`.
603    pub async fn try_query<Abi>(
604        &self,
605        application_id: ApplicationId<Abi>,
606        query: Abi::Query,
607    ) -> Result<QueryOutcome<Abi::QueryResponse>, TryQueryError>
608    where
609        Abi: ServiceAbi,
610    {
611        let query_bytes = serde_json::to_vec(&query)?;
612
613        let (
614            QueryOutcome {
615                response,
616                operations,
617            },
618            _,
619        ) = self
620            .validator
621            .worker()
622            .query_application(
623                self.id(),
624                Query::User {
625                    application_id: application_id.forget_abi(),
626                    bytes: query_bytes,
627                },
628                None,
629            )
630            .await?;
631
632        let deserialized_response = match response {
633            QueryResponse::User(bytes) => {
634                serde_json::from_slice(&bytes).expect("Failed to deserialize query response")
635            }
636            QueryResponse::System(_) => {
637                unreachable!("User query returned a system response")
638            }
639        };
640
641        Ok(QueryOutcome {
642            response: deserialized_response,
643            operations,
644        })
645    }
646
647    /// Executes a GraphQL `query` on an `application`'s state on this microchain.
648    ///
649    /// Returns the deserialized GraphQL JSON response from the `application`.
650    pub async fn graphql_query<Abi>(
651        &self,
652        application_id: ApplicationId<Abi>,
653        query: impl Into<async_graphql::Request>,
654    ) -> QueryOutcome<serde_json::Value>
655    where
656        Abi: ServiceAbi<Query = async_graphql::Request, QueryResponse = async_graphql::Response>,
657    {
658        let query = query.into();
659        let query_str = query.query.clone();
660
661        self.try_graphql_query(application_id, query)
662            .await
663            .unwrap_or_else(|error| panic!("Service query {query_str:?} failed: {error}"))
664    }
665
666    /// Attempts to execute a GraphQL `query` on an `application`'s state on this microchain.
667    ///
668    /// Returns the deserialized GraphQL JSON response from the `application`.
669    pub async fn try_graphql_query<Abi>(
670        &self,
671        application_id: ApplicationId<Abi>,
672        query: impl Into<async_graphql::Request>,
673    ) -> Result<QueryOutcome<serde_json::Value>, TryGraphQLQueryError>
674    where
675        Abi: ServiceAbi<Query = async_graphql::Request, QueryResponse = async_graphql::Response>,
676    {
677        let query = query.into();
678        let QueryOutcome {
679            response,
680            operations,
681        } = self.try_query(application_id, query).await?;
682
683        if !response.errors.is_empty() {
684            return Err(TryGraphQLQueryError::Service(response.errors));
685        }
686        let json_response = response.data.into_json()?;
687
688        Ok(QueryOutcome {
689            response: json_response,
690            operations,
691        })
692    }
693
694    /// Executes a GraphQL `mutation` on an `application` and proposes a block with the resulting
695    /// scheduled operations.
696    ///
697    /// Returns the certificate of the new block.
698    pub async fn graphql_mutation<Abi>(
699        &self,
700        application_id: ApplicationId<Abi>,
701        query: impl Into<async_graphql::Request>,
702    ) -> ConfirmedBlockCertificate
703    where
704        Abi: ServiceAbi<Query = async_graphql::Request, QueryResponse = async_graphql::Response>,
705    {
706        self.try_graphql_mutation(application_id, query)
707            .await
708            .expect("Failed to execute service GraphQL mutation")
709    }
710
711    /// Attempts to execute a GraphQL `mutation` on an `application` and proposes a block with the
712    /// resulting scheduled operations.
713    ///
714    /// Returns the certificate of the new block.
715    pub async fn try_graphql_mutation<Abi>(
716        &self,
717        application_id: ApplicationId<Abi>,
718        query: impl Into<async_graphql::Request>,
719    ) -> Result<ConfirmedBlockCertificate, TryGraphQLMutationError>
720    where
721        Abi: ServiceAbi<Query = async_graphql::Request, QueryResponse = async_graphql::Response>,
722    {
723        let QueryOutcome { operations, .. } = self.try_graphql_query(application_id, query).await?;
724
725        let (certificate, _) = Box::pin(self.try_add_block(|block| {
726            for operation in operations {
727                match operation {
728                    Operation::User {
729                        application_id,
730                        bytes,
731                    } => {
732                        block.with_raw_operation(application_id, bytes);
733                    }
734                    Operation::System(system_operation) => {
735                        block.with_system_operation(*system_operation);
736                    }
737                }
738            }
739        }))
740        .await?;
741
742        Ok(certificate)
743    }
744
745    /// Queries the balance of an account owned by `account_owner` on this chain.
746    pub async fn query_account(
747        &self,
748        application_id: ApplicationId<FungibleTokenAbi>,
749        account_owner: AccountOwner,
750    ) -> Option<Amount> {
751        use async_graphql::InputType as _;
752
753        let query = format!(
754            "query {{ accounts {{ entry(key: {}) {{ value }} }} }}",
755            account_owner.to_value()
756        );
757        let QueryOutcome { response, .. } = self.graphql_query(application_id, query).await;
758        let balance = response.pointer("/accounts/entry/value")?.as_str()?;
759
760        Some(
761            balance
762                .parse()
763                .expect("Account balance cannot be parsed as a number"),
764        )
765    }
766
767    /// Queries the allowance for an owner-spender pair on this chain.
768    pub async fn query_allowance(
769        &self,
770        application_id: ApplicationId<FungibleTokenAbi>,
771        owner: AccountOwner,
772        spender: AccountOwner,
773    ) -> Option<Amount> {
774        use async_graphql::InputType as _;
775
776        let owner_spender = OwnerSpender::new(owner, spender);
777        let query = format!(
778            "query {{ allowances {{ entry(key: {}) {{ value }} }} }}",
779            owner_spender.to_value()
780        );
781        let QueryOutcome { response, .. } = self.graphql_query(application_id, query).await;
782        let allowance = response.pointer("/allowances/entry/value")?.as_str()?;
783
784        Some(
785            allowance
786                .parse()
787                .expect("Allowance cannot be parsed as a number"),
788        )
789    }
790}
791
792/// Failure to query an application's service on a chain.
793#[derive(Debug, thiserror::Error)]
794pub enum TryQueryError {
795    /// The query request failed to serialize to JSON.
796    #[error("Failed to serialize query request")]
797    Serialization(#[from] serde_json::Error),
798
799    /// Executing the service to handle the query failed.
800    #[error("Failed to execute service query")]
801    Execution(#[from] WorkerError),
802}
803
804/// Failure to perform a GraphQL query on an application on a chain.
805#[derive(Debug, thiserror::Error)]
806pub enum TryGraphQLQueryError {
807    /// The [`async_graphql::Request`] failed to serialize to JSON.
808    #[error("Failed to serialize GraphQL query request")]
809    RequestSerialization(#[source] serde_json::Error),
810
811    /// Execution of the service failed.
812    #[error("Failed to execute service query")]
813    Execution(#[from] WorkerError),
814
815    /// The response returned from the service was not valid JSON.
816    #[error("Unexpected non-JSON service query response")]
817    ResponseDeserialization(#[from] serde_json::Error),
818
819    /// The service reported some errors.
820    #[error("Service returned errors: {_0:#?}")]
821    Service(Vec<async_graphql::ServerError>),
822}
823
824impl From<TryQueryError> for TryGraphQLQueryError {
825    fn from(query_error: TryQueryError) -> Self {
826        match query_error {
827            TryQueryError::Serialization(error) => {
828                TryGraphQLQueryError::RequestSerialization(error)
829            }
830            TryQueryError::Execution(error) => TryGraphQLQueryError::Execution(error),
831        }
832    }
833}
834
835impl TryGraphQLQueryError {
836    /// Returns the inner [`ExecutionError`] in this error.
837    ///
838    /// # Panics
839    ///
840    /// If this is not caused by an [`ExecutionError`].
841    pub fn expect_execution_error(self) -> ExecutionError {
842        let TryGraphQLQueryError::Execution(worker_error) = self else {
843            panic!("Expected an `ExecutionError`. Got: {self:#?}");
844        };
845
846        worker_error.expect_execution_error(ChainExecutionContext::Query)
847    }
848}
849
850/// Failure to perform a GraphQL mutation on an application on a chain.
851#[derive(Debug, thiserror::Error)]
852pub enum TryGraphQLMutationError {
853    /// The GraphQL query for the mutation failed.
854    #[error(transparent)]
855    Query(#[from] TryGraphQLQueryError),
856
857    /// The block with the mutation's scheduled operations failed to be proposed.
858    #[error("Failed to propose block with operations scheduled by the GraphQL mutation")]
859    Proposal(#[from] WorkerError),
860}
861
862impl TryGraphQLMutationError {
863    /// Returns the inner [`ExecutionError`] in this [`TryGraphQLMutationError::Proposal`] error.
864    ///
865    /// # Panics
866    ///
867    /// If this is not caused by an [`ExecutionError`] during a block proposal.
868    pub fn expect_proposal_execution_error(self, transaction_index: u32) -> ExecutionError {
869        let TryGraphQLMutationError::Proposal(proposal_error) = self else {
870            panic!("Expected an `ExecutionError` during the block proposal. Got: {self:#?}");
871        };
872
873        proposal_error.expect_execution_error(ChainExecutionContext::Operation(transaction_index))
874    }
875}