thru-abi-gen 0.2.30

ABI code generation utilities for the Thru blockchain
Documentation
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use super::ir_helpers::{
    DerivedParamSpec, DynamicBinding, collect_dynamic_param_bindings,
    deduplicated_ts_parameter_bindings, derived_param_specs, sanitize_param_name,
    ts_name_dedup_map, ts_parameter_bindings,
};
use super::ir_serialization::ir_constant_name;
use crate::abi::resolved::{ResolvedType, ResolvedTypeKind, Size};
use crate::abi::types::PrimitiveType;
use crate::codegen::shared::ir::TypeIr;
use std::collections::BTreeMap;
use std::fmt::Write;

/* Emit the static footprint() method for a type.
Requires IR metadata - legacy fallback has been removed. */
pub fn emit_footprint_method(resolved_type: &ResolvedType, type_ir: Option<&TypeIr>) -> String {
    let ir = type_ir.unwrap_or_else(|| {
        panic!(
            "TypeScript codegen requires IR metadata for type '{}'. IR generation must have failed.",
            resolved_type.name
        )
    });
    let mut out = emit_ir_backed_footprint(resolved_type, ir);
    out.push_str(&emit_validate_method(resolved_type, Some(ir)));
    out
}

fn emit_ir_backed_footprint(resolved_type: &ResolvedType, type_ir: &TypeIr) -> String {
    let mut output = String::new();
    let param_names = ir_parameter_names(type_ir);
    let derived_specs = derived_param_specs(resolved_type, type_ir);
    output.push_str(&emit_ir_footprint(resolved_type, type_ir, &derived_specs));
    if param_names.is_empty() {
        output.push_str(&emit_ir_wrapper_footprint(resolved_type, &param_names));
    } else {
        output.push_str(&emit_ir_wrapper_from_params(
            resolved_type,
            type_ir,
            &param_names,
            &derived_specs,
        ));
    }
    output
}

