Skip to content

Commit

Permalink
fix: big contracts types
Browse files Browse the repository at this point in the history
  • Loading branch information
MartianGreed committed Oct 11, 2024
1 parent 20713d4 commit 4af6821
Show file tree
Hide file tree
Showing 5 changed files with 259 additions and 35 deletions.
24 changes: 21 additions & 3 deletions crates/dojo-bindgen/src/plugins/typescript/generator/enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ use crate::{error::BindgenResult, plugins::BindgenModelGenerator};
pub(crate) struct TsEnumGenerator;

impl BindgenModelGenerator for TsEnumGenerator {
fn generate(&self, token: &Composite, _buffer: &mut Vec<String>) -> BindgenResult<String> {
fn generate(&self, token: &Composite, buffer: &mut Vec<String>) -> BindgenResult<String> {
if token.r#type != CompositeType::Enum || token.inners.is_empty() {
return Ok(String::new());
}

Ok(format!(
let gen = format!(
"// Type definition for `{path}` enum
export enum {name} {{
{variants}
Expand All @@ -24,7 +24,13 @@ export enum {name} {{
.map(|inner| format!("\t{},", inner.name))
.collect::<Vec<String>>()
.join("\n")
))
);

if buffer.iter().any(|b| b.contains(&gen)) {
return Ok(String::new());
}

Ok(gen)
}
}

Expand Down Expand Up @@ -78,6 +84,18 @@ mod tests {
assert_eq!(result, "// Type definition for `core::test::AvailableTheme` enum\nexport enum AvailableTheme {\n\tLight,\n\tDark,\n\tDojo,\n}\n");
}

#[test]
fn test_it_does_not_duplicates_enum() {
let mut buff: Vec<String> = Vec::new();
let writer = TsEnumGenerator;
buff.push("// Type definition for `core::test::AvailableTheme` enum\nexport enum AvailableTheme {\n\tLight,\n\tDark,\n\tDojo,\n}\n".to_owned());

let token_dup = create_available_theme_enum_token();
let result = writer.generate(&token_dup, &mut buff).unwrap();
assert_eq!(buff.len(), 1);
assert!(result.is_empty())
}

fn create_available_theme_enum_token() -> Composite {
Composite {
type_path: "core::test::AvailableTheme".to_owned(),
Expand Down
63 changes: 47 additions & 16 deletions crates/dojo-bindgen/src/plugins/typescript/generator/function.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use cainome::parser::tokens::Function;
use cainome::parser::tokens::{CompositeType, Function, Token};
use convert_case::{Case, Casing};
use dojo_world::contracts::naming;

Expand All @@ -16,12 +16,8 @@ impl TsFunctionGenerator {
}
}

fn setup_function_wrapper_start(
&self,
contract: &DojoContract,
buffer: &mut Vec<String>,
) -> usize {
let fn_wrapper = format!("export async function setupWorld(provider: DojoProvider) {{\n\tconst contractName = \"{}\";\n", naming::get_name_from_tag(&contract.tag));
fn setup_function_wrapper_start(&self, buffer: &mut Vec<String>) -> usize {
let fn_wrapper = format!("export async function setupWorld(provider: DojoProvider) {{\n");

if !buffer.iter().any(|b| b.contains(&fn_wrapper)) {
buffer.push(fn_wrapper.clone());
Expand All @@ -30,14 +26,14 @@ impl TsFunctionGenerator {
buffer.iter().position(|b| b.contains(&fn_wrapper)).unwrap()
}

fn generate_system_function(&self, token: &Function) -> String {
fn generate_system_function(&self, contract_name: &str, token: &Function) -> String {
format!(
"\tconst {} = async ({}) => {{
\t\ttry {{
\t\t\treturn await provider.execute(\n
\t\t\t\taccount,
\t\t\t\t{{
\t\t\t\t\tcontractName,
\t\t\t\t\tcontractName: \"{contract_name}\",
\t\t\t\t\tentryPoint: \"{}\",
\t\t\t\t\tcalldata: [{}],
\t\t\t\t}}
Expand All @@ -59,7 +55,22 @@ impl TsFunctionGenerator {
.inputs
.iter()
.fold(inputs, |mut acc, input| {
acc.push(format!("{}: {}", input.0, JsType::from(input.1.type_name().as_str())));
let prefix = match &input.1 {
Token::Composite(t) => {
if t.r#type == CompositeType::Enum {
"models."
} else {
""
}
}
_ => "",
};
acc.push(format!(
"{}: {}{}",
input.0.to_case(Case::Camel),
prefix,
JsType::from(&input.1)
));
acc
})
.join(", ")
Expand All @@ -70,7 +81,7 @@ impl TsFunctionGenerator {
.inputs
.iter()
.fold(Vec::new(), |mut acc, input| {
acc.push(format!("{}", input.0));
acc.push(input.0.to_case(Case::Camel));
acc
})
.join(", ")
Expand Down Expand Up @@ -108,8 +119,12 @@ impl BindgenContractGenerator for TsFunctionGenerator {
buffer: &mut Vec<String>,
) -> BindgenResult<String> {
self.check_imports(buffer);
let idx = self.setup_function_wrapper_start(contract, buffer);
self.append_function_body(idx, buffer, self.generate_system_function(token));
let idx = self.setup_function_wrapper_start(buffer);
self.append_function_body(
idx,
buffer,
self.generate_system_function(naming::get_name_from_tag(&contract.tag).as_str(), token),
);
self.setup_function_wrapper_end(token, buffer);
Ok(String::new())
}
Expand All @@ -121,6 +136,7 @@ mod tests {
tokens::{CoreBasic, Function, Token},
TokenizedAbi,
};
use dojo_world::contracts::naming;

use super::TsFunctionGenerator;
use crate::{plugins::BindgenContractGenerator, DojoContract};
Expand All @@ -141,7 +157,7 @@ mod tests {
fn test_setup_function_wrapper_start() {
let generator = TsFunctionGenerator {};
let mut buff: Vec<String> = Vec::new();
let idx = generator.setup_function_wrapper_start(&create_dojo_contract(), &mut buff);
let idx = generator.setup_function_wrapper_start(&mut buff);

assert_eq!(buff.len(), 1);
assert_eq!(idx, 0);
Expand All @@ -156,7 +172,7 @@ mod tests {
\t\t\treturn await provider.execute(\n
\t\t\t\taccount,
\t\t\t\t{
\t\t\t\t\tcontractName,
\t\t\t\t\tcontractName: \"actions\",
\t\t\t\t\tentryPoint: \"change_theme\",
\t\t\t\t\tcalldata: [value],
\t\t\t\t}
Expand All @@ -166,7 +182,14 @@ mod tests {
\t\t}
\t};\n";

assert_eq!(expected, generator.generate_system_function(&function))
let contract = create_dojo_contract();
assert_eq!(
expected,
generator.generate_system_function(
naming::get_name_from_tag(&contract.tag).as_str(),
&function
)
)
}

#[test]
Expand All @@ -177,6 +200,14 @@ mod tests {
assert_eq!(expected, generator.format_function_inputs(&function))
}

#[test]
fn test_format_function_inputs_complex() {
let generator = TsFunctionGenerator {};
let function = create_change_theme_function();
let expected = "account: Account, value: number";
assert_eq!(expected, generator.format_function_inputs(&function))
}

#[test]
fn test_format_function_calldata() {
let generator = TsFunctionGenerator {};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,7 @@ export interface {name} {{
fields = token
.inners
.iter()
.map(|inner| format!(
"\t{}: {};",
inner.name,
JsType::from(inner.token.type_name().as_str()).0
))
.map(|inner| { format!("\t{}: {};", inner.name, JsType::from(&inner.token)) })
.collect::<Vec<String>>()
.join("\n")
))
Expand Down
Loading

0 comments on commit 4af6821

Please sign in to comment.