1pub mod committee;
8pub mod evm;
9mod execution;
10pub mod execution_state_actor;
11#[cfg(with_graphql)]
12mod graphql;
13mod policy;
14mod resources;
15mod runtime;
16pub mod system;
17#[cfg(with_testing)]
18pub mod test_utils;
19mod transaction_tracker;
20mod util;
21mod wasm;
22
23use std::{any::Any, collections::BTreeMap, fmt, ops::RangeInclusive, str::FromStr, sync::Arc};
24
25use allocative::Allocative;
26use async_graphql::SimpleObject;
27use async_trait::async_trait;
28use custom_debug_derive::Debug;
29use derive_more::Display;
30#[cfg(web)]
31use js_sys::wasm_bindgen::JsValue;
32use linera_base::{
33 abi::Abi,
34 crypto::{BcsHashable, CryptoHash},
35 data_types::{
36 Amount, ApplicationDescription, ApplicationPermissions, ArithmeticError, Blob, BlockHeight,
37 Bytecode, DecompressionError, Epoch, NetworkDescription, SendMessageRequest, StreamUpdate,
38 Timestamp,
39 },
40 doc_scalar, hex_debug, http,
41 identifiers::{
42 Account, AccountOwner, ApplicationId, BlobId, BlobType, ChainId, DataBlobHash, EventId,
43 GenericApplicationId, ModuleId, StreamId, StreamName,
44 },
45 ownership::ChainOwnership,
46 vm::VmRuntime,
47};
48use linera_views::{batch::Batch, ViewError};
49use serde::{Deserialize, Serialize};
50use system::AdminOperation;
51use thiserror::Error;
52pub use web_thread_pool::Pool as ThreadPool;
53use web_thread_select as web_thread;
54
55#[cfg(with_revm)]
56use crate::evm::EvmExecutionError;
57use crate::system::EPOCH_STREAM_NAME;
58#[cfg(with_testing)]
59use crate::test_utils::dummy_chain_description;
60#[cfg(all(with_testing, with_wasm_runtime))]
61pub use crate::wasm::test as wasm_test;
62#[cfg(with_wasm_runtime)]
63pub use crate::wasm::{
64 BaseRuntimeApi, ContractEntrypoints, ContractRuntimeApi, RuntimeApiData, ServiceEntrypoints,
65 ServiceRuntimeApi, WasmContractModule, WasmExecutionError, WasmServiceModule,
66};
67pub use crate::{
68 committee::{Committee, SharedCommittees},
69 execution::{ExecutionStateView, ServiceRuntimeEndpoint},
70 execution_state_actor::{ExecutionRequest, ExecutionStateActor},
71 policy::ResourceControlPolicy,
72 resources::{BalanceHolder, ResourceController, ResourceTracker},
73 runtime::{
74 ContractSyncRuntimeHandle, ServiceRuntimeRequest, ServiceSyncRuntime,
75 ServiceSyncRuntimeHandle,
76 },
77 system::{
78 SystemExecutionStateView, SystemMessage, SystemOperation, SystemQuery, SystemResponse,
79 },
80 transaction_tracker::{TransactionOutcome, TransactionTracker},
81};
82
83pub const LINERA_SOL: &str = include_str!("../solidity/Linera.sol");
86pub const LINERA_TYPES_SOL: &str = include_str!("../solidity/LineraTypes.sol");
87
88const MAX_STREAM_NAME_LEN: usize = 64;
90
91pub const FLAG_ZERO_HASH: &str = "FLAG_ZERO_HASH.linera.network";
96pub const FLAG_FREE_REJECT: &str = "FLAG_FREE_REJECT.linera.network";
100pub const FLAG_MANDATORY_APPS_NEED_ACCEPTED_MESSAGE: &str =
104 "FLAG_MANDATORY_APPS_NEED_ACCEPTED_MESSAGE.linera.network";
105pub const FLAG_FREE_APPLICATION_ID_PREFIX: &str = "FLAG_FREE_APPLICATION_ID_";
108pub const FLAG_FREE_APPLICATION_ID_SUFFIX: &str = ".linera.network";
110
111#[derive(Clone)]
113pub struct UserContractCode(Box<dyn UserContractModule>);
114
115#[derive(Clone)]
117pub struct UserServiceCode(Box<dyn UserServiceModule>);
118
119pub type UserContractInstance = Box<dyn UserContract>;
121
122pub type UserServiceInstance = Box<dyn UserService>;
124
125pub trait UserContractModule: dyn_clone::DynClone + Any + web_thread::Post + Send + Sync {
127 fn instantiate(
128 &self,
129 runtime: ContractSyncRuntimeHandle,
130 ) -> Result<UserContractInstance, ExecutionError>;
131}
132
133impl<T: UserContractModule + Send + Sync + 'static> From<T> for UserContractCode {
134 fn from(module: T) -> Self {
135 Self(Box::new(module))
136 }
137}
138
139dyn_clone::clone_trait_object!(UserContractModule);
140
141pub trait UserServiceModule: dyn_clone::DynClone + Any + web_thread::Post + Send + Sync {
143 fn instantiate(
144 &self,
145 runtime: ServiceSyncRuntimeHandle,
146 ) -> Result<UserServiceInstance, ExecutionError>;
147}
148
149impl<T: UserServiceModule + Send + Sync + 'static> From<T> for UserServiceCode {
150 fn from(module: T) -> Self {
151 Self(Box::new(module))
152 }
153}
154
155dyn_clone::clone_trait_object!(UserServiceModule);
156
157impl UserServiceCode {
158 fn instantiate(
159 &self,
160 runtime: ServiceSyncRuntimeHandle,
161 ) -> Result<UserServiceInstance, ExecutionError> {
162 self.0.instantiate(runtime)
163 }
164}
165
166impl UserContractCode {
167 fn instantiate(
168 &self,
169 runtime: ContractSyncRuntimeHandle,
170 ) -> Result<UserContractInstance, ExecutionError> {
171 self.0.instantiate(runtime)
172 }
173}
174
175pub struct JsVec<T>(pub Vec<T>);
176
177#[cfg(web)]
178const _: () = {
179 impl web_thread::AsJs for UserContractCode {
183 fn to_js(&self) -> Result<JsValue, JsValue> {
184 ((&*self.0) as &dyn Any)
185 .downcast_ref::<WasmContractModule>()
186 .expect("we only support Wasm modules on the Web for now")
187 .to_js()
188 }
189
190 fn from_js(value: JsValue) -> Result<Self, JsValue> {
191 WasmContractModule::from_js(value).map(Into::into)
192 }
193 }
194
195 impl web_thread::Post for UserContractCode {
196 fn transferables(&self) -> js_sys::Array {
197 self.0.transferables()
198 }
199 }
200
201 impl web_thread::AsJs for UserServiceCode {
202 fn to_js(&self) -> Result<JsValue, JsValue> {
203 ((&*self.0) as &dyn Any)
204 .downcast_ref::<WasmServiceModule>()
205 .expect("we only support Wasm modules on the Web for now")
206 .to_js()
207 }
208
209 fn from_js(value: JsValue) -> Result<Self, JsValue> {
210 WasmServiceModule::from_js(value).map(Into::into)
211 }
212 }
213
214 impl web_thread::Post for UserServiceCode {
215 fn transferables(&self) -> js_sys::Array {
216 self.0.transferables()
217 }
218 }
219
220 impl<T: web_thread::AsJs> web_thread::AsJs for JsVec<T> {
221 fn to_js(&self) -> Result<JsValue, JsValue> {
222 let array = self
223 .0
224 .iter()
225 .map(T::to_js)
226 .collect::<Result<js_sys::Array, _>>()?;
227 Ok(array.into())
228 }
229
230 fn from_js(value: JsValue) -> Result<Self, JsValue> {
231 let array = js_sys::Array::from(&value);
232 let v = array
233 .into_iter()
234 .map(T::from_js)
235 .collect::<Result<Vec<_>, _>>()?;
236 Ok(JsVec(v))
237 }
238 }
239
240 impl<T: web_thread::Post> web_thread::Post for JsVec<T> {
241 fn transferables(&self) -> js_sys::Array {
242 let mut array = js_sys::Array::new();
243 for x in &self.0 {
244 array = array.concat(&x.transferables());
245 }
246 array
247 }
248 }
249};
250
251#[derive(Error, Debug, strum::IntoStaticStr)]
253pub enum ExecutionError {
254 #[error(transparent)]
255 ViewError(#[from] ViewError),
256 #[error(transparent)]
257 ArithmeticError(#[from] ArithmeticError),
258 #[error("User application reported an error: {0}")]
259 UserError(String),
260 #[cfg(with_wasm_runtime)]
261 #[error(transparent)]
262 WasmError(#[from] WasmExecutionError),
263 #[cfg(with_revm)]
264 #[error(transparent)]
265 EvmError(#[from] EvmExecutionError),
266 #[error(transparent)]
267 DecompressionError(#[from] DecompressionError),
268 #[error("The given promise is invalid or was polled once already")]
269 InvalidPromise,
270
271 #[error("Attempted to perform a reentrant call to application {0}")]
272 ReentrantCall(ApplicationId),
273 #[error(
274 "Application {caller_id} attempted to perform a cross-application to {callee_id} call \
275 from `finalize`"
276 )]
277 CrossApplicationCallInFinalize {
278 caller_id: Box<ApplicationId>,
279 callee_id: Box<ApplicationId>,
280 },
281 #[error("Failed to load bytecode from storage {0:?}")]
282 ApplicationBytecodeNotFound(Box<ApplicationDescription>),
283 #[error("Unsupported dynamic application load: {0:?}")]
285 UnsupportedDynamicApplicationLoad(Box<ApplicationId>),
286
287 #[error("Excessive number of bytes read from storage")]
288 ExcessiveRead,
289 #[error("Excessive number of bytes written to storage")]
290 ExcessiveWrite,
291 #[error("Block execution required too much fuel for VM {0}")]
292 MaximumFuelExceeded(VmRuntime),
293 #[error("Services running as oracles in block took longer than allowed")]
294 MaximumServiceOracleExecutionTimeExceeded,
295 #[error("Service running as an oracle produced a response that's too large")]
296 ServiceOracleResponseTooLarge,
297 #[error("Serialized size of the block exceeds limit")]
298 BlockTooLarge,
299 #[error("HTTP response exceeds the size limit of {limit} bytes, having at least {size} bytes")]
300 HttpResponseSizeLimitExceeded { limit: u64, size: u64 },
301 #[error("Runtime failed to respond to application")]
302 MissingRuntimeResponse,
303 #[error("Application is not authorized to perform system operations on this chain: {0:}")]
304 UnauthorizedApplication(ApplicationId),
305 #[error("Failed to make network reqwest: {0}")]
306 ReqwestError(#[from] reqwest::Error),
307 #[error("Encountered I/O error: {0}")]
308 IoError(#[from] std::io::Error),
309 #[error("More recorded oracle responses than expected")]
310 UnexpectedOracleResponse,
311 #[error("Invalid JSON: {0}")]
312 JsonError(#[from] serde_json::Error),
313 #[error(transparent)]
314 BcsError(#[from] bcs::Error),
315 #[error("Recorded response for oracle query has the wrong type")]
316 OracleResponseMismatch,
317 #[error("Service oracle query tried to create operations: {0:?}")]
318 ServiceOracleQueryOperations(Vec<Operation>),
319 #[error("Assertion failed: local time {local_time} is not earlier than {timestamp}")]
320 AssertBefore {
321 timestamp: Timestamp,
322 local_time: Timestamp,
323 },
324
325 #[error("Stream names can be at most {MAX_STREAM_NAME_LEN} bytes.")]
326 StreamNameTooLong,
327 #[error("Blob exceeds size limit")]
328 BlobTooLarge,
329 #[error("Bytecode exceeds size limit")]
330 BytecodeTooLarge,
331 #[error("Attempt to perform an HTTP request to an unauthorized host: {0:?}")]
332 UnauthorizedHttpRequest(reqwest::Url),
333 #[error("Attempt to perform an HTTP request to an invalid URL")]
334 InvalidUrlForHttpRequest(#[from] url::ParseError),
335 #[error("Worker thread failure: {0:?}")]
336 Thread(#[from] web_thread::Error),
337 #[error("The chain being queried is not active {0}")]
338 InactiveChain(ChainId),
339 #[error("Blobs not found: {0:?}")]
340 BlobsNotFound(Vec<BlobId>),
341 #[error("Events not found: {0:?}")]
342 EventsNotFound(Vec<EventId>),
343
344 #[error("Invalid HTTP header name used for HTTP request")]
345 InvalidHeaderName(#[from] reqwest::header::InvalidHeaderName),
346 #[error("Invalid HTTP header value used for HTTP request")]
347 InvalidHeaderValue(#[from] reqwest::header::InvalidHeaderValue),
348
349 #[error("No NetworkDescription found in storage")]
350 NoNetworkDescriptionFound,
351 #[error("{epoch:?} is not recognized by chain {chain_id:}")]
352 InvalidEpoch { chain_id: ChainId, epoch: Epoch },
353 #[error("Transfer must have positive amount")]
354 IncorrectTransferAmount,
355 #[error("Transfer from owned account must be authenticated by the right signer")]
356 UnauthenticatedTransferOwner,
357 #[error("The transferred amount must not exceed the balance of the current account {account}: {balance}")]
358 InsufficientBalance {
359 balance: Amount,
360 account: AccountOwner,
361 },
362 #[error("Required execution fees exceeded the total funding available. Fees {fees}, available balance: {balance}")]
363 FeesExceedFunding { fees: Amount, balance: Amount },
364 #[error("Claim must have positive amount")]
365 IncorrectClaimAmount,
366 #[error("Claim must be authenticated by the right signer")]
367 UnauthenticatedClaimOwner,
368 #[error("Admin operations are only allowed on the admin chain.")]
369 AdminOperationOnNonAdminChain,
370 #[error("Failed to create new committee: expected {expected}, but got {provided}")]
371 InvalidCommitteeEpoch { expected: Epoch, provided: Epoch },
372 #[error("Failed to remove committee")]
373 InvalidCommitteeRemoval,
374 #[error("No recorded response for oracle query")]
375 MissingOracleResponse,
376 #[error("process_streams was not called for all stream updates")]
377 UnprocessedStreams,
378 #[error("Internal error: {0}")]
379 InternalError(&'static str),
380 #[error("UpdateStreams is outdated")]
381 OutdatedUpdateStreams,
382}
383
384impl ExecutionError {
385 pub fn is_local(&self) -> bool {
389 match self {
390 ExecutionError::ArithmeticError(_)
391 | ExecutionError::UserError(_)
392 | ExecutionError::DecompressionError(_)
393 | ExecutionError::InvalidPromise
394 | ExecutionError::CrossApplicationCallInFinalize { .. }
395 | ExecutionError::ReentrantCall(_)
396 | ExecutionError::ApplicationBytecodeNotFound(_)
397 | ExecutionError::UnsupportedDynamicApplicationLoad(_)
398 | ExecutionError::ExcessiveRead
399 | ExecutionError::ExcessiveWrite
400 | ExecutionError::MaximumFuelExceeded(_)
401 | ExecutionError::MaximumServiceOracleExecutionTimeExceeded
402 | ExecutionError::ServiceOracleResponseTooLarge
403 | ExecutionError::BlockTooLarge
404 | ExecutionError::HttpResponseSizeLimitExceeded { .. }
405 | ExecutionError::UnauthorizedApplication(_)
406 | ExecutionError::UnexpectedOracleResponse
407 | ExecutionError::JsonError(_)
408 | ExecutionError::BcsError(_)
409 | ExecutionError::OracleResponseMismatch
410 | ExecutionError::ServiceOracleQueryOperations(_)
411 | ExecutionError::AssertBefore { .. }
412 | ExecutionError::StreamNameTooLong
413 | ExecutionError::BlobTooLarge
414 | ExecutionError::BytecodeTooLarge
415 | ExecutionError::UnauthorizedHttpRequest(_)
416 | ExecutionError::InvalidUrlForHttpRequest(_)
417 | ExecutionError::InactiveChain(_)
418 | ExecutionError::BlobsNotFound(_)
419 | ExecutionError::EventsNotFound(_)
420 | ExecutionError::InvalidHeaderName(_)
421 | ExecutionError::InvalidHeaderValue(_)
422 | ExecutionError::InvalidEpoch { .. }
423 | ExecutionError::IncorrectTransferAmount
424 | ExecutionError::UnauthenticatedTransferOwner
425 | ExecutionError::InsufficientBalance { .. }
426 | ExecutionError::FeesExceedFunding { .. }
427 | ExecutionError::IncorrectClaimAmount
428 | ExecutionError::UnauthenticatedClaimOwner
429 | ExecutionError::AdminOperationOnNonAdminChain
430 | ExecutionError::InvalidCommitteeEpoch { .. }
431 | ExecutionError::InvalidCommitteeRemoval
432 | ExecutionError::MissingOracleResponse
433 | ExecutionError::UnprocessedStreams
434 | ExecutionError::OutdatedUpdateStreams
435 | ExecutionError::ViewError(ViewError::NotFound(_)) => false,
436 #[cfg(with_wasm_runtime)]
437 ExecutionError::WasmError(_) => false,
438 #[cfg(with_revm)]
439 ExecutionError::EvmError(..) => false,
440 ExecutionError::MissingRuntimeResponse
441 | ExecutionError::ViewError(_)
442 | ExecutionError::ReqwestError(_)
443 | ExecutionError::Thread(_)
444 | ExecutionError::NoNetworkDescriptionFound
445 | ExecutionError::InternalError(_)
446 | ExecutionError::IoError(_) => true,
447 }
448 }
449
450 pub fn error_type(&self) -> String {
453 let variant: &'static str = self.into();
454 format!("ExecutionError::{variant}")
455 }
456
457 pub fn is_limit_error(&self) -> bool {
462 matches!(
463 self,
464 ExecutionError::ExcessiveRead
465 | ExecutionError::ExcessiveWrite
466 | ExecutionError::MaximumFuelExceeded(_)
467 | ExecutionError::MaximumServiceOracleExecutionTimeExceeded
468 | ExecutionError::BlockTooLarge
469 )
470 }
471
472 pub fn is_transient_error(&self) -> bool {
478 matches!(
479 self,
480 ExecutionError::BlobsNotFound(_) | ExecutionError::EventsNotFound(_)
481 )
482 }
483}
484
485pub trait UserContract {
487 fn instantiate(&mut self, argument: Vec<u8>) -> Result<(), ExecutionError>;
489
490 fn execute_operation(&mut self, operation: Vec<u8>) -> Result<Vec<u8>, ExecutionError>;
492
493 fn execute_message(&mut self, message: Vec<u8>) -> Result<(), ExecutionError>;
495
496 fn process_streams(&mut self, updates: Vec<StreamUpdate>) -> Result<(), ExecutionError>;
498
499 fn finalize(&mut self) -> Result<(), ExecutionError>;
501}
502
503pub trait UserService {
505 fn handle_query(&mut self, argument: Vec<u8>) -> Result<Vec<u8>, ExecutionError>;
507}
508
509#[derive(Clone, Copy)]
511pub struct ExecutionRuntimeConfig {
512 pub allow_application_logs: bool,
515}
516
517impl Default for ExecutionRuntimeConfig {
518 fn default() -> Self {
519 Self {
520 allow_application_logs: true,
521 }
522 }
523}
524
525#[cfg_attr(not(web), async_trait)]
528#[cfg_attr(web, async_trait(?Send))]
529pub trait ExecutionRuntimeContext {
530 fn chain_id(&self) -> ChainId;
531
532 fn thread_pool(&self) -> &Arc<ThreadPool>;
533
534 fn execution_runtime_config(&self) -> ExecutionRuntimeConfig;
535
536 fn user_contracts(&self) -> &Arc<papaya::HashMap<ApplicationId, UserContractCode>>;
537
538 fn user_services(&self) -> &Arc<papaya::HashMap<ApplicationId, UserServiceCode>>;
539
540 async fn get_user_contract(
541 &self,
542 description: &ApplicationDescription,
543 txn_tracker: &TransactionTracker,
544 ) -> Result<UserContractCode, ExecutionError>;
545
546 async fn get_user_service(
547 &self,
548 description: &ApplicationDescription,
549 txn_tracker: &TransactionTracker,
550 ) -> Result<UserServiceCode, ExecutionError>;
551
552 async fn get_blob(&self, blob_id: BlobId) -> Result<Option<Arc<Blob>>, ViewError>;
553
554 async fn get_event(&self, event_id: EventId) -> Result<Option<Arc<Vec<u8>>>, ViewError>;
555
556 async fn get_network_description(&self) -> Result<Option<NetworkDescription>, ViewError>;
557
558 async fn get_committees(
562 &self,
563 epoch_range: RangeInclusive<Epoch>,
564 ) -> Result<BTreeMap<Epoch, Committee>, ExecutionError> {
565 let mut committees = BTreeMap::new();
566 let mut missing = Vec::new();
567 for index in epoch_range.start().0..=epoch_range.end().0 {
568 let epoch = Epoch(index);
569 match self.get_or_load_committee(epoch).await? {
570 Some(committee) => {
571 committees.insert(epoch, (*committee).clone());
572 }
573 None => missing.push(epoch),
574 }
575 }
576 if !missing.is_empty() {
577 let net_description = self
578 .get_network_description()
579 .await?
580 .ok_or(ExecutionError::NoNetworkDescriptionFound)?;
581 let event_ids = missing
582 .into_iter()
583 .map(|epoch| EventId {
584 chain_id: net_description.admin_chain_id,
585 stream_id: StreamId::system(EPOCH_STREAM_NAME),
586 index: epoch.0,
587 })
588 .collect();
589 return Err(ExecutionError::EventsNotFound(event_ids));
590 }
591 Ok(committees)
592 }
593
594 async fn get_or_load_committee(
607 &self,
608 epoch: Epoch,
609 ) -> Result<Option<Arc<Committee>>, ViewError>;
610
611 async fn contains_blob(&self, blob_id: BlobId) -> Result<bool, ViewError>;
612
613 async fn contains_event(&self, event_id: EventId) -> Result<bool, ViewError>;
614
615 #[cfg(with_testing)]
616 async fn add_blobs(
617 &self,
618 blobs: impl IntoIterator<Item = Blob> + Send,
619 ) -> Result<(), ViewError>;
620
621 #[cfg(with_testing)]
622 async fn add_events(
623 &self,
624 events: impl IntoIterator<Item = (EventId, Vec<u8>)> + Send,
625 ) -> Result<(), ViewError>;
626}
627
628#[derive(Clone, Copy, Debug)]
629pub struct OperationContext {
630 pub chain_id: ChainId,
632 #[debug(skip_if = Option::is_none)]
634 pub authenticated_signer: Option<AccountOwner>,
635 pub height: BlockHeight,
637 pub round: Option<u32>,
639 pub timestamp: Timestamp,
641}
642
643#[derive(Clone, Copy, Debug)]
644pub struct MessageContext {
645 pub chain_id: ChainId,
647 pub origin: ChainId,
649 pub is_bouncing: bool,
651 #[debug(skip_if = Option::is_none)]
653 pub authenticated_signer: Option<AccountOwner>,
654 #[debug(skip_if = Option::is_none)]
656 pub refund_grant_to: Option<Account>,
657 pub height: BlockHeight,
659 pub round: Option<u32>,
661 pub timestamp: Timestamp,
663}
664
665#[derive(Clone, Copy, Debug)]
666pub struct ProcessStreamsContext {
667 pub chain_id: ChainId,
669 pub height: BlockHeight,
671 pub round: Option<u32>,
673 pub timestamp: Timestamp,
675}
676
677impl From<MessageContext> for ProcessStreamsContext {
678 fn from(context: MessageContext) -> Self {
679 Self {
680 chain_id: context.chain_id,
681 height: context.height,
682 round: context.round,
683 timestamp: context.timestamp,
684 }
685 }
686}
687
688impl From<OperationContext> for ProcessStreamsContext {
689 fn from(context: OperationContext) -> Self {
690 Self {
691 chain_id: context.chain_id,
692 height: context.height,
693 round: context.round,
694 timestamp: context.timestamp,
695 }
696 }
697}
698
699#[derive(Clone, Copy, Debug)]
700pub struct FinalizeContext {
701 pub chain_id: ChainId,
703 #[debug(skip_if = Option::is_none)]
705 pub authenticated_signer: Option<AccountOwner>,
706 pub height: BlockHeight,
708 pub round: Option<u32>,
710}
711
712#[derive(Clone, Copy, Debug, Eq, PartialEq)]
713pub struct QueryContext {
714 pub chain_id: ChainId,
716 pub next_block_height: BlockHeight,
718 pub local_time: Timestamp,
720}
721
722pub trait BaseRuntime {
723 type Read: fmt::Debug + Send + Sync;
724 type ContainsKey: fmt::Debug + Send + Sync;
725 type ContainsKeys: fmt::Debug + Send + Sync;
726 type ReadMultiValuesBytes: fmt::Debug + Send + Sync;
727 type ReadValueBytes: fmt::Debug + Send + Sync;
728 type FindKeysByPrefix: fmt::Debug + Send + Sync;
729 type FindKeyValuesByPrefix: fmt::Debug + Send + Sync;
730
731 fn chain_id(&mut self) -> Result<ChainId, ExecutionError>;
733
734 fn block_height(&mut self) -> Result<BlockHeight, ExecutionError>;
736
737 fn application_id(&mut self) -> Result<ApplicationId, ExecutionError>;
739
740 fn application_creator_chain_id(&mut self) -> Result<ChainId, ExecutionError>;
742
743 fn read_application_description(
745 &mut self,
746 application_id: ApplicationId,
747 ) -> Result<ApplicationDescription, ExecutionError>;
748
749 fn application_parameters(&mut self) -> Result<Vec<u8>, ExecutionError>;
751
752 fn read_system_timestamp(&mut self) -> Result<Timestamp, ExecutionError>;
754
755 fn read_chain_balance(&mut self) -> Result<Amount, ExecutionError>;
757
758 fn read_owner_balance(&mut self, owner: AccountOwner) -> Result<Amount, ExecutionError>;
760
761 fn read_owner_balances(&mut self) -> Result<Vec<(AccountOwner, Amount)>, ExecutionError>;
763
764 fn read_balance_owners(&mut self) -> Result<Vec<AccountOwner>, ExecutionError>;
766
767 fn chain_ownership(&mut self) -> Result<ChainOwnership, ExecutionError>;
769
770 fn application_permissions(&mut self) -> Result<ApplicationPermissions, ExecutionError>;
772
773 #[cfg(feature = "test")]
775 fn contains_key(&mut self, key: Vec<u8>) -> Result<bool, ExecutionError> {
776 let promise = self.contains_key_new(key)?;
777 self.contains_key_wait(&promise)
778 }
779
780 fn contains_key_new(&mut self, key: Vec<u8>) -> Result<Self::ContainsKey, ExecutionError>;
782
783 fn contains_key_wait(&mut self, promise: &Self::ContainsKey) -> Result<bool, ExecutionError>;
785
786 #[cfg(feature = "test")]
788 fn contains_keys(&mut self, keys: Vec<Vec<u8>>) -> Result<Vec<bool>, ExecutionError> {
789 let promise = self.contains_keys_new(keys)?;
790 self.contains_keys_wait(&promise)
791 }
792
793 fn contains_keys_new(
795 &mut self,
796 keys: Vec<Vec<u8>>,
797 ) -> Result<Self::ContainsKeys, ExecutionError>;
798
799 fn contains_keys_wait(
801 &mut self,
802 promise: &Self::ContainsKeys,
803 ) -> Result<Vec<bool>, ExecutionError>;
804
805 #[cfg(feature = "test")]
807 fn read_multi_values_bytes(
808 &mut self,
809 keys: Vec<Vec<u8>>,
810 ) -> Result<Vec<Option<Vec<u8>>>, ExecutionError> {
811 let promise = self.read_multi_values_bytes_new(keys)?;
812 self.read_multi_values_bytes_wait(&promise)
813 }
814
815 fn read_multi_values_bytes_new(
817 &mut self,
818 keys: Vec<Vec<u8>>,
819 ) -> Result<Self::ReadMultiValuesBytes, ExecutionError>;
820
821 fn read_multi_values_bytes_wait(
823 &mut self,
824 promise: &Self::ReadMultiValuesBytes,
825 ) -> Result<Vec<Option<Vec<u8>>>, ExecutionError>;
826
827 #[cfg(feature = "test")]
829 fn read_value_bytes(&mut self, key: Vec<u8>) -> Result<Option<Vec<u8>>, ExecutionError> {
830 let promise = self.read_value_bytes_new(key)?;
831 self.read_value_bytes_wait(&promise)
832 }
833
834 fn read_value_bytes_new(
836 &mut self,
837 key: Vec<u8>,
838 ) -> Result<Self::ReadValueBytes, ExecutionError>;
839
840 fn read_value_bytes_wait(
842 &mut self,
843 promise: &Self::ReadValueBytes,
844 ) -> Result<Option<Vec<u8>>, ExecutionError>;
845
846 fn find_keys_by_prefix_new(
848 &mut self,
849 key_prefix: Vec<u8>,
850 ) -> Result<Self::FindKeysByPrefix, ExecutionError>;
851
852 fn find_keys_by_prefix_wait(
854 &mut self,
855 promise: &Self::FindKeysByPrefix,
856 ) -> Result<Vec<Vec<u8>>, ExecutionError>;
857
858 #[cfg(feature = "test")]
860 #[expect(clippy::type_complexity)]
861 fn find_key_values_by_prefix(
862 &mut self,
863 key_prefix: Vec<u8>,
864 ) -> Result<Vec<(Vec<u8>, Vec<u8>)>, ExecutionError> {
865 let promise = self.find_key_values_by_prefix_new(key_prefix)?;
866 self.find_key_values_by_prefix_wait(&promise)
867 }
868
869 fn find_key_values_by_prefix_new(
871 &mut self,
872 key_prefix: Vec<u8>,
873 ) -> Result<Self::FindKeyValuesByPrefix, ExecutionError>;
874
875 #[expect(clippy::type_complexity)]
877 fn find_key_values_by_prefix_wait(
878 &mut self,
879 promise: &Self::FindKeyValuesByPrefix,
880 ) -> Result<Vec<(Vec<u8>, Vec<u8>)>, ExecutionError>;
881
882 fn perform_http_request(
884 &mut self,
885 request: http::Request,
886 ) -> Result<http::Response, ExecutionError>;
887
888 fn assert_before(&mut self, timestamp: Timestamp) -> Result<(), ExecutionError>;
894
895 fn read_data_blob(&mut self, hash: DataBlobHash) -> Result<Vec<u8>, ExecutionError>;
897
898 fn assert_data_blob_exists(&mut self, hash: DataBlobHash) -> Result<(), ExecutionError>;
900
901 fn allow_application_logs(&mut self) -> Result<bool, ExecutionError>;
904
905 #[cfg(web)]
908 fn send_log(&mut self, message: String, level: tracing::log::Level);
909}
910
911pub trait ServiceRuntime: BaseRuntime {
912 fn try_query_application(
914 &mut self,
915 queried_id: ApplicationId,
916 argument: Vec<u8>,
917 ) -> Result<Vec<u8>, ExecutionError>;
918
919 fn schedule_operation(&mut self, operation: Vec<u8>) -> Result<(), ExecutionError>;
921
922 fn check_execution_time(&mut self) -> Result<(), ExecutionError>;
924}
925
926pub trait ContractRuntime: BaseRuntime {
927 fn authenticated_signer(&mut self) -> Result<Option<AccountOwner>, ExecutionError>;
929
930 fn message_is_bouncing(&mut self) -> Result<Option<bool>, ExecutionError>;
933
934 fn message_origin_chain_id(&mut self) -> Result<Option<ChainId>, ExecutionError>;
936
937 fn authenticated_caller_id(&mut self) -> Result<Option<ApplicationId>, ExecutionError>;
940
941 fn maximum_fuel_per_block(&mut self, vm_runtime: VmRuntime) -> Result<u64, ExecutionError>;
943
944 fn remaining_fuel(&mut self, vm_runtime: VmRuntime) -> Result<u64, ExecutionError>;
946
947 fn consume_fuel(&mut self, fuel: u64, vm_runtime: VmRuntime) -> Result<(), ExecutionError>;
949
950 fn send_message(&mut self, message: SendMessageRequest<Vec<u8>>) -> Result<(), ExecutionError>;
952
953 fn transfer(
955 &mut self,
956 source: AccountOwner,
957 destination: Account,
958 amount: Amount,
959 ) -> Result<(), ExecutionError>;
960
961 fn claim(
963 &mut self,
964 source: Account,
965 destination: Account,
966 amount: Amount,
967 ) -> Result<(), ExecutionError>;
968
969 fn try_call_application(
972 &mut self,
973 authenticated: bool,
974 callee_id: ApplicationId,
975 argument: Vec<u8>,
976 ) -> Result<Vec<u8>, ExecutionError>;
977
978 fn emit(&mut self, name: StreamName, value: Vec<u8>) -> Result<u32, ExecutionError>;
980
981 fn read_event(
985 &mut self,
986 chain_id: ChainId,
987 stream_name: StreamName,
988 index: u32,
989 ) -> Result<Vec<u8>, ExecutionError>;
990
991 fn subscribe_to_events(
993 &mut self,
994 chain_id: ChainId,
995 application_id: ApplicationId,
996 stream_name: StreamName,
997 ) -> Result<(), ExecutionError>;
998
999 fn unsubscribe_from_events(
1001 &mut self,
1002 chain_id: ChainId,
1003 application_id: ApplicationId,
1004 stream_name: StreamName,
1005 ) -> Result<(), ExecutionError>;
1006
1007 fn query_service(
1009 &mut self,
1010 application_id: ApplicationId,
1011 query: Vec<u8>,
1012 ) -> Result<Vec<u8>, ExecutionError>;
1013
1014 fn open_chain(
1016 &mut self,
1017 ownership: ChainOwnership,
1018 application_permissions: ApplicationPermissions,
1019 balance: Amount,
1020 ) -> Result<ChainId, ExecutionError>;
1021
1022 fn close_chain(&mut self) -> Result<(), ExecutionError>;
1024
1025 fn change_ownership(&mut self, ownership: ChainOwnership) -> Result<(), ExecutionError>;
1027
1028 fn change_application_permissions(
1030 &mut self,
1031 application_permissions: ApplicationPermissions,
1032 ) -> Result<(), ExecutionError>;
1033
1034 fn create_application(
1036 &mut self,
1037 module_id: ModuleId,
1038 parameters: Vec<u8>,
1039 argument: Vec<u8>,
1040 required_application_ids: Vec<ApplicationId>,
1041 ) -> Result<ApplicationId, ExecutionError>;
1042
1043 fn create_data_blob(&mut self, bytes: Vec<u8>) -> Result<DataBlobHash, ExecutionError>;
1045
1046 fn publish_module(
1048 &mut self,
1049 contract: Bytecode,
1050 service: Bytecode,
1051 vm_runtime: VmRuntime,
1052 ) -> Result<ModuleId, ExecutionError>;
1053
1054 fn validation_round(&mut self) -> Result<Option<u32>, ExecutionError>;
1056
1057 fn write_batch(&mut self, batch: Batch) -> Result<(), ExecutionError>;
1059}
1060
1061#[derive(
1063 Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, Allocative, strum::AsRefStr,
1064)]
1065pub enum Operation {
1066 System(Box<SystemOperation>),
1068 User {
1070 application_id: ApplicationId,
1071 #[serde(with = "serde_bytes")]
1072 #[debug(with = "hex_debug")]
1073 bytes: Vec<u8>,
1074 },
1075}
1076
1077impl BcsHashable<'_> for Operation {}
1078
1079#[derive(
1081 Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, Allocative, strum::AsRefStr,
1082)]
1083pub enum Message {
1084 System(SystemMessage),
1086 User {
1088 application_id: ApplicationId,
1089 #[serde(with = "serde_bytes")]
1090 #[debug(with = "hex_debug")]
1091 bytes: Vec<u8>,
1092 },
1093}
1094
1095#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1097pub enum Query {
1098 System(SystemQuery),
1100 User {
1102 application_id: ApplicationId,
1103 #[serde(with = "serde_bytes")]
1104 #[debug(with = "hex_debug")]
1105 bytes: Vec<u8>,
1106 },
1107}
1108
1109#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1111pub struct QueryOutcome<Response = QueryResponse> {
1112 pub response: Response,
1113 pub operations: Vec<Operation>,
1114}
1115
1116impl From<QueryOutcome<SystemResponse>> for QueryOutcome {
1117 fn from(system_outcome: QueryOutcome<SystemResponse>) -> Self {
1118 let QueryOutcome {
1119 response,
1120 operations,
1121 } = system_outcome;
1122
1123 QueryOutcome {
1124 response: QueryResponse::System(response),
1125 operations,
1126 }
1127 }
1128}
1129
1130impl From<QueryOutcome<Vec<u8>>> for QueryOutcome {
1131 fn from(user_service_outcome: QueryOutcome<Vec<u8>>) -> Self {
1132 let QueryOutcome {
1133 response,
1134 operations,
1135 } = user_service_outcome;
1136
1137 QueryOutcome {
1138 response: QueryResponse::User(response),
1139 operations,
1140 }
1141 }
1142}
1143
1144#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1146pub enum QueryResponse {
1147 System(SystemResponse),
1149 User(
1151 #[serde(with = "serde_bytes")]
1152 #[debug(with = "hex_debug")]
1153 Vec<u8>,
1154 ),
1155}
1156
1157#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, Copy, Allocative)]
1159pub enum MessageKind {
1160 Simple,
1162 Protected,
1165 Tracked,
1168 Bouncing,
1170}
1171
1172impl Display for MessageKind {
1173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1174 match self {
1175 MessageKind::Simple => write!(f, "Simple"),
1176 MessageKind::Protected => write!(f, "Protected"),
1177 MessageKind::Tracked => write!(f, "Tracked"),
1178 MessageKind::Bouncing => write!(f, "Bouncing"),
1179 }
1180 }
1181}
1182
1183#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, SimpleObject, Allocative)]
1185pub struct OutgoingMessage {
1186 pub destination: ChainId,
1188 #[debug(skip_if = Option::is_none)]
1190 pub authenticated_signer: Option<AccountOwner>,
1191 #[debug(skip_if = Amount::is_zero)]
1193 pub grant: Amount,
1194 #[debug(skip_if = Option::is_none)]
1196 pub refund_grant_to: Option<Account>,
1197 pub kind: MessageKind,
1199 pub message: Message,
1201}
1202
1203impl BcsHashable<'_> for OutgoingMessage {}
1204
1205impl OutgoingMessage {
1206 pub fn new(recipient: ChainId, message: impl Into<Message>) -> Self {
1208 OutgoingMessage {
1209 destination: recipient,
1210 authenticated_signer: None,
1211 grant: Amount::ZERO,
1212 refund_grant_to: None,
1213 kind: MessageKind::Simple,
1214 message: message.into(),
1215 }
1216 }
1217
1218 pub fn with_kind(mut self, kind: MessageKind) -> Self {
1220 self.kind = kind;
1221 self
1222 }
1223
1224 pub fn with_authenticated_signer(mut self, authenticated_signer: Option<AccountOwner>) -> Self {
1226 self.authenticated_signer = authenticated_signer;
1227 self
1228 }
1229}
1230
1231impl OperationContext {
1232 fn refund_grant_to(&self) -> Option<Account> {
1235 self.authenticated_signer.map(|owner| Account {
1236 chain_id: self.chain_id,
1237 owner,
1238 })
1239 }
1240}
1241
1242#[cfg(with_testing)]
1243#[derive(Clone)]
1244pub struct TestExecutionRuntimeContext {
1245 chain_id: ChainId,
1246 thread_pool: Arc<ThreadPool>,
1247 execution_runtime_config: ExecutionRuntimeConfig,
1248 user_contracts: Arc<papaya::HashMap<ApplicationId, UserContractCode>>,
1249 user_services: Arc<papaya::HashMap<ApplicationId, UserServiceCode>>,
1250 blobs: Arc<papaya::HashMap<BlobId, Blob>>,
1251 events: Arc<papaya::HashMap<EventId, Vec<u8>>>,
1252}
1253
1254#[cfg(with_testing)]
1255impl TestExecutionRuntimeContext {
1256 pub fn new(chain_id: ChainId, execution_runtime_config: ExecutionRuntimeConfig) -> Self {
1257 Self {
1258 chain_id,
1259 thread_pool: Arc::new(ThreadPool::new(20)),
1260 execution_runtime_config,
1261 user_contracts: Arc::default(),
1262 user_services: Arc::default(),
1263 blobs: Arc::default(),
1264 events: Arc::default(),
1265 }
1266 }
1267}
1268
1269#[cfg(with_testing)]
1270#[cfg_attr(not(web), async_trait)]
1271#[cfg_attr(web, async_trait(?Send))]
1272impl ExecutionRuntimeContext for TestExecutionRuntimeContext {
1273 fn chain_id(&self) -> ChainId {
1274 self.chain_id
1275 }
1276
1277 fn thread_pool(&self) -> &Arc<ThreadPool> {
1278 &self.thread_pool
1279 }
1280
1281 fn execution_runtime_config(&self) -> ExecutionRuntimeConfig {
1282 self.execution_runtime_config
1283 }
1284
1285 fn user_contracts(&self) -> &Arc<papaya::HashMap<ApplicationId, UserContractCode>> {
1286 &self.user_contracts
1287 }
1288
1289 fn user_services(&self) -> &Arc<papaya::HashMap<ApplicationId, UserServiceCode>> {
1290 &self.user_services
1291 }
1292
1293 async fn get_user_contract(
1294 &self,
1295 description: &ApplicationDescription,
1296 _txn_tracker: &TransactionTracker,
1297 ) -> Result<UserContractCode, ExecutionError> {
1298 let application_id: ApplicationId = description.into();
1299 let pinned = self.user_contracts().pin();
1300 Ok(pinned
1301 .get(&application_id)
1302 .ok_or_else(|| {
1303 ExecutionError::ApplicationBytecodeNotFound(Box::new(description.clone()))
1304 })?
1305 .clone())
1306 }
1307
1308 async fn get_user_service(
1309 &self,
1310 description: &ApplicationDescription,
1311 _txn_tracker: &TransactionTracker,
1312 ) -> Result<UserServiceCode, ExecutionError> {
1313 let application_id: ApplicationId = description.into();
1314 let pinned = self.user_services().pin();
1315 Ok(pinned
1316 .get(&application_id)
1317 .ok_or_else(|| {
1318 ExecutionError::ApplicationBytecodeNotFound(Box::new(description.clone()))
1319 })?
1320 .clone())
1321 }
1322
1323 async fn get_blob(&self, blob_id: BlobId) -> Result<Option<Arc<Blob>>, ViewError> {
1324 Ok(self.blobs.pin().get(&blob_id).cloned().map(Arc::new))
1325 }
1326
1327 async fn get_event(&self, event_id: EventId) -> Result<Option<Arc<Vec<u8>>>, ViewError> {
1328 Ok(self.events.pin().get(&event_id).cloned().map(Arc::new))
1329 }
1330
1331 async fn get_network_description(&self) -> Result<Option<NetworkDescription>, ViewError> {
1332 let pinned = self.blobs.pin();
1333 let genesis_committee_blob_hash = pinned
1334 .iter()
1335 .find(|(_, blob)| blob.content().blob_type() == BlobType::Committee)
1336 .map_or_else(
1337 || CryptoHash::test_hash("genesis committee"),
1338 |(_, blob)| blob.id().hash,
1339 );
1340 Ok(Some(NetworkDescription {
1341 admin_chain_id: dummy_chain_description(0).id(),
1342 genesis_config_hash: CryptoHash::test_hash("genesis config"),
1343 genesis_timestamp: Timestamp::from(0),
1344 genesis_committee_blob_hash,
1345 name: "dummy network description".to_string(),
1346 }))
1347 }
1348
1349 async fn get_or_load_committee(
1350 &self,
1351 epoch: Epoch,
1352 ) -> Result<Option<Arc<Committee>>, ViewError> {
1353 let Some(net_description) = self.get_network_description().await? else {
1357 return Ok(None);
1358 };
1359 let blob_hash = if epoch.0 == 0 {
1360 net_description.genesis_committee_blob_hash
1361 } else {
1362 let event_id = EventId {
1363 chain_id: net_description.admin_chain_id,
1364 stream_id: StreamId::system(EPOCH_STREAM_NAME),
1365 index: epoch.0,
1366 };
1367 match self.get_event(event_id).await? {
1368 Some(bytes) => bcs::from_bytes(&bytes)?,
1369 None => return Ok(None),
1370 }
1371 };
1372 let blob_id = BlobId::new(blob_hash, BlobType::Committee);
1373 let Some(blob) = self.get_blob(blob_id).await? else {
1374 return Ok(None);
1375 };
1376 let committee: Committee = bcs::from_bytes(blob.bytes())?;
1377 Ok(Some(Arc::new(committee)))
1378 }
1379
1380 async fn contains_blob(&self, blob_id: BlobId) -> Result<bool, ViewError> {
1381 Ok(self.blobs.pin().contains_key(&blob_id))
1382 }
1383
1384 async fn contains_event(&self, event_id: EventId) -> Result<bool, ViewError> {
1385 Ok(self.events.pin().contains_key(&event_id))
1386 }
1387
1388 #[cfg(with_testing)]
1389 async fn add_blobs(
1390 &self,
1391 blobs: impl IntoIterator<Item = Blob> + Send,
1392 ) -> Result<(), ViewError> {
1393 let pinned = self.blobs.pin();
1394 for blob in blobs {
1395 pinned.insert(blob.id(), blob);
1396 }
1397
1398 Ok(())
1399 }
1400
1401 #[cfg(with_testing)]
1402 async fn add_events(
1403 &self,
1404 events: impl IntoIterator<Item = (EventId, Vec<u8>)> + Send,
1405 ) -> Result<(), ViewError> {
1406 let pinned = self.events.pin();
1407 for (event_id, bytes) in events {
1408 pinned.insert(event_id, bytes);
1409 }
1410
1411 Ok(())
1412 }
1413}
1414
1415impl From<SystemOperation> for Operation {
1416 fn from(operation: SystemOperation) -> Self {
1417 Operation::System(Box::new(operation))
1418 }
1419}
1420
1421impl Operation {
1422 pub fn system(operation: SystemOperation) -> Self {
1423 Operation::System(Box::new(operation))
1424 }
1425
1426 #[cfg(with_testing)]
1428 pub fn user<A: Abi>(
1429 application_id: ApplicationId<A>,
1430 operation: &A::Operation,
1431 ) -> Result<Self, bcs::Error> {
1432 Self::user_without_abi(application_id.forget_abi(), operation)
1433 }
1434
1435 #[cfg(with_testing)]
1438 pub fn user_without_abi(
1439 application_id: ApplicationId,
1440 operation: &impl Serialize,
1441 ) -> Result<Self, bcs::Error> {
1442 Ok(Operation::User {
1443 application_id,
1444 bytes: bcs::to_bytes(&operation)?,
1445 })
1446 }
1447
1448 pub fn as_system_operation(&self) -> Option<&SystemOperation> {
1451 match self {
1452 Operation::System(system_operation) => Some(system_operation),
1453 Operation::User { .. } => None,
1454 }
1455 }
1456
1457 pub fn application_id(&self) -> GenericApplicationId {
1458 match self {
1459 Self::System(_) => GenericApplicationId::System,
1460 Self::User { application_id, .. } => GenericApplicationId::User(*application_id),
1461 }
1462 }
1463
1464 pub fn published_blob_ids(&self) -> Vec<BlobId> {
1466 match self.as_system_operation() {
1467 Some(SystemOperation::PublishDataBlob { blob_hash }) => {
1468 vec![BlobId::new(*blob_hash, BlobType::Data)]
1469 }
1470 Some(SystemOperation::Admin(AdminOperation::PublishCommitteeBlob { blob_hash })) => {
1471 vec![BlobId::new(*blob_hash, BlobType::Committee)]
1472 }
1473 Some(SystemOperation::PublishModule { module_id }) => module_id.bytecode_blob_ids(),
1474 _ => vec![],
1475 }
1476 }
1477
1478 pub fn is_exempt_from_permissions(&self) -> bool {
1480 let Operation::System(system_op) = self else {
1481 return false;
1482 };
1483 matches!(
1484 **system_op,
1485 SystemOperation::ProcessNewEpoch(_)
1486 | SystemOperation::ProcessRemovedEpoch(_)
1487 | SystemOperation::UpdateStreams(_)
1488 )
1489 }
1490}
1491
1492impl From<SystemMessage> for Message {
1493 fn from(message: SystemMessage) -> Self {
1494 Message::System(message)
1495 }
1496}
1497
1498impl Message {
1499 pub fn system(message: SystemMessage) -> Self {
1500 Message::System(message)
1501 }
1502
1503 pub fn user<A, M: Serialize>(
1506 application_id: ApplicationId<A>,
1507 message: &M,
1508 ) -> Result<Self, bcs::Error> {
1509 let application_id = application_id.forget_abi();
1510 let bytes = bcs::to_bytes(&message)?;
1511 Ok(Message::User {
1512 application_id,
1513 bytes,
1514 })
1515 }
1516
1517 pub fn application_id(&self) -> GenericApplicationId {
1518 match self {
1519 Self::System(_) => GenericApplicationId::System,
1520 Self::User { application_id, .. } => GenericApplicationId::User(*application_id),
1521 }
1522 }
1523}
1524
1525impl From<SystemQuery> for Query {
1526 fn from(query: SystemQuery) -> Self {
1527 Query::System(query)
1528 }
1529}
1530
1531impl Query {
1532 pub fn system(query: SystemQuery) -> Self {
1533 Query::System(query)
1534 }
1535
1536 pub fn user<A: Abi>(
1538 application_id: ApplicationId<A>,
1539 query: &A::Query,
1540 ) -> Result<Self, serde_json::Error> {
1541 Self::user_without_abi(application_id.forget_abi(), query)
1542 }
1543
1544 pub fn user_without_abi(
1547 application_id: ApplicationId,
1548 query: &impl Serialize,
1549 ) -> Result<Self, serde_json::Error> {
1550 Ok(Query::User {
1551 application_id,
1552 bytes: serde_json::to_vec(&query)?,
1553 })
1554 }
1555
1556 pub fn application_id(&self) -> GenericApplicationId {
1557 match self {
1558 Self::System(_) => GenericApplicationId::System,
1559 Self::User { application_id, .. } => GenericApplicationId::User(*application_id),
1560 }
1561 }
1562}
1563
1564impl From<SystemResponse> for QueryResponse {
1565 fn from(response: SystemResponse) -> Self {
1566 QueryResponse::System(response)
1567 }
1568}
1569
1570impl From<Vec<u8>> for QueryResponse {
1571 fn from(response: Vec<u8>) -> Self {
1572 QueryResponse::User(response)
1573 }
1574}
1575
1576#[derive(Eq, PartialEq, Debug, Hash, Clone, Serialize, Deserialize)]
1578pub struct BlobState {
1579 pub last_used_by: Option<CryptoHash>,
1583 pub chain_id: ChainId,
1585 pub block_height: BlockHeight,
1587 pub epoch: Option<Epoch>,
1589}
1590
1591#[derive(Clone, Copy, Display)]
1593#[cfg_attr(with_wasm_runtime, derive(Debug, Default))]
1594pub enum WasmRuntime {
1595 #[cfg(with_wasmer)]
1596 #[default]
1597 #[display("wasmer")]
1598 Wasmer,
1599 #[cfg(with_wasmtime)]
1600 #[cfg_attr(not(with_wasmer), default)]
1601 #[display("wasmtime")]
1602 Wasmtime,
1603}
1604
1605#[derive(Clone, Copy, Display)]
1606#[cfg_attr(with_revm, derive(Debug, Default))]
1607pub enum EvmRuntime {
1608 #[cfg(with_revm)]
1609 #[default]
1610 #[display("revm")]
1611 Revm,
1612}
1613
1614pub trait WithWasmDefault {
1616 fn with_wasm_default(self) -> Self;
1617}
1618
1619impl WithWasmDefault for Option<WasmRuntime> {
1620 fn with_wasm_default(self) -> Self {
1621 #[cfg(with_wasm_runtime)]
1622 {
1623 Some(self.unwrap_or_default())
1624 }
1625 #[cfg(not(with_wasm_runtime))]
1626 {
1627 None
1628 }
1629 }
1630}
1631
1632impl FromStr for WasmRuntime {
1633 type Err = InvalidWasmRuntime;
1634
1635 fn from_str(string: &str) -> Result<Self, Self::Err> {
1636 match string {
1637 #[cfg(with_wasmer)]
1638 "wasmer" => Ok(WasmRuntime::Wasmer),
1639 #[cfg(with_wasmtime)]
1640 "wasmtime" => Ok(WasmRuntime::Wasmtime),
1641 unknown => Err(InvalidWasmRuntime(unknown.to_owned())),
1642 }
1643 }
1644}
1645
1646#[derive(Clone, Debug, Error)]
1648#[error("{0:?} is not a valid WebAssembly runtime")]
1649pub struct InvalidWasmRuntime(String);
1650
1651doc_scalar!(Operation, "An operation to be executed in a block");
1652doc_scalar!(
1653 Message,
1654 "A message to be sent and possibly executed in the receiver's block."
1655);
1656doc_scalar!(MessageKind, "The kind of outgoing message being sent");