Skip to content

Commit

Permalink
feat!: publish templates + update transaction model + global publish …
Browse files Browse the repository at this point in the history
…template
  • Loading branch information
sdbondi committed Dec 26, 2024
1 parent cb9ccdd commit 96571e7
Show file tree
Hide file tree
Showing 78 changed files with 1,046 additions and 612 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

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

Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@ where TTemplateProvider: TemplateProvider<Template = LoadedTemplate>
let initial_ownership_proofs = transaction
.signatures()
.iter()
.map(|sig| public_key_to_fungible_address(sig.public_key()))
.map(|p| p.public_key())
.chain(Some(transaction.seal_signature().public_key()).filter(|_| transaction.is_seal_signer_authorized()))
.map(public_key_to_fungible_address)
.collect();
let auth_params = AuthParams {
initial_ownership_proofs,
Expand Down
7 changes: 3 additions & 4 deletions applications/tari_dan_wallet_cli/src/command/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,7 @@ async fn handle_submit_manifest(
component_address: fee_account.address.as_component_address().unwrap(),
method: "pay_fee".to_string(),
args: args![Amount::try_from(common.max_fee.unwrap_or(1000))?],
}])
.collect(),
}]),
)
.with_instructions(instructions.instructions)
.with_inputs(common.inputs)
Expand Down Expand Up @@ -472,12 +471,12 @@ fn summarize_transaction(transaction: &UnsignedTransaction) {
}
println!();
println!("🌟 Submitting fee instructions:");
for instruction in &transaction.fee_instructions {
for instruction in transaction.fee_instructions() {
println!("- {}", instruction);
}
println!();
println!("🌟 Submitting instructions:");
for instruction in &transaction.instructions {
for instruction in transaction.instructions() {
println!("- {}", instruction);
}
println!();
Expand Down
15 changes: 11 additions & 4 deletions applications/tari_dan_wallet_daemon/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,12 @@ fn exit_on_ci() {
}

const BUILD: &[(&str, &[&str])] = &[
("../../bindings", &["ci"]),
("../../bindings", &["install", "--omit=dev"]),
("../../bindings", &["run", "tsc"]),
("../../clients/javascript/wallet_daemon_client", &["ci"]),
("../../clients/javascript/wallet_daemon_client", &[
"install",
"--omit=dev",
]),
("../../clients/javascript/wallet_daemon_client", &["run", "build"]),
("../tari_dan_wallet_web_ui", &["run", "build"]),
];
Expand All @@ -48,8 +51,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let npm = if cfg!(windows) { "npm.cmd" } else { "npm" };

for (target, args) in BUILD {
if let Err(error) = Command::new(npm).arg("ci").current_dir(target).status() {
println!("cargo:warning='npm ci' error : {:?}", error);
if let Err(error) = Command::new(npm)
.args(["install", "--omit=dev"])
.current_dir(target)
.status()
{
println!("cargo:warning='npm install' error : {:?}", error);
exit_on_ci();
break;
}
Expand Down
14 changes: 5 additions & 9 deletions applications/tari_dan_wallet_daemon/src/handlers/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,7 @@ pub async fn handle_create(
.fee_transaction_pay_from_component(default_account.address.as_component_address().unwrap(), max_fee)
.create_account(owner_pk.clone())
.with_inputs(inputs)
.sign(&signing_key.key)
.build();
.build_and_seal(&signing_key.key);

let mut events = context.notifier().subscribe();
let tx_id = context
Expand Down Expand Up @@ -227,8 +226,7 @@ pub async fn handle_invoke(
.fee_transaction_pay_from_component(account_address, req.max_fee.unwrap_or(DEFAULT_FEE))
.call_method(account_address, &req.method, req.args)
.with_inputs(inputs)
.sign(&signing_key.key)
.build();
.build_and_seal(&signing_key.key);

let mut events = context.notifier().subscribe();
let tx_id = context
Expand Down Expand Up @@ -433,7 +431,7 @@ pub async fn handle_reveal_funds(
.into_iter()
.map(|addr| SubstateRequirement::new(addr.substate_id.clone(), Some(addr.version)));

let transaction = builder.with_inputs(inputs).sign(&account_key.key).build();
let transaction = builder.with_inputs(inputs).build_and_seal(&account_key.key);

sdk.confidential_outputs_api()
.proofs_set_transaction_hash(proof_id, *transaction.id())?;
Expand Down Expand Up @@ -698,8 +696,7 @@ async fn finish_claiming<T: WalletStore>(
let transaction = Transaction::builder()
.with_fee_instructions(instructions)
.with_inputs(inputs)
.sign(&account_secret_key.key)
.build();
.build_and_seal(&account_secret_key.key);
let is_first_account = accounts_api.count()? == 0;
let mut events = context.notifier().subscribe();
let tx_id = context
Expand Down Expand Up @@ -948,8 +945,7 @@ pub async fn handle_transfer(
.with_fee_instructions(fee_instructions)
.with_instructions(instructions)
.with_inputs(vec![resource_substate_address])
.sign(&account_secret_key.key)
.build();
.build_and_seal(&account_secret_key.key);

let required_inputs = inputs.into_iter().map(Into::into).collect();
// If dry run we can return the result immediately
Expand Down
6 changes: 2 additions & 4 deletions applications/tari_dan_wallet_daemon/src/handlers/nfts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,7 @@ async fn mint_account_nft(
let transaction = Transaction::builder()
.fee_transaction_pay_from_component(account.address.as_component_address().unwrap(), fee)
.with_instructions(instructions)
.sign(owner_sk)
.build();
.build_and_seal(owner_sk);

let mut events = context.notifier().subscribe();
let tx_id = context
Expand Down Expand Up @@ -254,8 +253,7 @@ async fn create_account_nft(
.fee_transaction_pay_from_component(account.address.as_component_address().unwrap(), fee)
.call_function(ACCOUNT_NFT_TEMPLATE_ADDRESS, "create", args![owner_token,])
.with_inputs(inputs)
.sign(owner_sk)
.build();
.build_and_seal(owner_sk);

let tx_id = sdk
.transaction_api()
Expand Down
104 changes: 64 additions & 40 deletions applications/tari_dan_wallet_daemon/src/handlers/transaction.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
// Copyright 2023 The Tari Project
// SPDX-License-Identifier: BSD-3-Clause
use std::{collections::HashSet, time::Duration};
use std::time::Duration;

use anyhow::anyhow;
use axum_jrpc::error::{JsonRpcError, JsonRpcErrorReason};
use futures::{future, future::Either};
use log::*;
use tari_dan_app_utilities::json_encoding;
use tari_dan_common_types::{optional::Optional, Epoch, SubstateRequirement};
use tari_dan_wallet_sdk::apis::{jwt::JrpcPermission, key_manager};
use tari_engine_types::{indexed_value::IndexedValue, instruction::Instruction, substate::SubstateId};
use tari_template_lib::{args, args::Arg, models::Amount};
use tari_template_lib::{args, models::Amount};
use tari_transaction::Transaction;
use tari_wallet_daemon_client::types::{
AccountGetRequest,
AccountGetResponse,
CallInstructionRequest,
PublishTemplateRequest,
PublishTemplateResponse,
TransactionGetAllRequest,
TransactionGetAllResponse,
TransactionGetRequest,
Expand All @@ -31,7 +33,10 @@ use tari_wallet_daemon_client::types::{
use tokio::time;

use super::{accounts, context::HandlerContext};
use crate::{handlers::HandlerError, services::WalletEvent};
use crate::{
handlers::{helpers::get_account_or_default, HandlerError},
services::WalletEvent,
};

const LOG_TARGET: &str = "tari::dan::wallet_daemon::handlers::transaction";

Expand Down Expand Up @@ -100,8 +105,7 @@ pub async fn handle_submit(
let autofill_inputs = req.autofill_inputs;
let detected_inputs = if req.detect_inputs {
// If we are not overriding inputs, we will use inputs that we know about in the local substate id db
let mut substates = get_referenced_substate_addresses(&req.transaction.instructions)?;
substates.extend(get_referenced_substate_addresses(&req.transaction.fee_instructions)?);
let substates = req.transaction.to_referenced_substates()?;
let substates = substates.into_iter().collect::<Vec<_>>();
let loaded_substates = sdk.substate_api().locate_dependent_substates(&substates).await?;
loaded_substates
Expand Down Expand Up @@ -129,8 +133,7 @@ pub async fn handle_submit(
let transaction = Transaction::builder()
.with_unsigned_transaction(req.transaction)
.with_inputs(detected_inputs)
.sign(&key.key)
.build();
.build_and_seal(&key.key);

for input in transaction.inputs() {
debug!(target: LOG_TARGET, "Input: {}", input)
Expand Down Expand Up @@ -173,8 +176,7 @@ pub async fn handle_submit_dry_run(
let autofill_inputs = req.autofill_inputs;
let detected_inputs = if req.detect_inputs {
// If we are not overriding inputs, we will use inputs that we know about in the local substate id db
let mut substates = get_referenced_substate_addresses(&req.transaction.instructions)?;
substates.extend(get_referenced_substate_addresses(&req.transaction.fee_instructions)?);
let substates = req.transaction.to_referenced_substates()?;
let substates = substates.into_iter().collect::<Vec<_>>();
sdk.substate_api().locate_dependent_substates(&substates).await?
} else {
Expand All @@ -184,8 +186,7 @@ pub async fn handle_submit_dry_run(
let transaction = Transaction::builder()
.with_unsigned_transaction(req.transaction)
.with_inputs(detected_inputs)
.sign(&key.key)
.build();
.build_and_seal(&key.key);

for proof_id in req.proof_ids {
// update the proofs table with the corresponding transaction hash
Expand All @@ -200,7 +201,7 @@ pub async fn handle_submit_dry_run(
);
let exec_result = context
.transaction_service()
.submit_dry_run_transaction(transaction, autofill_inputs.clone())
.submit_dry_run_transaction(transaction, autofill_inputs)
.await?;

let json_result = json_encoding::encode_finalize_result_into_json(&exec_result.finalize)?;
Expand Down Expand Up @@ -371,33 +372,56 @@ pub async fn handle_wait_result(
}
}

fn get_referenced_substate_addresses(instructions: &[Instruction]) -> anyhow::Result<HashSet<SubstateId>> {
let mut substates = HashSet::new();
for instruction in instructions {
match instruction {
Instruction::CallMethod {
component_address,
args,
..
} => {
substates.insert(SubstateId::Component(*component_address));
for arg in args {
if let Arg::Literal(bytes) = arg {
let val = IndexedValue::from_raw(bytes)?;
substates.extend(val.referenced_substates());
}
}
},
Instruction::CallFunction { args, .. } => {
for arg in args {
if let Arg::Literal(bytes) = arg {
let val = IndexedValue::from_raw(bytes)?;
substates.extend(val.referenced_substates());
}
}
},
_ => {},
pub async fn handle_publish_template(
context: &HandlerContext,
token: Option<String>,
req: PublishTemplateRequest,
) -> Result<PublishTemplateResponse, anyhow::Error> {
let sdk = context.wallet_sdk();

let fee_account = get_account_or_default(req.fee_account, &sdk.accounts_api())?;

let transaction = Transaction::builder()
.fee_transaction_pay_from_component(
fee_account.address.as_component_address().unwrap(),
req.max_fee.try_into()?,
)
.publish_template(req.binary)
.build_unsigned_transaction();

if req.dry_run {
let request = TransactionSubmitDryRunRequest {
transaction,
signing_key_index: Some(fee_account.key_index),
autofill_inputs: vec![],
detect_inputs: req.detect_inputs,
proof_ids: vec![],
};
let resp = handle_submit_dry_run(context, token, request).await?;
if let Some(reject) = resp.result.finalize.full_reject() {
return Err(JsonRpcError::new(
JsonRpcErrorReason::ApplicationError(5),
format!("Dry-run transaction rejected: {reject}"),
serde_json::Value::Null,
)
.into());
}
return Ok(PublishTemplateResponse {
transaction_id: resp.transaction_id,
dry_run_fee: Some(resp.result.finalize.fee_receipt.total_fees_charged()),
});
}
Ok(substates)
let request = TransactionSubmitRequest {
transaction,
signing_key_index: Some(fee_account.key_index),
autofill_inputs: vec![],
detect_inputs: req.detect_inputs,
detect_inputs_use_unversioned: true,
proof_ids: vec![],
};
let resp = handle_submit(context, token, request).await?;
Ok(PublishTemplateResponse {
transaction_id: resp.transaction_id,
dry_run_fee: None,
})
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,7 @@ pub async fn handle_claim_validator_fees(

let transaction = Transaction::builder()
.with_fee_instructions(fee_instructions)
.sign(&account_secret_key.key)
.build();
.build_and_seal(&account_secret_key.key);

// send the transaction
let required_inputs = inputs.into_iter().map(Into::into).collect();
Expand Down
5 changes: 4 additions & 1 deletion applications/tari_dan_wallet_daemon/src/jrpc_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::{net::SocketAddr, sync::Arc};

use axum::{
extract::Extension,
extract::{DefaultBodyLimit, Extension},
http::{Request, StatusCode},
middleware::Next,
response::Response,
Expand Down Expand Up @@ -73,6 +73,8 @@ pub fn spawn_listener(
.layer(Extension((preferred_address,signaling_server_address)))
.layer(Extension(Arc::new(shutdown_signal.clone())))
.layer(CorsLayer::permissive())
// Limit the body size to 5MB to allow for wasm uploads
.layer(DefaultBodyLimit::max(5*1024*1024))
.layer(axum::middleware::from_fn(extract_token));

let server = axum::Server::try_bind(&preferred_address)?;
Expand Down Expand Up @@ -124,6 +126,7 @@ async fn handler(
"submit_instruction" => call_handler(context, value, token, transaction::handle_submit_instruction).await,
"submit" => call_handler(context, value, token, transaction::handle_submit).await,
"submit_dry_run" => call_handler(context, value, token, transaction::handle_submit_dry_run).await,
"publish_template" => call_handler(context, value, token, transaction::handle_publish_template).await,
"get" => call_handler(context, value, token, transaction::handle_get).await,
"get_result" => call_handler(context, value, token, transaction::handle_get_result).await,
"wait_result" => call_handler(context, value, token, transaction::handle_wait_result).await,
Expand Down
Loading

0 comments on commit 96571e7

Please sign in to comment.