-
Notifications
You must be signed in to change notification settings - Fork 194
/
Copy pathmod.rs
344 lines (300 loc) · 11.1 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use async_trait::async_trait;
use cainome::parser::tokens::{Composite, CompositeType, Function, Token};
use crate::error::BindgenResult;
use crate::plugins::BuiltinPlugin;
use crate::{DojoContract, DojoData, DojoModel};
pub struct UnityPlugin {}
impl UnityPlugin {
pub fn new() -> Self {
Self {}
}
// Maps cairo types to C#/Unity SDK defined types
fn map_type(type_name: &str) -> String {
match type_name {
"u8" => "byte".to_string(),
"u16" => "ushort".to_string(),
"u32" => "uint".to_string(),
"u64" => "ulong".to_string(),
"u128" => "BigInteger".to_string(),
"u256" => "BigInteger".to_string(),
"usize" => "uint".to_string(),
"felt252" => "FieldElement".to_string(),
"bytes31" => "string".to_string(),
"ClassHash" => "FieldElement".to_string(),
"ContractAddress" => "FieldElement".to_string(),
_ => type_name.to_string(),
}
}
fn generated_header() -> String {
format!(
"// Generated by dojo-bindgen on {}. Do not modify this file manually.\n",
chrono::Utc::now().to_rfc2822()
)
}
// Token should be a struct
// This will be formatted into a C# struct
// using C# and unity SDK types
fn format_struct(token: &Composite) -> String {
let fields = token
.inners
.iter()
.map(|field| {
format!(
"public {} {};",
UnityPlugin::map_type(field.token.clone().type_name().as_str()),
field.name
)
})
.collect::<Vec<String>>()
.join("\n ");
format!(
"
// Type definition for `{}` struct
[Serializable]
public struct {} {{
{}
}}
",
token.type_path,
token.type_name(),
fields
)
}
// Token should be an enum
// This will be formatted into a C# enum
// Enum is mapped using index of cairo enum
fn format_enum(token: &Composite) -> String {
let fields = token
.inners
.iter()
.map(|field| format!("{},", field.name,))
.collect::<Vec<String>>()
.join("\n ");
format!(
"
// Type definition for `{}` enum
public enum {} {{
{}
}}
",
token.type_path,
token.type_name(),
fields
)
}
// Token should be a model
// This will be formatted into a C# class inheriting from ModelInstance
// Fields are mapped using C# and unity SDK types
fn format_model(model: &Composite) -> String {
let fields = model
.inners
.iter()
.map(|field| {
format!(
"[ModelField(\"{}\")]\n public {} {};",
field.name,
UnityPlugin::map_type(field.token.type_name().as_str()),
field.name,
)
})
.collect::<Vec<String>>()
.join("\n\n ");
format!(
"
// Model definition for `{}` model
public class {} : ModelInstance {{
{}
// Start is called before the first frame update
void Start() {{
}}
// Update is called once per frame
void Update() {{
}}
}}
",
model.type_path,
model.type_name(),
fields
)
}
// Handles a model definition and its referenced tokens
// Will map all structs and enums to C# types
// Will format the model into a C# class
fn handle_model(&self, model: &DojoModel, handled_tokens: &mut Vec<Composite>) -> String {
let mut out = String::new();
out += UnityPlugin::generated_header().as_str();
out += "using System;\n";
out += "using Dojo;\n";
out += "using Dojo.Starknet;\n";
let mut model_struct: Option<&Composite> = None;
let tokens = &model.tokens;
for token in &tokens.structs {
if handled_tokens.iter().any(|t| t.type_name() == token.type_name()) {
continue;
}
handled_tokens.push(token.to_composite().unwrap().to_owned());
// first index is our model struct
if token.type_name() == model.name {
model_struct = Some(token.to_composite().unwrap());
continue;
}
out += UnityPlugin::format_struct(token.to_composite().unwrap()).as_str();
}
for token in &tokens.enums {
if handled_tokens.iter().any(|t| t.type_name() == token.type_name()) {
continue;
}
handled_tokens.push(token.to_composite().unwrap().to_owned());
out += UnityPlugin::format_enum(token.to_composite().unwrap()).as_str();
}
out += "\n";
out += UnityPlugin::format_model(model_struct.expect("model struct not found")).as_str();
out
}
// Formats a system into a C# method used by the contract class
// Handled tokens should be a list of all structs and enums used by the contract
// Such as a set of referenced tokens from a model
fn format_system(system: &Function, handled_tokens: &[Composite]) -> String {
fn map_type(token: &Token) -> String {
match token {
Token::CoreBasic(t) => UnityPlugin::map_type(&t.type_name()),
Token::Composite(t) => t.type_name().to_string(),
Token::Array(t) => format!("{}[]", map_type(&t.inner)),
_ => panic!("Unsupported token type: {:?}", token),
}
}
let args = system
.inputs
.iter()
.map(|arg| format!("{} {}", map_type(&arg.1), &arg.0))
.collect::<Vec<String>>()
.join(", ");
let calldata = system
.inputs
.iter()
.map(|arg| {
let token = &arg.1;
let type_name = &arg.0;
match handled_tokens.iter().find(|t| t.type_name() == token.type_name()) {
Some(t) => {
// Need to flatten the struct members.
match t.r#type {
CompositeType::Struct => t
.inners
.iter()
.map(|field| {
format!(
"new FieldElement({}.{}).Inner()",
type_name, field.name
)
})
.collect::<Vec<String>>()
.join(",\n "),
_ => {
format!("new FieldElement({}).Inner()", type_name)
}
}
}
None => match UnityPlugin::map_type(type_name).as_str() {
"FieldElement" => format!("{}.Inner()", type_name),
_ => format!("new FieldElement({}).Inner()", type_name),
},
}
})
.collect::<Vec<String>>()
.join(",\n ");
format!(
"
// Call the `{system_name}` system with the specified Account and calldata
// Returns the transaction hash. Use `WaitForTransaction` to wait for the transaction to be \
confirmed.
public async Task<FieldElement> {system_name}(Account account{arg_sep}{args}) {{
return await account.ExecuteRaw(new dojo.Call[] {{
new dojo.Call{{
to = contractAddress,
selector = \"{system_name}\",
calldata = new dojo.FieldElement[] {{
{calldata}
}}
}}
}});
}}
",
// selector for execute
system_name = system.name,
// add comma if we have args
arg_sep = if !args.is_empty() { ", " } else { "" },
// formatted args to use our mapped types
args = args,
// calldata for execute
calldata = calldata
)
}
// Formats a contract file path into a pretty contract name
// eg. dojo_examples::actions::actions.json -> Actions
fn formatted_contract_name(contract_file_name: &str) -> String {
let contract_name =
contract_file_name.split("::").last().unwrap().trim_end_matches(".json");
// capitalize contract name
contract_name.chars().next().unwrap().to_uppercase().to_string() + &contract_name[1..]
}
// Handles a contract definition and its underlying systems
// Will format the contract into a C# class and
// all systems into C# methods
// Handled tokens should be a list of all structs and enums used by the contract
fn handle_contract(&self, contract: &DojoContract, handled_tokens: &[Composite]) -> String {
let mut out = String::new();
out += UnityPlugin::generated_header().as_str();
out += "using System;\n";
out += "using System.Threading.Tasks;\n";
out += "using Dojo;\n";
out += "using Dojo.Starknet;\n";
out += "using UnityEngine;\n";
out += "using dojo_bindings;\n";
let systems = contract
.systems
.iter()
.map(|system| UnityPlugin::format_system(system.to_function().unwrap(), handled_tokens))
.collect::<Vec<String>>()
.join("\n\n ");
out += &format!(
"
// System definitions for `{}` contract
public class {} : MonoBehaviour {{
// The address of this contract
public string contractAddress;
{}
}}
",
contract.qualified_path,
// capitalize contract name
UnityPlugin::formatted_contract_name(&contract.qualified_path),
systems
);
out
}
}
#[async_trait]
impl BuiltinPlugin for UnityPlugin {
async fn generate_code(&self, data: &DojoData) -> BindgenResult<HashMap<PathBuf, Vec<u8>>> {
let mut out: HashMap<PathBuf, Vec<u8>> = HashMap::new();
let mut handled_tokens = Vec::<Composite>::new();
// Handle codegen for models
for (name, model) in &data.models {
let models_path = Path::new(&format!("Models/{}.gen.cs", name)).to_owned();
println!("Generating model: {}", name);
let code = self.handle_model(model, &mut handled_tokens);
out.insert(models_path, code.as_bytes().to_vec());
}
// Handle codegen for systems
for (name, contract) in &data.contracts {
let contracts_path = Path::new(&format!("Contracts/{}.gen.cs", name)).to_owned();
println!("Generating contract: {}", name);
let code = self.handle_contract(contract, &handled_tokens);
out.insert(contracts_path, code.as_bytes().to_vec());
}
Ok(out)
}
}