fn emit_ir_footprint(
    resolved_type: &ResolvedType,
    type_ir: &TypeIr,
    derived_specs: &[DerivedParamSpec],
) -> String {
    let mut output = String::new();
    /* All bindings are needed for IR packing (all canonical names must be in the record) */
    let bindings: Vec<_> = ts_parameter_bindings(type_ir).into_iter().collect();
    /* Deduplicated bindings are used for public API (function signatures, Params type) */
    let dedup_bindings: Vec<_> = deduplicated_ts_parameter_bindings(type_ir)
        .into_iter()
        .filter(|b| !b.derived)
        .collect();
    /* Map from ts_name to deduplicated ts_name for __tnPackParams */
    let dedup_map = ts_name_dedup_map(type_ir);
    let const_name = ir_constant_name(resolved_type);

    writeln!(
        &mut output,
        "  private static __tnFootprintInternal(__tnParams: Record<string, bigint>): bigint {{"
    )
    .unwrap();
    writeln!(
        &mut output,
        "    return __tnEvalFootprint({}.root, {{ params: __tnParams }});",
        const_name
    )
    .unwrap();
    writeln!(&mut output, "  }}\n").unwrap();

    writeln!(
        &mut output,
        "  private static __tnValidateInternal(buffer: Uint8Array, __tnParams: Record<string, bigint>): {{ ok: boolean; code?: string; consumed?: bigint }} {{"
    )
    .unwrap();
    writeln!(
        &mut output,
        "    return __tnValidateIrTree({}, buffer, __tnParams);",
        const_name
    )
    .unwrap();
    writeln!(&mut output, "  }}\n").unwrap();

    writeln!(
        &mut output,
        "  static __tnInvokeFootprint(__tnParams: Record<string, bigint>): bigint {{"
    )
    .unwrap();
    writeln!(
        &mut output,
        "    return this.__tnFootprintInternal(__tnParams);"
    )
    .unwrap();
    writeln!(&mut output, "  }}\n").unwrap();

    writeln!(
        &mut output,
        "  static __tnInvokeValidate(buffer: Uint8Array, __tnParams: Record<string, bigint>): __TnValidateResult {{"
    )
    .unwrap();
    writeln!(
        &mut output,
        "    return this.__tnValidateInternal(buffer, __tnParams);"
    )
    .unwrap();
    writeln!(&mut output, "  }}\n").unwrap();

    if bindings.is_empty() {
        writeln!(&mut output, "  static footprintIr(): bigint {{").unwrap();
        writeln!(
            &mut output,
            "    return this.__tnFootprintInternal(Object.create(null));"
        )
        .unwrap();
        writeln!(&mut output, "  }}\n").unwrap();
        return output;
    }

    /* Use deduplicated bindings for public API */
    let params_sig = dedup_bindings
        .iter()
        .map(|binding| format!("{}: number | bigint", binding.ts_name))
        .collect::<Vec<_>>()
        .join(", ");
    let params_ns = format!("{}.Params", resolved_type.name);
    writeln!(
        &mut output,
        "  static footprintIr({}): bigint {{",
        params_sig
    )
    .unwrap();
    writeln!(
        &mut output,
        "    const params = {}.Params.fromValues({{",
        resolved_type.name
    )
    .unwrap();
    for binding in &dedup_bindings {
        writeln!(
            &mut output,
            "      {}: {},",
            binding.ts_name, binding.ts_name
        )
        .unwrap();
    }
    writeln!(&mut output, "    }});").unwrap();
    writeln!(
        &mut output,
        "    return this.footprintIrFromParams(params);"
    )
    .unwrap();
    writeln!(&mut output, "  }}\n").unwrap();

    writeln!(
        &mut output,
        "  private static __tnPackParams(params: {}): Record<string, bigint> {{",
        params_ns
    )
    .unwrap();
    writeln!(
        &mut output,
        "    const record: Record<string, bigint> = Object.create(null);"
    )
    .unwrap();
    /* Use all bindings for record keys (IR needs all canonical names),
    but map ts_names to deduplicated equivalents for params access */
    for binding in bindings.iter().filter(|binding| !binding.derived) {
        let params_field = dedup_map
            .get(&binding.ts_name)
            .map(|s| s.as_str())
            .unwrap_or(&binding.ts_name);
        writeln!(
            &mut output,
            "    record[\"{}\"] = params.{};",
            binding.canonical.replace('\"', "\\\""),
            params_field
        )
        .unwrap();
    }
    for spec in derived_specs {
        writeln!(
            &mut output,
            "    record[\"{}\"] = (() => {{ return {}; }})();",
            spec.canonical.replace('\"', "\\\""),
            spec.expr
        )
        .unwrap();
    }
    writeln!(&mut output, "    return record;").unwrap();
    writeln!(&mut output, "  }}\n").unwrap();

    output
}

fn ir_parameter_names(type_ir: &TypeIr) -> Vec<String> {
    type_ir
        .parameters
        .iter()
        .filter(|param| !param.derived)
        .map(|param| sanitize_param_name(&param.name))
        .collect()
}

fn emit_ir_wrapper_footprint(resolved_type: &ResolvedType, params: &[String]) -> String {
    let mut output = String::new();
    let signature_params: Vec<String> = params
        .iter()
        .map(|name| format!("{name}: number | bigint"))
        .collect();
    let ir_args: Vec<String> = params
        .iter()
        .map(|name| format!("__tnToBigInt({name})"))
        .collect();

    if signature_params.is_empty() {
        writeln!(&mut output, "  static footprint(): number {{").unwrap();
    } else {
        writeln!(
            &mut output,
            "  static footprint({}): number {{",
            signature_params.join(", ")
        )
        .unwrap();
    }

    let ir_call = if ir_args.is_empty() {
        "this.footprintIr()".to_string()
    } else {
        format!("this.footprintIr({})", ir_args.join(", "))
    };
    writeln!(&mut output, "    const irResult = {ir_call};").unwrap();
    writeln!(
        &mut output,
        "      const maxSafe = __tnToBigInt(Number.MAX_SAFE_INTEGER);"
    )
    .unwrap();
    writeln!(
        &mut output,
        "    if (__tnBigIntGreaterThan(irResult, maxSafe)) {{"
    )
    .unwrap();
    writeln!(
        &mut output,
        "      throw new Error('footprint exceeds Number.MAX_SAFE_INTEGER for {}');",
        resolved_type.name
    )
    .unwrap();
    writeln!(&mut output, "    }}").unwrap();
    writeln!(
        &mut output,
        "    return __tnBigIntToNumber(irResult, '{}::footprint');",
        resolved_type.name
    )
    .unwrap();
    writeln!(
        &mut output,
        "  }}
"
    )
    .unwrap();
    output
}

