Skip to main content

TemplateTest

Struct TemplateTest 

Source
pub struct TemplateTest { /* private fields */ }
Expand description

Test harness for Tari Ootle templates.

Compiles WASM templates, manages an in-memory state store, and provides convenience methods for executing transactions, creating accounts, and inspecting results. Designed for use in #[test] functions within template crates.

§Quick start

use tari_template_test_tooling::TemplateTest;

let mut test = TemplateTest::my_crate();
let (account, proof, secret_key) = test.create_funded_account();

Implementations§

Source§

impl TemplateTest

Source

pub const FUNDED_ACCOUNT_INITIAL_BALANCE: u64 = 1_000_000_000

The initial balance of a funded account created by create_funded_account.

Source

pub fn my_crate() -> Self

Creates a new TemplateTest with the template in the current crate. This is useful for tests within a template crate.

Source

pub fn new<P: AsRef<Path>, I: IntoIterator<Item = T>, T: Into<TemplateSpec>>( base_path: P, template_paths: I, ) -> Self

Creates a new TemplateTest with templates relative to the given base path. All template_paths are resolved relative to the base path.

Source

pub fn new_cwd<I: IntoIterator<Item = T>, T: Into<TemplateSpec>>( template_paths: I, ) -> Self

Creates a new TemplateTest using the current working directory as the base path. Template paths are resolved relative to the CWD.

Source

pub fn new_builtin_only() -> Self

Creates a new TemplateTest with only the built-in templates (e.g. Account, faucets). No user templates are compiled or loaded.

Source

pub fn new_with_compile_envs<P, I, T, TEnvs, K, V>( base_path: P, template_paths: I, envs: TEnvs, ) -> Self
where P: AsRef<Path>, I: IntoIterator<Item = T>, T: Into<TemplateSpec>, TEnvs: IntoIterator<Item = (K, V)>, TEnvs::IntoIter: Clone, K: AsRef<OsStr>, V: AsRef<OsStr>,

Creates a new TemplateTest with additional environment variables set during WASM compilation. This is useful for templates that use env!() or conditional compilation based on environment variables.

Source

pub fn bootstrap_state(&mut self)

Initializes the in-memory state store with built-in resources and faucet state. This is called automatically by the constructors and typically does not need to be called manually.

Source

pub fn compile_new_template<T, P, TEnvs, K, V>( &mut self, name: T, path: P, features: &[&str], envs: TEnvs, ) -> TemplateAddress
where T: Into<String>, P: AsRef<Path>, TEnvs: IntoIterator<Item = (K, V)>, TEnvs::IntoIter: Clone, K: AsRef<OsStr>, V: AsRef<OsStr>,

Compiles and adds a new template to the test environment after initial construction. Returns the TemplateAddress assigned to the newly compiled template. The template is registered under the given name for later lookup via get_template_address.

Source

pub fn set_dry_run(&mut self, dry_run: bool) -> &mut Self

Executes subsequent transactions as a dry run: fees are metered but not settled, as the indexer’s fee estimation does.

Source

pub fn enable_fees(&mut self) -> &mut Self

Enables fee charging for subsequent transaction executions. By default, fees are disabled in tests.

Source

pub fn disable_fees(&mut self) -> &mut Self

Disables fee charging for subsequent transaction executions.

Source

pub fn enable_auto_add_proofs_from_signers(&mut self) -> &mut Self

Enables automatic proof generation from transaction signers. When enabled (the default), if the proofs argument is empty, proofs are automatically derived from the transaction’s signing keys.

Source

pub fn disable_auto_add_proofs_from_signers(&mut self) -> &mut Self

Disables automatic proof generation from transaction signers. When disabled, you must explicitly pass the required proofs to each execution call.

Source

pub fn fee_table(&self) -> &FeeTable

Returns a reference to the current fee table used when fees are enabled.

Source

pub fn set_fee_table(&mut self, fee_table: FeeTable) -> &mut Self

Replaces the fee table with the given one. Only has effect when fees are enabled.

Source

pub fn set_burn_rate_bps(&mut self, rate_bps: u16) -> &mut Self

Sets the exhaust burn rate applied to the transaction’s accrued fees. Defaults to zero, so tests see no burn unless they ask for one.

Source

pub fn set_virtual_substate( &mut self, address: VirtualSubstateId, value: VirtualSubstate, ) -> &mut Self

Sets a virtual substate (e.g. CurrentEpoch) that is available to transactions during execution.

Source

pub fn remove_virtual_substate( &mut self, address: VirtualSubstateId, ) -> &mut Self

Removes a virtual substate so that it is not available to transactions during execution.

This is useful for testing that templates handle missing virtual substates correctly (e.g. asserting that Consensus::current_epoch_hash() returns VirtualSubstateNotFound when the hash has not been injected).

Source

pub fn read_only_state_store(&self) -> ReadOnlyStateStore<'_>

Returns a read-only view of the current state store, useful for inspecting component state between transactions.

Source

pub fn get_state_store_mut(&mut self) -> &mut MemoryStateStore

