Skip to content

Commit

Permalink
feat(template_lib): builtin template addresses (#881)
Browse files Browse the repository at this point in the history
Description
---
* `template_lib` exports an enum `BuiltinTemplate` that enumerates all
the builtin templates and allows to retrieve the addresses via a new
`BuiltinTemplateInvoke` engine operation
* The engine implements the `EngineOp::BuiltinTemplateInvoke` by
accessing the appropriate constants in the `template_builtin` crate

Motivation and Context
---
Template developers will want to perform cross-template calls with
builtin templates (e.g. accounts). For convenience we want to expose the
corresponding template addresses in the `template_lib` crate.

There are two main ways of doing this:

1. Export the template addresses directly as constants
2. Create a new engine call for getting the template address

This PR follows (2) for template WASM size optimisation reasons, as (1)
would require to include the full address (32 bytes for each one of the
builtin templates, and we may have more of them in the future) in every
template WASM.

How Has This Been Tested?
---
New engine unit test for builtin template addresses

What process can a PR reviewer use to test or verify this change?
---
Use the new `BuiltinTemplate` enum in a template

Breaking Changes
---

- [x] None
- [ ] Requires data directory to be deleted
- [ ] Other - Please specify
  • Loading branch information
mrnaveira authored Jan 8, 2024
1 parent 5bcc900 commit 7e47cce
Show file tree
Hide file tree
Showing 13 changed files with 160 additions and 2 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions dan_layer/engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ tari_crypto = { workspace = true, features = ["borsh"] }
tari_dan_common_types = { workspace = true }
tari_engine_types = { workspace = true }
tari_template_abi = { workspace = true, features = ["std"] }
tari_template_builtin = { workspace = true }
tari_template_lib = { workspace = true }
tari_utilities = { workspace = true }
tari_transaction = { workspace = true }
Expand Down
16 changes: 16 additions & 0 deletions dan_layer/engine/src/runtime/impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,12 @@ use tari_engine_types::{
TemplateAddress,
};
use tari_template_abi::TemplateDef;
use tari_template_builtin::{ACCOUNT_NFT_TEMPLATE_ADDRESS, ACCOUNT_TEMPLATE_ADDRESS};
use tari_template_lib::{
args::{
BucketAction,
BucketRef,
BuiltinTemplateAction,
CallAction,
CallFunctionArg,
CallMethodArg,
Expand Down Expand Up @@ -82,6 +84,7 @@ use tari_template_lib::{
crypto::RistrettoPublicKeyBytes,
models::{Amount, BucketId, ComponentAddress, Metadata, NonFungibleAddress, NotAuthorized, VaultRef},
prelude::ResourceType,
template::BuiltinTemplate,
};

use super::{tracker::FinalizeData, Runtime};
Expand Down Expand Up @@ -1694,6 +1697,19 @@ impl<TTemplateProvider: TemplateProvider<Template = LoadedTemplate>> RuntimeInte
self.tracker.pop_call_frame()?;
Ok(())
}

fn builtin_template_invoke(&self, action: BuiltinTemplateAction) -> Result<InvokeResult, RuntimeError> {
self.invoke_modules_on_runtime_call("builtin_template_invoke")?;

let address = match action {
BuiltinTemplateAction::GetTemplateAddress { bultin } => match bultin {
BuiltinTemplate::Account => *ACCOUNT_TEMPLATE_ADDRESS,
BuiltinTemplate::AccountNft => *ACCOUNT_NFT_TEMPLATE_ADDRESS,
},
};

Ok(InvokeResult::encode(&address)?)
}
}

fn validate_component_access_rule_methods(
Expand Down
3 changes: 3 additions & 0 deletions dan_layer/engine/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ use tari_template_lib::{
Arg,
BucketAction,
BucketRef,
BuiltinTemplateAction,
CallAction,
CallerContextAction,
ComponentAction,
Expand Down Expand Up @@ -170,6 +171,8 @@ pub trait RuntimeInterface: Send + Sync {

fn call_invoke(&self, action: CallAction, args: EngineArgs) -> Result<InvokeResult, RuntimeError>;

fn builtin_template_invoke(&self, action: BuiltinTemplateAction) -> Result<InvokeResult, RuntimeError>;

fn check_component_access_rules(&self, method: &str, locked: &LockedSubstate) -> Result<(), RuntimeError>;

fn validate_return_value(&self, value: &IndexedValue) -> Result<(), RuntimeError>;
Expand Down
4 changes: 4 additions & 0 deletions dan_layer/engine/src/wasm/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use tari_template_abi::{CallInfo, EngineOp, FunctionDef};
use tari_template_lib::{
args::{
BucketInvokeArg,
BuiltinTemplateInvokeArg,
CallInvokeArg,
CallerContextInvokeArg,
ComponentInvokeArg,
Expand Down Expand Up @@ -165,6 +166,9 @@ impl WasmProcess {
.interface()
.proof_invoke(arg.proof_ref, arg.action, arg.args.into())
}),
EngineOp::BuiltinTemplateInvoke => Self::handle(env, arg, |env, arg: BuiltinTemplateInvokeArg| {
env.state().interface().builtin_template_invoke(arg.action)
}),
};

result.unwrap_or_else(|err| {
Expand Down
13 changes: 13 additions & 0 deletions dan_layer/engine/tests/templates/builtin_templates/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[workspace]
[package]
name = "builtin_templates"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
tari_template_lib = { path = "../../../../template_lib" }

[lib]
crate-type = ["cdylib", "lib"]
40 changes: 40 additions & 0 deletions dan_layer/engine/tests/templates/builtin_templates/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Copyright 2024. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use tari_template_lib::prelude::*;

#[template]
mod builtin_templates {
use super::*;

pub struct BuiltinTest {}

impl BuiltinTest {
pub fn get_account_template_address() -> TemplateAddress {
BuiltinTemplate::Account.address()
}

pub fn get_account_nft_template_address() -> TemplateAddress {
BuiltinTemplate::AccountNft.address()
}
}
}
14 changes: 14 additions & 0 deletions dan_layer/engine/tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ use tari_engine_types::{
virtual_substate::{VirtualSubstate, VirtualSubstateAddress},
TemplateAddress,
};
use tari_template_builtin::{ACCOUNT_NFT_TEMPLATE_ADDRESS, ACCOUNT_TEMPLATE_ADDRESS};
use tari_template_lib::{
args,
crypto::RistrettoPublicKeyBytes,
Expand Down Expand Up @@ -1328,3 +1329,16 @@ mod free_test_coins {
);
}
}

#[test]
fn test_builtin_templates() {
let mut template_test = TemplateTest::new(vec!["tests/templates/builtin_templates"]);

let account_template_address: TemplateAddress =
template_test.call_function("BuiltinTest", "get_account_template_address", args![], vec![]);
assert_eq!(account_template_address, *ACCOUNT_TEMPLATE_ADDRESS);

let account_nft_template_address: TemplateAddress =
template_test.call_function("BuiltinTest", "get_account_nft_template_address", args![], vec![]);
assert_eq!(account_nft_template_address, *ACCOUNT_NFT_TEMPLATE_ADDRESS);
}
2 changes: 2 additions & 0 deletions dan_layer/template_abi/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub enum EngineOp {
EmitEvent = 0x0B,
CallInvoke = 0x0C,
ProofInvoke = 0x0D,
BuiltinTemplateInvoke = 0x0E,
}

impl EngineOp {
Expand All @@ -58,6 +59,7 @@ impl EngineOp {
0x0B => Some(EngineOp::EmitEvent),
0x0C => Some(EngineOp::CallInvoke),
0x0D => Some(EngineOp::ProofInvoke),
0x0E => Some(EngineOp::BuiltinTemplateInvoke),
_ => None,
}
}
Expand Down
15 changes: 15 additions & 0 deletions dan_layer/template_lib/src/args/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ use crate::{
},
prelude::{ComponentAccessRules, ConfidentialOutputProof, TemplateAddress},
resource::ResourceType,
template::BuiltinTemplate,
Hash,
};

Expand Down Expand Up @@ -587,3 +588,17 @@ pub struct VaultCreateProofByNonFungiblesArg {
pub struct CreateProofOfResourceByConfidentialArg {
// pub proof: ConfidentialProofOfKnowledge
}

// -------------------------------- BuiltinTemplate -------------------------------- //

/// A template builtin operation argument
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BuiltinTemplateInvokeArg {
pub action: BuiltinTemplateAction,
}

/// The possible actions that can be performed related to builtin templates
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BuiltinTemplateAction {
GetTemplateAddress { bultin: BuiltinTemplate },
}
2 changes: 1 addition & 1 deletion dan_layer/template_lib/src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,5 +60,5 @@ pub use crate::{
},
rand,
resource::{ResourceBuilder, ResourceManager, ResourceType},
template::TemplateManager,
template::{BuiltinTemplate, TemplateManager},
};
46 changes: 46 additions & 0 deletions dan_layer/template_lib/src/template/builtin.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright 2024. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use serde::{Deserialize, Serialize};
use tari_template_abi::{call_engine, EngineOp};

use crate::{
args::{BuiltinTemplateAction, BuiltinTemplateInvokeArg, InvokeResult},
prelude::TemplateAddress,
};

/// All the templates that are included by default in the Tari network
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BuiltinTemplate {
Account,
AccountNft,
}

impl BuiltinTemplate {
pub fn address(self) -> TemplateAddress {
let resp: InvokeResult = call_engine(EngineOp::BuiltinTemplateInvoke, &BuiltinTemplateInvokeArg {
action: BuiltinTemplateAction::GetTemplateAddress { bultin: self },
});

resp.decode().expect("Failed to decode TemplateAddress")
}
}
5 changes: 4 additions & 1 deletion dan_layer/template_lib/src/template/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

//! Utilities to allow a template to call functions from other templates (i.e., composability)
//! Utilities related to templates
mod builtin;
pub use builtin::BuiltinTemplate;

mod manager;
pub use manager::TemplateManager;

0 comments on commit 7e47cce

Please sign in to comment.