Skip to content

Commit

Permalink
feat: improve scaffolding (#751)
Browse files Browse the repository at this point in the history
Improve the tari scaffolder
  • Loading branch information
stringhandler authored Nov 27, 2023
1 parent 896ce5a commit 720baef
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ function Connections() {
setShowAddPeerDialog(setElseToggle);
};

const onSubmitAddPeer = () => {
addPeer(formState.publicKey, [formState.address]);
const onSubmitAddPeer = async () => {
await addPeer(formState.publicKey, [formState.address]);
setFormState({ publicKey: '', address: '' });
setShowAddPeerDialog(false);
};
Expand Down
8 changes: 7 additions & 1 deletion applications/tari_scaffolder/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,16 @@ fn replace_tokens(in_file: &str, loaded_template: &LoadedTemplate, cli: &Cli) ->
let arr = globals.get_mut("commands").unwrap().as_array_mut().unwrap();
let mut args = vec![];
let mut is_method = false;
let mut requires_buckets = false;
for a in &f.arguments {
dbg!(a);
args.push(liquid::object!({
"name": a.name,
"arg_type": a.arg_type.to_string(),
}));
if &a.arg_type.to_string() == "Bucket" {
requires_buckets = true;
}
if &a.name == "self" {
is_method = true;
}
Expand All @@ -113,7 +117,9 @@ fn replace_tokens(in_file: &str, loaded_template: &LoadedTemplate, cli: &Cli) ->
"title": f.name.to_case(Case::UpperCamel),
"args" : args,
"is_method": is_method,
"is_mut": f.is_mut
"is_mut": f.is_mut,
"output": f.output.to_string(),
"requires_buckets": requires_buckets,
})));
}
},
Expand Down
8 changes: 4 additions & 4 deletions applications/tari_scaffolder/src/template/Cargo.toml.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ edition = "2021"

[dependencies]
{% if crates_root == "[crates]" %}
tari_wallet_daemon_client= "*"
tari_engine_types= "*"
tari_template_lib= "*"
tari_transaction = "*"
tari_wallet_daemon_client = { git = "https://github.com/tari-project/tari-dan", branch = "development" }
tari_engine_types = { git = "https://github.com/tari-project/tari-dan", branch = "development" }
tari_template_lib = { git = "https://github.com/tari-project/tari-dan", branch = "development" }
tari_transaction = { git = "https://github.com/tari-project/tari-dan", branch = "development" }
{% else %}
tari_wallet_daemon_client={path="{{crates_root}}/clients/wallet_daemon_client"}
tari_engine_types={path="{{crates_root}}/dan_layer/engine_types"}
Expand Down
69 changes: 52 additions & 17 deletions applications/tari_scaffolder/src/template/src/cli.rs.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ pub(crate) struct Cli {
pub dry_run: bool,
#[clap(subcommand)]
pub command: Command,
#[clap(long, short='f', default_value="100")]
pub fees: u64
#[clap(long, short='f', default_value="1000")]
pub max_fee: u64,
#[clap(long, short = 'a', default_value = "TestAccount_0")]
pub default_account: String,
}