fn emit_validate_method(resolved_type: &ResolvedType, type_ir: Option<&TypeIr>) -> String {
    match type_ir {
        Some(ir) if ir.parameters.iter().any(|param| !param.derived) => {
            let extractor_available = !collect_dynamic_param_bindings(resolved_type).is_empty();
            emit_validate_with_params(resolved_type, ir, extractor_available)
        }
        _ => emit_validate_const(resolved_type),
    }
}

fn emit_validate_with_params(
    resolved_type: &ResolvedType,
    _type_ir: &TypeIr,
    extractor_available: bool,
) -> String {
    let class_name = &resolved_type.name;
    let params_ns = format!("{}.Params", class_name);
    let mut output = String::new();

    writeln!(
        &mut output,
        "  static validate(buffer: Uint8Array, opts?: {{ params?: {} }}): {{ ok: boolean; code?: string; consumed?: number; params?: {} }} {{",
        params_ns, params_ns
    )
    .unwrap();
    writeln!(
        &mut output,
        "    if (!buffer || buffer.length === undefined) {{"
    )
    .unwrap();
    writeln!(
        &mut output,
        "      return {{ ok: false, code: \"tn.invalid_buffer\" }};"
    )
    .unwrap();
    writeln!(&mut output, "    }}").unwrap();
    writeln!(
        &mut output,
        "    const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);"
    )
    .unwrap();
    writeln!(&mut output, "    let params = opts?.params ?? null;").unwrap();
    if extractor_available {
        writeln!(&mut output, "    if (!params) {{").unwrap();
        writeln!(
            &mut output,
            "      const extracted = this.__tnExtractParams(view, buffer);"
        )
        .unwrap();
        writeln!(
            &mut output,
            "      if (!extracted) return {{ ok: false, code: \"tn.param_extraction_failed\" }};"
        )
        .unwrap();
        writeln!(&mut output, "      params = extracted.params;").unwrap();
        writeln!(&mut output, "    }}").unwrap();
    } else {
        writeln!(&mut output, "    if (!params) {{").unwrap();
        writeln!(
            &mut output,
            "      return {{ ok: false, code: \"tn.param_extraction_failed\" }};"
        )
        .unwrap();
        writeln!(&mut output, "    }}").unwrap();
    }
    writeln!(
        &mut output,
        "    const __tnParamsRec = this.__tnPackParams(params);"
    )
    .unwrap();
    writeln!(
        &mut output,
        "    const irResult = this.__tnValidateInternal(buffer, __tnParamsRec);"
    )
    .unwrap();
    writeln!(&mut output, "    if (!irResult.ok) {{").unwrap();
    writeln!(
        &mut output,
        "      return {{ ok: false, code: irResult.code, consumed: irResult.consumed ? __tnBigIntToNumber(irResult.consumed, '{}::validate') : undefined, params }};",
        resolved_type.name
    )
    .unwrap();
    writeln!(&mut output, "    }}").unwrap();
    writeln!(
        &mut output,
        "    const consumed = irResult.consumed ? __tnBigIntToNumber(irResult.consumed, '{}::validate') : undefined;",
        resolved_type.name
    )
    .unwrap();
    writeln!(&mut output, "    return {{ ok: true, consumed, params }};").unwrap();
    writeln!(&mut output, "  }}\n").unwrap();

    output
}

