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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
//! Compile-time validation of computation arguments using const evaluation.
//!
//! This module uses syn's visitor pattern to find `#[args("circuit_name")]` attributes in the code,
//! extracts the argument list, and validates it against the circuit interface using const
//! evaluation. Arguments are replaced with placeholder constants to enable this validation to run
//! at compile-time.
use crate::utils::{get_param_tokens_from_interface, read_conf_ix_interface};
use proc_macro2::{Span, TokenStream};
use quote::ToTokens;
use std::collections::HashMap;
use syn::{
parse_quote,
punctuated::Punctuated,
visit_mut::VisitMut,
Attribute,
Expr,
ExprCall,
ExprMethodCall,
ItemFn,
Local,
Stmt,
};
const ARGS_ATTRIBUTE_NAME: &str = "args";
/// Extracts method calls and accounts from ArgBuilder chain and converts them to ArgumentRef::...
/// expressions
fn extract_builder_args(
expr: &Expr,
) -> syn::Result<(
Punctuated<Expr, syn::token::Comma>,
Punctuated<Expr, syn::token::Comma>,
)> {
let mut method_calls = Vec::new();
let mut current = expr;
// Traverse the method call chain backwards (from build() to new())
loop {
match current {
Expr::MethodCall(ExprMethodCall {
method,
receiver,
args,
..
}) => {
if method == "build" {
// Start from the receiver of build()
current = receiver.as_ref();
continue;
}
// Collect method calls in reverse order
method_calls.push((method.to_string(), args.clone()));
current = receiver.as_ref();
}
Expr::Call(ExprCall { func, .. }) => {
// Check if this is ArgBuilder::new()
if let Expr::Path(path_expr) = func.as_ref() {
if let Some(seg) = path_expr.path.segments.last() {
if seg.ident == "new" {
// Found the start, break
break;
}
}
}
return Err(syn::Error::new_spanned(
expr,
"Expected ArgBuilder::new()...build() pattern",
));
}
_ => {
return Err(syn::Error::new_spanned(
expr,
"Expected ArgBuilder::new()...build() pattern",
));
}
}
}
// Reverse to get correct order and convert to ArgumentRef::... expressions
method_calls.reverse();
let mut arguments = Punctuated::new();
let mut account_count = 0u8;
let mut accounts = Punctuated::new();
for (method_name, method_args) in method_calls {
let arg_expr = match method_name.as_str() {
"x25519_pubkey" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::X25519Pubkey(0) }
}
"plaintext_u128" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::PlaintextU128(0) }
}
"plaintext_u64" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::PlaintextU64(0) }
}
"plaintext_u32" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::PlaintextU32(0) }
}
"plaintext_u16" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::PlaintextU16(0) }
}
"plaintext_u8" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::PlaintextU8(0) }
}
"plaintext_i128" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::PlaintextI128(0) }
}
"plaintext_i64" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::PlaintextI64(0) }
}
"plaintext_i32" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::PlaintextI32(0) }
}
"plaintext_i16" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::PlaintextI16(0) }
}
"plaintext_i8" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::PlaintextI8(0) }
}
"plaintext_bool" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::PlaintextBool(0) }
}
"plaintext_float" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::PlaintextFloat(0) }
}
"encrypted_u128" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::EncryptedU128(0) }
}
"encrypted_u64" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::EncryptedU64(0) }
}
"encrypted_u32" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::EncryptedU32(0) }
}
"encrypted_u16" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::EncryptedU16(0) }
}
"encrypted_u8" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::EncryptedU8(0) }
}
"encrypted_i128" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::EncryptedI128(0) }
}
"encrypted_i64" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::EncryptedI64(0) }
}
"encrypted_i32" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::EncryptedI32(0) }
}
"encrypted_i16" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::EncryptedI16(0) }
}
"encrypted_i8" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::EncryptedI8(0) }
}
"encrypted_bool" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::EncryptedBool(0) }
}
"encrypted_float" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::EncryptedFloat(0) }
}
"arcis_ed25519_signature" => {
// We don't care about the index since we're just checking if it matches the param
parse_quote! { ArgumentRef::ArcisEd25519Signature(0) }
}
"account" => {
if method_args.len() != 3 {
return Err(syn::Error::new_spanned(
&method_args,
"account expects 3 arguments",
));
}
let offset = method_args.iter().nth(1).unwrap();
let length = method_args.iter().nth(2).unwrap();
let account_index = account_count;
let res = parse_quote! { ArgumentRef::Account(#account_index) };
account_count += 1;
// Set pubkey to zero address so it can run in const context
accounts.push(parse_quote! { AccountArgument { pubkey: anchor_lang::solana_program::pubkey::Pubkey::new_from_array([0;32]), offset: #offset, length: #length } });
res
}
_ => {
return Err(syn::Error::new_spanned(
&method_args,
format!("Unknown builder method: {}", method_name),
));
}
};
arguments.push(arg_expr);
}
Ok((arguments, accounts))
}
#[derive(Default)]
struct ArgInfo {
args: Punctuated<Expr, syn::token::Comma>,
accounts: Punctuated<Expr, syn::token::Comma>,
}
#[derive(Default)]
struct IxArgsFinder {
current_ix: Option<String>,
// Mapping to args and accounts for each circuit
found: HashMap<String, ArgInfo>,
errors: Vec<syn::Error>,
}
impl VisitMut for IxArgsFinder {
fn visit_attributes_mut(&mut self, i: &mut Vec<Attribute>) {
let attr = i
.iter()
.enumerate()
.find(|attr| attr.1.meta.path().is_ident(ARGS_ATTRIBUTE_NAME));
if let Some((idx, attr)) = attr {
match attr.meta.require_list() {
Ok(nv) => {
let s: syn::LitStr = match syn::parse2(nv.tokens.clone()) {
Ok(s) => s,
Err(e) => {
self.errors.push(e);
return;
}
};
self.current_ix = Some(s.value());
}
Err(e) => self.errors.push(e),
}
i.remove(idx);
}
}
fn visit_local_mut(&mut self, i: &mut Local) {
self.visit_attributes_mut(&mut i.attrs);
syn::visit_mut::visit_local_mut(self, i);
}
fn visit_expr_mut(&mut self, i: &mut Expr) {
let Some(current_ix) = self.current_ix.as_ref() else {
syn::visit_mut::visit_expr_mut(self, i);
return;
};
if self.found.contains_key(current_ix) {
syn::visit_mut::visit_expr_mut(self, i);
return;
}
// Check if this is an inline ArgBuilder::new()...build() expression
match extract_builder_args(i) {
Ok((arguments, accounts)) => {
self.found.insert(
current_ix.clone(),
ArgInfo {
args: arguments,
accounts,
},
);
// Clear current_ix after finding args
self.current_ix = None;
}
Err(_) => {
// Not an ArgBuilder pattern, continue visiting
syn::visit_mut::visit_expr_mut(self, i);
}
}
}
fn visit_stmt_mut(&mut self, i: &mut Stmt) {
syn::visit_mut::visit_stmt_mut(self, i);
}
}
pub fn check_args_fn(mut item_fn: ItemFn) -> TokenStream {
let mut ix_args_finder = IxArgsFinder::default();
ix_args_finder.visit_item_fn_mut(&mut item_fn);
if ix_args_finder.found.is_empty() {
ix_args_finder.errors.push(syn::Error::new(
Span::call_site(),
"No `#[args(\"your_instruction\")]` found.",
));
}
let extra_stmts = ix_args_finder
.found
.into_iter()
.map(|(ix, ArgInfo { args, accounts })| {
let conf_ix_interface = read_conf_ix_interface(&ix);
let param_tokens = get_param_tokens_from_interface(&conf_ix_interface);
let quote_args = args.iter();
let quote_accounts = accounts.iter();
let res = parse_quote! {
const {
let accounts = [#(#quote_accounts),*];
let params = [#(#param_tokens),*];
let args = [#(#quote_args),*];
const_match_computation(&args, &accounts, ¶ms);
};
};
res
});
item_fn.block.stmts.splice(0..0, extra_stmts);
let mut res = item_fn.to_token_stream();
for err in ix_args_finder.errors {
res.extend(err.to_compile_error());
}
res
}
#[cfg(test)]
mod tests {
use super::*;
#[ignore = "Used for debugging, not for testing."]
#[test]
fn debug_this_macro() {
let input = parse_quote! {
pub fn find_next_match(ctx: Context<NextMatch>, computation_offset: u64) -> Result<()> {
ctx.accounts.sign_pda_account.bump = ctx.bumps.sign_pda_account;
#[args("find_next_match")]
let args = ArgBuilder::new()
.x25519_pubkey(ctx.accounts.orderbook.encryption_pubkey)
.plaintext_u128(ctx.accounts.orderbook.nonce)
.account(
ctx.accounts.orderbook.key(),
// Offset of 8 (discriminator) + 1 (bump) + 16 (nonce) + 32 (encryption pubkey)
8 + 1 + 16 + 32,
32 * 3 * ORDERBOOK_SIZE as u32,
)
.build();
// Call the Arcium program to queue the computations
queue_computation(
ctx.accounts,
computation_offset,
args,
Some("http://172.20.0.10:8080".to_string()),
vec![CallbackInstruction{
program_id: ID_CONST,
discriminator: instruction::FindNextMatchCallback::DISCRIMINATOR.to_vec(),
accounts: vec![
CallbackAccount{
pubkey: ARCIUM_PROGRAM_ID,
is_writable: false,
},
CallbackAccount{
pubkey: derive_comp_def_pda!(COMP_DEF_OFFSET_FIND_MATCH),
is_writable: false,
},
CallbackAccount{
pubkey: INSTRUCTIONS_SYSVAR_ID,
is_writable: false,
},
],
}],
1,
0,
)?;
Ok(())
}
};
let res = check_args_fn(input);
println!("{}", res);
}
}