impl Cli {
Expand Down Expand Up @@ -72,13 +74,25 @@ pub(crate) mod {{ c.name }} {
use tari_engine_types::TemplateAddress;
use tari_template_lib::prelude::ComponentAddress;
use tari_transaction::SubstateRequirement;
use tari_template_lib::args;
use tari_template_lib::prelude::Amount;
use tari_template_lib::prelude::ResourceAddress;
use std::str::FromStr;




#[derive(Debug, Args, Clone)]
pub struct Command {
{% for arg in c.args %}
{% if arg.name != "self" %}
{% if arg.arg_type != "Bucket" %}
pub {{ arg.name}} : String,
{% else %}
pub {{ arg.name}}_amount : u64,
pub {{ arg.name}}_resource: String,
pub {{ arg.name}}_withdraw_from_component: String,
{% endif %}
{% else %}
pub component_address: String,
{% endif %}
Expand All @@ -94,19 +108,40 @@ use tari_transaction::SubstateRequirement;
// let template_address= ;
let method = "{{c.name}}".to_string();



client.submit_instruction(Instruction::CallMethod {
component_address: ComponentAddress::from_hex(&self.component_address).unwrap(),
method,
args: vec![
{% for arg in c.args %}
{% if arg.name != "self" %}
parse_arg(&self.{{ arg.name}}).unwrap(),
{% endif %}
{% endfor %}
]
}, dump_buckets, is_dry_run, fees, vec![format!("component_{}", self.component_address).parse().unwrap()]
let mut instructions = vec![];
{% if c.requires_buckets %}
{% for bucket_arg in c.args %}
{% if bucket_arg.arg_type == "Bucket" %}
instructions.push(Instruction::CallMethod {
component_address: ComponentAddress::from_hex(&self.{{bucket_arg.name}}_withdraw_from_component).unwrap(),
method: "withdraw".to_string(),
args: args![ResourceAddress::from_str(&self.{{ bucket_arg.name}}_resource).unwrap(), self.{{ bucket_arg.name}}_amount],
});
instructions.push(Instruction::PutLastInstructionOutputOnWorkspace {
key: b"bucket_{{bucket_arg.name}}".to_vec(),
});
{% endif %}
{% endfor %}
{% endif %}
instructions.push(
Instruction::CallMethod {
component_address: ComponentAddress::from_hex(&self.component_address).unwrap(),
method,
args: args![
{% for arg in c.args %}
{% if arg.name != "self" %}
{% if arg.arg_type != "Bucket" %}
parse_arg(&self.{{ arg.name}}).unwrap(),
{% else %}
Variable("bucket_{{arg.name}}"),
{% endif %}
{% endif %}
{% endfor %}
]
}
);

client.submit_instructions(instructions, dump_buckets, is_dry_run, fees, vec![format!("component_{}", self.component_address).parse().unwrap()]

).await;
println!("done");
Expand All @@ -115,7 +150,7 @@ use tari_transaction::SubstateRequirement;


{% else %}
pub async fn run(self, mut client: DaemonClient, template_address: TemplateAddress, fees: u64) {
pub async fn run(self, mut client: DaemonClient, template_address: TemplateAddress, dump_buckets: bool, fees: u64) {

// let template_address= ;
let function = "{{c.name}}".to_string();
Expand All @@ -132,7 +167,7 @@ use tari_transaction::SubstateRequirement;
{% endif %}
{% endfor %}
]
}, false, false, fees, vec![]
}, dump_buckets, false, fees, vec![]

).await;
println!("done");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,16 @@ pub struct DaemonClient {
endpoint: String,
auth_token: Option<String>,
last_id: usize,
default_account: String
}

impl DaemonClient {
pub(crate) fn new(endpoint: String, auth_token: Option<String>) -> Self {
pub(crate) fn new(endpoint: String, auth_token: Option<String>, default_account: String) -> Self {
Self {
endpoint,
auth_token,
last_id: 0,
default_account
}
}

Expand All @@ -49,26 +51,29 @@ impl DaemonClient {
self.submit_instructions(vec![instruction], dump_buckets, is_dry_run, fees, other_inputs).await;
}

pub async fn submit_instructions(&mut self, instruction: Vec<Instruction>, dump_buckets: bool, is_dry_run: bool, fees: u64, other_inputs: Vec<SubstateRequirement>) {
pub async fn submit_instructions(&mut self, instructions: Vec<Instruction>, dump_buckets: bool, is_dry_run: bool, max_fee: u64, other_inputs: Vec<SubstateRequirement>) {
let mut client =
WalletDaemonClient::connect(&self.endpoint, self.auth_token.clone()).unwrap();
//let r = client.list_keys().await;

//dbg!(r);

let tx = CallInstructionRequest {
instruction,
fee_account: ComponentAddressOrName::Name("TestAccount_0".to_string()),
instructions,
fee_account: ComponentAddressOrName::Name(self.default_account.clone()),
dump_outputs_into: if dump_buckets {
Some(ComponentAddressOrName::Name("TestAccount_0".to_string()))
Some(ComponentAddressOrName::Name(self.default_account.clone()))
} else {
None
},
fee: fees,
max_fee,
inputs: other_inputs,
override_inputs: None,
is_dry_run,
proof_ids: vec![],
new_outputs: None,
min_epoch: None,
max_epoch: None,
};

let r2 = client.submit_instruction(tx).await.unwrap();
Expand All @@ -78,7 +83,7 @@ impl DaemonClient {



//"dump_outputs_into": "TestAccount_0",
//"dump_outputs_into": self.default_account,

}

Expand Down
8 changes: 4 additions & 4 deletions applications/tari_scaffolder/src/template/src/main.rs.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ use tari_utilities::hex::from_hex;
async fn main() {
let cli = Cli::init();
let jrpc = cli.daemon_jrpc_endpoint.clone().unwrap_or_else(|| "http://127.0.0.1:18016".to_string());
let token = cli.auth_token.as_ref().map(|a| a.to_string()).or(fs::read_to_string("token.data").ok());
let token = cli.auth_token.as_ref().map(|a| a.to_string()).or(fs::read_to_string("token.data").ok());

let client= DaemonClient::new(jrpc, token);
let client= DaemonClient::new(jrpc, token, cli.default_account.clone());
let template_address = from_hex(&cli.template).unwrap().try_into().unwrap();
match cli.command {
Command::Login(com) => {
Expand All @@ -29,9 +29,9 @@ let token = cli.auth_token.as_ref().map(|a| a.to_string()).or(fs::read_to_string
{% for c in commands %}
Command::{{c.title}}(com) => {
{% if c.is_method %}
com.run(client, cli.dump_buckets, cli.dry_run, cli.fees).await;
com.run(client, cli.dump_buckets, cli.dry_run, cli.max_fee).await;
{% else %}
com.run(client, template_address, cli.fees).await;
com.run(client, template_address, cli.dump_buckets, cli.max_fee).await;
{% endif %}
}
{% endfor %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ function Connections() {
setShowAddPeerDialog(setElseToggle);
};

const onSubmitAddPeer = () => {
addPeer(formState.publicKey, [formState.address]);
const onSubmitAddPeer = async () => {
await addPeer(formState.publicKey, [formState.address]);
setFormState({ publicKey: '', address: '' });
setShowAddPeerDialog(false);
};
Expand Down
3 changes: 3 additions & 0 deletions dan_layer/template_lib/src/models/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ impl FromStr for Metadata {
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
if !s.contains('=') {
return Err("Invalid metadata string, missing '='".to_string());
}
let pairs = s.split(',').map(|pair| {
let mut split = pair.split('=');
let key = split.next().ok_or_else(|| "Missing key".to_string())?;
Expand Down
4 changes: 4 additions & 0 deletions dan_layer/transaction/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,10 @@ impl TransactionBuilder {
self
}

pub fn build_as_instructions(mut self) -> Vec<Instruction> {
self.instructions.drain(..).collect()
}

pub fn build(mut self) -> Transaction {
Transaction::new(
self.fee_instructions.drain(..).collect(),
Expand Down

0 comments on commit 720baef

Please sign in to comment.