Source

pub fn extract_component_value<T>( &self, component_address: ComponentAddress, path: &str, ) -> T
where T: DeserializeOwned + for<'b> Decode<'b, ()>,

Extracts and deserializes a value from a component’s state at the given JSON pointer path.

§Panics

Panics if the component does not exist, the path is invalid, or the value cannot be deserialized into T.

Source

pub fn default_signing_key(&self) -> &RistrettoSecretKey

Returns the default secret key used to sign transactions when no other key is specified.

Source

pub fn assert_calls(&self, expected: &[&'static str])

Asserts that the tracked cross-template calls match the given expected list exactly.

§Panics

Panics if the recorded calls do not match expected.

Source

pub fn clear_calls(&self)

Clears the tracked cross-template call log.

Source

pub fn get_previous_output_address(&self, ty: SubstateType) -> SubstateId

Returns a SubstateId from the outputs of the most recently committed transaction that matches the given SubstateType.

§Panics

Panics if no output of the given type was produced by the last transaction.

Source

pub fn get_module(&self, module_name: &str) -> LoadedWasmTemplate

Returns the compiled WASM module for the template registered under the given name.

§Panics

Panics if no template with the given name exists.

Source

pub fn get_template_address(&self, name: &str) -> TemplateAddress

Returns the TemplateAddress for the template registered under the given name.

§Panics

Panics if no template with the given name exists.

Source

pub fn create_account( &mut self, owner_public_key: RistrettoPublicKeyBytes, workspace_id: Option<BuilderWorkspaceKey>, proofs: Vec<NonFungibleAddress>, ) -> ComponentAddress

Creates a new account component owned by the given public key. Returns the ComponentAddress of the newly created account.

Optionally places the result on the workspace under workspace_id. Additional proofs are passed as initial ownership proofs for the transaction.

Source

pub fn call_function<T>( &mut self, template_name: &str, func_name: &str, args: Vec<NamedArg>, proofs: Vec<NonFungibleAddress>, ) -> T
where T: DeserializeOwned + for<'b> Decode<'b, ()>,

Calls a template function by name and returns the deserialized result.

This is a convenience method that builds a transaction with a single CallFunction instruction, executes it, and decodes the return value.

§Panics

Panics if the transaction fails or if the return value cannot be deserialized into T.

Source

pub fn call_method<T>( &mut self, component_address: ComponentAddress, method_name: &str, args: Vec<NamedArg>, proofs: Vec<NonFungibleAddress>, ) -> T
where T: DeserializeOwned + for<'b> Decode<'b, ()>,

Calls a method on an existing component and returns the deserialized result.

This is a convenience method that builds a transaction with a single CallMethod instruction, executes it, and decodes the return value.

§Panics

Panics if the transaction fails or if the return value cannot be deserialized into T.

Source

pub fn get_test_proof_and_secret_key( &self, ) -> (NonFungibleAddress, RistrettoSecretKey)

Returns the default owner proof (non-fungible address) and secret key pair. Useful for setting up ownership proofs in tests.

Source

pub fn owner_proof(&self) -> NonFungibleAddress

Returns the default owner proof derived from the test’s default public key.

Source

pub fn secret_key(&self) -> &RistrettoSecretKey

Returns a reference to the default secret key.

Source

pub fn public_key(&self) -> &RistrettoPublicKey

Returns a reference to the default public key.

Source

pub fn new_key_pair( &mut self, seed: u8, ) -> (RistrettoSecretKey, RistrettoPublicKey)

Generates a deterministic key pair from the given seed byte. Different seeds produce different key pairs, allowing tests to create multiple distinct identities.

Source

pub fn to_public_key_bytes(&self) -> RistrettoPublicKeyBytes

Returns the default public key as RistrettoPublicKeyBytes, the byte representation commonly used in template function arguments.

Source

pub fn create_empty_account( &mut self, ) -> (ComponentAddress, NonFungibleAddress, RistrettoSecretKey)

Creates a new account with zero balance and a fresh key pair. Returns (account_address, owner_proof, secret_key).

Fees are temporarily disabled for the account creation transaction.

Source

pub fn create_funded_account( &mut self, ) -> (ComponentAddress, NonFungibleAddress, RistrettoSecretKey)

Creates a new account funded with FUNDED_ACCOUNT_INITIAL_BALANCE tokens from the XTR faucet, using a fresh key pair. Returns (account_address, owner_proof, secret_key).

Fees are temporarily disabled for the account creation transaction.

Source

pub fn create_funded_account_with_keypair( &mut self, ) -> (ComponentAddress, NonFungibleAddress, RistrettoSecretKey, RistrettoPublicKey)

Creates a new account funded from the XTR faucet using a fresh key pair. Returns (account_address, owner_proof, secret_key, public_key).

Unlike [create_funded_account], this also returns the public key. Fees are temporarily disabled for the account creation transaction.

Source

pub fn create_owner_proof( &mut self, ) -> (NonFungibleAddress, RistrettoPublicKey, RistrettoSecretKey)

Creates a fresh owner proof by generating a new key pair with an auto-incrementing seed. Returns (owner_proof, public_key, secret_key).

Each call produces a different key pair, making this suitable for creating multiple distinct owners.

Source

pub fn try_execute_instructions( &mut self, fee_instructions: Vec<Instruction>, instructions: Vec<Instruction>, proofs: Vec<NonFungibleAddress>, ) -> Result<ExecuteResult, TransactionError>

Builds and executes a transaction from raw fee and main instruction vectors. Returns Ok(ExecuteResult) on successful execution, or a TransactionError if the transaction processor encounters a fatal error.

Unlike execute_expect_success, this does not panic on rejection and does not commit state changes.

Source

pub fn try_execute( &mut self, transaction: Transaction, proofs: Vec<NonFungibleAddress>, ) -> Result<ExecuteResult, TransactionError>

Executes a pre-built transaction without committing state changes. Returns Ok(ExecuteResult) on successful execution, or a TransactionError if the transaction processor encounters a fatal error.

This is the lowest-level execution method. It does not panic on transaction rejection and does not commit the resulting state diff. Use this when you need full control over result handling.

Source

pub fn execute_and_commit_on_success( &mut self, transaction: Transaction, proofs: Vec<NonFungibleAddress>, ) -> ExecuteResult

Executes a transaction and commits state changes only if the transaction is accepted. Does not panic on rejection — returns the result in all cases.

Source

pub fn transaction(&self) -> TransactionBuilder<MainIntent>

Returns a new TransactionBuilder configured for the local test network. Use this to construct custom transactions with multiple instructions.

The builder is valid for the epoch the harness is executing in, and carries a distinct nonce so that otherwise-identical transactions get distinct ids (see Self::transaction_seq).

Source

pub fn current_epoch(&self) -> Epoch

The epoch transactions execute in, as injected via Self::set_virtual_substate. Tests that remove the virtual substate entirely still have to build transactions, so those fall back to the genesis epoch.

Source

pub fn execute_expect_commit( &mut self, transaction: Transaction, proofs: Vec<NonFungibleAddress>, ) -> ExecuteResult

Executes a transaction. Panics if the transaction is not finalized (fee transaction fails). Does not panic if the main instructions fails (use execute_expect_success for that).

Source

pub fn build_and_execute( &mut self, builder: TransactionBuilder<MainIntent>, proofs: Vec<NonFungibleAddress>, ) -> ExecuteResult

Executes a transaction. Panics if the transaction fails.

Source

pub fn execute_expect_success( &mut self, transaction: Transaction, proofs: Vec<NonFungibleAddress>, ) -> ExecuteResult

Executes a transaction. Panics if the transaction fails.

Source

pub fn execute_expect_failure( &mut self, transaction: Transaction, proofs: Vec<NonFungibleAddress>, ) -> RejectReason

Executes a transaction. Panics if the transaction succeeds.

Source

pub fn execute_and_commit( &mut self, instructions: Vec<Instruction>, proofs: Vec<NonFungibleAddress>, ) -> Result<ExecuteResult>

Executes instructions (with no fee instructions) and commits the state diff on success. Returns an error if the transaction is rejected.

Source

pub fn execute_and_commit_with_fees( &mut self, fee_instructions: Vec<Instruction>, instructions: Vec<Instruction>, proofs: Vec<NonFungibleAddress>, ) -> Result<ExecuteResult>

Executes instructions with explicit fee instructions and commits the state diff on success. Returns an error if the fee transaction is rejected or the main transaction fails.

Source

pub fn execute_and_commit_manifest<'a, I: IntoIterator<Item = (&'a str, ManifestValue)>>( &mut self, manifest: &str, variables: I, proofs: Vec<NonFungibleAddress>, ) -> Result<ExecuteResult>

Parses and executes a transaction manifest string, automatically importing all registered templates. Template names are available as identifiers in the manifest without explicit use statements.

variables provides named values that can be referenced in the manifest (e.g. component addresses, amounts).

Returns an error if parsing fails, the transaction is rejected, or execution fails.

Source

pub fn print_state(&self)

Prints all substates in the current state store to stderr for debugging.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> ArchivePointee for T

Source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
Source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
Source§

impl<U> As for U

Source§

fn as_<T>(self) -> T
where T: CastFrom<U>, U: Sized,

Casts self to type T. The semantics of numeric casting with the as operator are followed, so <T as As>::as_::<U> can be used in the same way as T as U for numeric conversions. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, B> FromByteType<T> for B
where T: ConvertFromByteType<B>,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> LayoutRaw for T

Source§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Returns the layout of the type.
Source§

impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
where T: SharedNiching<N1, N2>, N1: Niching<T>, N2: Niching<T>,

Source§

unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool

Returns whether the given value has been niched. Read more
Source§

fn resolve_niched(out: Place<NichedOption<T, N1>>)

Writes data to out indicating that a T is niched.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The metadata type for pointers and references to this type.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more