fn emit_validate_const(resolved_type: &ResolvedType) -> String {
    let mut output = String::new();
    match &resolved_type.size {
        Size::Const(sz) => {
            writeln!(
                &mut output,
                "  static validate(buffer: Uint8Array, _opts?: {{ params?: never }}): {{ ok: boolean; code?: string; consumed?: number }} {{"
            )
            .unwrap();
            writeln!(
                &mut output,
                "    if (buffer.length < {}) return {{ ok: false, code: \"tn.buffer_too_small\", consumed: {} }};",
                sz, sz
            )
            .unwrap();
            writeln!(&mut output, "    return {{ ok: true, consumed: {} }};", sz).unwrap();
            writeln!(&mut output, "  }}\n").unwrap();
        }
        _ => {
            writeln!(
                &mut output,
                "  static validate(_buffer: Uint8Array, _opts?: {{ params?: never }}): {{ ok: boolean; code?: string; consumed?: number }} {{"
            )
            .unwrap();
            writeln!(
                &mut output,
                "    __tnLogWarn(\"{}::validate falling back to basic length check\");",
                resolved_type.name
            )
            .unwrap();
            writeln!(
                &mut output,
                "    return {{ ok: true, consumed: _buffer.length }};"
            )
            .unwrap();
            writeln!(&mut output, "  }}\n").unwrap();
        }
    }
    output
}
fn emit_ir_wrapper_from_params(
    resolved_type: &ResolvedType,
    type_ir: &TypeIr,
    _legacy_params: &[String],
    _derived_specs: &[DerivedParamSpec],
) -> String {
    /* Use deduplicated bindings for public API */
    let public_bindings: Vec<_> = deduplicated_ts_parameter_bindings(type_ir)
        .into_iter()
        .filter(|binding| !binding.derived)
        .collect();
    if public_bindings.is_empty() {
        return String::new();
    }

    let mut output = String::new();
    let params_ns = format!("{}.Params", resolved_type.name);

    writeln!(
        &mut output,
        "  static footprintIrFromParams(params: {}): bigint {{",
        params_ns
    )
    .unwrap();
    writeln!(
        &mut output,
        "    const __tnParams = this.__tnPackParams(params);"
    )
    .unwrap();
    writeln!(
        &mut output,
        "    return this.__tnFootprintInternal(__tnParams);"
    )
    .unwrap();
    writeln!(&mut output, "  }}\n").unwrap();

    writeln!(
        &mut output,
        "  static footprintFromParams(params: {}): number {{",
        params_ns
    )
    .unwrap();
    writeln!(
        &mut output,
        "    const irResult = this.footprintIrFromParams(params);"
    )
    .unwrap();
    writeln!(
        &mut output,
        "    const maxSafe = __tnToBigInt(Number.MAX_SAFE_INTEGER);"
    )
    .unwrap();
    writeln!(
        &mut output,
        "    if (__tnBigIntGreaterThan(irResult, maxSafe)) throw new Error('footprint exceeds Number.MAX_SAFE_INTEGER for {}');",
        resolved_type.name
    )
    .unwrap();
    writeln!(
        &mut output,
        "    return __tnBigIntToNumber(irResult, '{}::footprintFromParams');",
        resolved_type.name
    )
    .unwrap();
    writeln!(&mut output, "  }}\n").unwrap();

    writeln!(
        &mut output,
        "  static footprintFromValues(input: {{ {} }}): number {{",
        public_bindings
            .iter()
            .map(|b| format!("{}: number | bigint", b.ts_name))
            .collect::<Vec<_>>()
            .join(", ")
    )
    .unwrap();
    writeln!(
        &mut output,
        "    const params = {}.params(input);",
        resolved_type.name
    )
    .unwrap();
    writeln!(&mut output, "    return this.footprintFromParams(params);").unwrap();
    writeln!(&mut output, "  }}\n").unwrap();

    writeln!(
        &mut output,
        "  static footprint(params: {}): number {{",
        params_ns
    )
    .unwrap();
    writeln!(&mut output, "    return this.footprintFromParams(params);").unwrap();
    writeln!(&mut output, "  }}\n").unwrap();

    output
}