Support (fixed-length) arrays of 16-bit integers
[ldk-java] / typescript_strings.py
1 from bindingstypes import ConvInfo
2 from enum import Enum
3
4 def first_to_lower(string: str) -> str:
5     first = string[0]
6     return first.lower() + string[1:]
7
8
9 class Target(Enum):
10     NODEJS = 1,
11     BROWSER = 2
12
13 class Consts:
14     def __init__(self, DEBUG: bool, target: Target, outdir: str, **kwargs):
15         self.outdir = outdir
16         self.struct_file_suffixes = {}
17         self.function_ptr_counter = 0
18         self.function_ptrs = {}
19         self.c_type_map = dict(
20             bool = ['boolean', 'boolean', 'XXX'],
21             uint8_t = ['number', 'number', 'Uint8Array'],
22             uint16_t = ['number', 'number', 'Uint16Array'],
23             uint32_t = ['number', 'number', 'Uint32Array'],
24             uint64_t = ['bigint', 'bigint', 'BigUint64Array'],
25         )
26         self.java_type_map = dict(
27             String = "number"
28         )
29         self.java_hu_type_map = dict(
30             String = "string"
31         )
32
33         self.to_hu_conv_templates = dict(
34             ptr = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
35             default = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
36         )
37
38         self.bindings_header = """
39 import * as version from './version.mjs';
40 import { UInt5, WitnessVersion } from './structs/CommonBase.mjs';
41
42 const imports: any = {};
43 imports.env = {};
44
45 var js_objs: Array<WeakRef<object>> = [];
46 var js_invoke: Function;
47 var getRandomValues: Function;
48
49 imports.wasi_snapshot_preview1 = {
50         "fd_write": (fd: number, iovec_array_ptr: number, iovec_array_len: number, bytes_written_ptr: number) => {
51                 // This should generally only be used to print panic messages
52                 const ptr_len_view = new Uint32Array(wasm.memory.buffer, iovec_array_ptr, iovec_array_len * 2);
53                 var bytes_written = 0;
54                 for (var i = 0; i < iovec_array_len; i++) {
55                         const bytes_view = new Uint8Array(wasm.memory.buffer, ptr_len_view[i*2], ptr_len_view[i*2+1]);
56                         console.log("[fd " + fd + "]: " + String.fromCharCode(...bytes_view));
57                         bytes_written += ptr_len_view[i*2+1]!;
58                 }
59                 const written_view = new Uint32Array(wasm.memory.buffer, bytes_written_ptr, 1);
60                 written_view[0] = bytes_written;
61                 return 0;
62         },
63         "fd_close": (_fd: number) => {
64                 // This is not generally called, but may be referenced in debug builds
65                 console.log("wasi_snapshot_preview1:fd_close");
66                 return 58; // Not Supported
67         },
68         "fd_seek": (_fd: number, _offset: bigint, _whence: number, _new_offset: number) => {
69                 // This is not generally called, but may be referenced in debug builds
70                 console.log("wasi_snapshot_preview1:fd_seek");
71                 return 58; // Not Supported
72         },
73         "random_get": (buf_ptr: number, buf_len: number) => {
74                 const buf = new Uint8Array(wasm.memory.buffer, buf_ptr, buf_len);
75                 getRandomValues(buf);
76                 return 0;
77         },
78         "environ_sizes_get": (environ_var_count_ptr: number, environ_len_ptr: number) => {
79                 // This is called before fd_write to format + print panic messages
80                 const out_count_view = new Uint32Array(wasm.memory.buffer, environ_var_count_ptr, 1);
81                 out_count_view[0] = 0;
82                 const out_len_view = new Uint32Array(wasm.memory.buffer, environ_len_ptr, 1);
83                 out_len_view[0] = 0;
84                 return 0;
85         },
86         "environ_get": (_environ_ptr: number, _environ_buf_ptr: number) => {
87                 // This is called before fd_write to format + print panic messages,
88                 // but only if we have variables in environ_sizes_get, so shouldn't ever actually happen!
89                 console.log("wasi_snapshot_preview1:environ_get");
90                 return 58; // Note supported - we said there were 0 environment entries!
91         },
92         "proc_exit" : () => {
93                 console.log("wasi_snapshot_preview1:proc_exit");
94         },
95 };
96
97 var wasm: any = null;
98 let isWasmInitialized: boolean = false;
99
100 async function finishInitializeWasm(wasmInstance: WebAssembly.Instance) {
101         if (typeof crypto === "undefined") {
102                 var crypto_import = (await import('crypto')).webcrypto;
103                 getRandomValues = crypto_import.getRandomValues.bind(crypto_import);
104         } else {
105                 getRandomValues = crypto.getRandomValues.bind(crypto);
106         }
107
108         wasm = wasmInstance.exports;
109         if (!wasm.test_bigint_pass_deadbeef0badf00d(BigInt("0xdeadbeef0badf00d"))) {
110                 throw new Error(\"Currently need BigInt-as-u64 support, try ----experimental-wasm-bigint");
111         }
112
113         if (decodeString(wasm.TS_get_lib_version_string()) !== version.get_ldk_java_bindings_version())
114                 throw new Error(\"Compiled LDK library and LDK class files do not match\");
115         // Fetching the LDK versions from C also checks that the header and binaries match
116         const c_bindings_ver: number = wasm.TS_get_ldk_c_bindings_version();
117         const ldk_ver: number = wasm.TS_get_ldk_version();
118         if (c_bindings_ver == 0)
119                 throw new Error(\"LDK version did not match the header we built against\");
120         if (ldk_ver == 0)
121                 throw new Error(\"LDK C bindings version did not match the header we built against\");
122         const c_bindings_version: string = decodeString(c_bindings_ver)
123         const ldk_version: string = decodeString(ldk_ver);
124         console.log(\"Loaded LDK-Java Bindings with LDK \" + ldk_version + \" and LDK-C-Bindings \" + c_bindings_version);
125
126         isWasmInitialized = true;
127 }
128
129 const fn_list = ["uuuuuu", "buuuuu", "bbuuuu", "bbbuuu", "bbbbuu",
130         "bbbbbb", "ubuubu", "ubuuuu", "ubbuuu", "uubuuu", "uububu", "ububuu"];
131
132 /* @internal */
133 export async function initializeWasmFromUint8Array(wasmBinary: Uint8Array) {
134         for (const fn of fn_list) { imports.env["js_invoke_function_" + fn] = js_invoke; }
135         const { instance: wasmInstance } = await WebAssembly.instantiate(wasmBinary, imports);
136         await finishInitializeWasm(wasmInstance);
137 }
138
139 /* @internal */
140 export async function initializeWasmFetch(uri: string) {
141         for (const fn of fn_list) { imports.env["js_invoke_function_" + fn] = js_invoke; }
142         const stream = fetch(uri);
143         const { instance: wasmInstance } = await WebAssembly.instantiateStreaming(stream, imports);
144         await finishInitializeWasm(wasmInstance);
145 }"""
146
147         self.bindings_header += """
148 // WASM CODEC
149
150 /* @internal */
151 export function uint5ArrToBytes(inputArray: Array<UInt5>): Uint8Array {
152         const arr = new Uint8Array(inputArray.length);
153         for (var i = 0; i < inputArray.length; i++) {
154                 arr[i] = inputArray[i]!.getVal();
155         }
156         return arr;
157 }
158
159 /* @internal */
160 export function WitnessVersionArrToBytes(inputArray: Array<WitnessVersion>): Uint8Array {
161         const arr = new Uint8Array(inputArray.length);
162         for (var i = 0; i < inputArray.length; i++) {
163                 arr[i] = inputArray[i]!.getVal();
164         }
165         return arr;
166 }
167
168
169
170 /* @internal */
171 export function encodeUint128 (inputVal: bigint): number {
172         if (inputVal >= 0x10000000000000000000000000000000n) throw "U128s cannot exceed 128 bits";
173         const cArrayPointer = wasm.TS_malloc(16 + 8);
174         const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
175         arrayLengthView[0] = BigInt(16);
176         const arrayMemoryView = new Uint8Array(wasm.memory.buffer, cArrayPointer + 8, 16);
177         for (var i = 0; i < 16; i++) arrayMemoryView[i] = Number((inputVal >> BigInt(i)*8n) & 0xffn);
178         return cArrayPointer;
179 }
180 /* @internal */
181 export function encodeUint8Array (inputArray: Uint8Array|null): number {
182         if (inputArray == null) return 0;
183         const cArrayPointer = wasm.TS_malloc(inputArray.length + 8);
184         const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
185         arrayLengthView[0] = BigInt(inputArray.length);
186         const arrayMemoryView = new Uint8Array(wasm.memory.buffer, cArrayPointer + 8, inputArray.length);
187         arrayMemoryView.set(inputArray);
188         return cArrayPointer;
189 }
190 /* @internal */
191 export function encodeUint16Array (inputArray: Uint16Array|Array<number>|null): number {
192         if (inputArray == null) return 0;
193         const cArrayPointer = wasm.TS_malloc((inputArray.length + 4) * 2);
194         const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
195         arrayLengthView[0] = BigInt(inputArray.length);
196         const arrayMemoryView = new Uint16Array(wasm.memory.buffer, cArrayPointer + 8, inputArray.length);
197         arrayMemoryView.set(inputArray);
198         return cArrayPointer;
199 }
200 /* @internal */
201 export function encodeUint32Array (inputArray: Uint32Array|Array<number>|null): number {
202         if (inputArray == null) return 0;
203         const cArrayPointer = wasm.TS_malloc((inputArray.length + 2) * 4);
204         const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
205         arrayLengthView[0] = BigInt(inputArray.length);
206         const arrayMemoryView = new Uint32Array(wasm.memory.buffer, cArrayPointer + 8, inputArray.length);
207         arrayMemoryView.set(inputArray);
208         return cArrayPointer;
209 }
210 /* @internal */
211 export function encodeUint64Array (inputArray: BigUint64Array|Array<bigint>|null): number {
212         if (inputArray == null) return 0;
213         const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 8);
214         const arrayMemoryView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, inputArray.length + 1);
215         arrayMemoryView[0] = BigInt(inputArray.length);
216         arrayMemoryView.set(inputArray, 1);
217         return cArrayPointer;
218 }
219
220 /* @internal */
221 export function check_arr_len(arr: Uint8Array|null, len: number): Uint8Array|null {
222         if (arr !== null && arr.length != len) { throw new Error("Expected array of length " + len + " got " + arr.length); }
223         return arr;
224 }
225
226 /* @internal */
227 export function check_16_arr_len(arr: Uint16Array|null, len: number): Uint16Array|null {
228         if (arr !== null && arr.length != len) { throw new Error("Expected array of length " + len + " got " + arr.length); }
229         return arr;
230 }
231
232 /* @internal */
233 export function getArrayLength(arrayPointer: number): number {
234         const arraySizeViewer = new BigUint64Array(wasm.memory.buffer, arrayPointer, 1);
235         const len = arraySizeViewer[0]!;
236         if (len >= (2n ** 32n)) throw new Error("Bogus Array Size");
237         return Number(len % (2n ** 32n));
238 }
239 /* @internal */
240 export function decodeUint128 (arrayPointer: number, free = true): bigint {
241         const arraySize = getArrayLength(arrayPointer);
242         if (arraySize != 16) throw "Need 16 bytes for a uint128";
243         const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, arraySize);
244         var val = 0n;
245         for (var i = 0; i < 16; i++) {
246                 val <<= 8n;
247                 val |= BigInt(actualArrayViewer[i]!);
248         }
249         if (free) {
250                 wasm.TS_free(arrayPointer);
251         }
252         return val;
253 }
254 /* @internal */
255 export function decodeUint8Array (arrayPointer: number, free = true): Uint8Array {
256         const arraySize = getArrayLength(arrayPointer);
257         const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, arraySize);
258         // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
259         // will free the underlying memory when it becomes unreachable instead of copying here.
260         // Note that doing so may have edge-case interactions with memory resizing (invalidating the buffer).
261         const actualArray = actualArrayViewer.slice(0, arraySize);
262         if (free) {
263                 wasm.TS_free(arrayPointer);
264         }
265         return actualArray;
266 }
267 /* @internal */
268 export function decodeUint16Array (arrayPointer: number, free = true): Uint16Array {
269         const arraySize = getArrayLength(arrayPointer);
270         const actualArrayViewer = new Uint16Array(wasm.memory.buffer, arrayPointer + 8, arraySize);
271         // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
272         // will free the underlying memory when it becomes unreachable instead of copying here.
273         // Note that doing so may have edge-case interactions with memory resizing (invalidating the buffer).
274         const actualArray = actualArrayViewer.slice(0, arraySize);
275         if (free) {
276                 wasm.TS_free(arrayPointer);
277         }
278         return actualArray;
279 }
280 /* @internal */
281 export function decodeUint64Array (arrayPointer: number, free = true): bigint[] {
282         const arraySize = getArrayLength(arrayPointer);
283         const actualArrayViewer = new BigUint64Array(
284                 wasm.memory.buffer, // value
285                 arrayPointer + 8, // offset (ignoring length bytes)
286                 arraySize // uint32 count
287         );
288         // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
289         // will free the underlying memory when it becomes unreachable instead of copying here.
290         const actualArray = new Array(arraySize);
291         for (var i = 0; i < arraySize; i++) actualArray[i] = actualArrayViewer[i];
292         if (free) {
293                 wasm.TS_free(arrayPointer);
294         }
295         return actualArray;
296 }
297
298 export function freeWasmMemory(pointer: number) { wasm.TS_free(pointer); }
299
300 /* @internal */
301 export function getU64ArrayElem(arrayPointer: number, idx: number): bigint {
302         const actualArrayViewer = new BigUint64Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
303         return actualArrayViewer[idx]!;
304 }
305
306 /* @internal */
307 export function getU32ArrayElem(arrayPointer: number, idx: number): number {
308         const actualArrayViewer = new Uint32Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
309         return actualArrayViewer[idx]!;
310 }
311
312 /* @internal */
313 export function getU8ArrayElem(arrayPointer: number, idx: number): number {
314         const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
315         return actualArrayViewer[idx]!;
316 }
317
318
319 /* @internal */
320 export function encodeString(str: string): number {
321         const charArray = new TextEncoder().encode(str);
322         return encodeUint8Array(charArray);
323 }
324
325 /* @internal */
326 export function decodeString(stringPointer: number, free = true): string {
327         const arraySize = getArrayLength(stringPointer);
328         const memoryView = new Uint8Array(wasm.memory.buffer, stringPointer + 8, arraySize);
329         const result = new TextDecoder("utf-8").decode(memoryView);
330
331         if (free) {
332                 wasm.TS_free(stringPointer);
333         }
334
335         return result;
336 }
337 """
338         if DEBUG:
339             self.bindings_header += """
340 /* @internal */
341 export function getRemainingAllocationCount(): number {
342         return wasm.TS_allocs_remaining();
343 }
344 /* @internal */
345 export function debugPrintRemainingAllocs() {
346         wasm.TS_print_leaks();
347 }
348 """
349         else:
350             self.bindings_header += "\n/* @internal */ export function getRemainingAllocationCount(): number { return 0; }\n"
351             self.bindings_header += "/* @internal */ export function debugPrintRemainingAllocs() { }\n"
352
353         with open(outdir + "/index.mts", 'a') as index:
354             index.write("""import { initializeWasmFetch, initializeWasmFromUint8Array } from './bindings.mjs';
355 /** Initializes the WASM backend by calling `fetch()` on the given URI - Browser only */
356 export async function initializeWasmWebFetch(uri: string) {
357         await initializeWasmFetch(uri);
358 }
359 /** Initializes the WASM backend given a Uint8Array of the .wasm binary file - Browser or Node.JS */
360 export async function initializeWasmFromBinary(bin: Uint8Array) {
361         await initializeWasmFromUint8Array(bin);
362 }
363
364 """)
365
366         self.bindings_version_file = """export function get_ldk_java_bindings_version(): String {
367         return "<git_version_ldk_garbagecollected>";
368 }"""
369
370         self.common_base = """
371 function freer(f: () => void) { f() }
372 const finalizer = new FinalizationRegistry(freer);
373 function get_freeer(ptr: bigint, free_fn: (ptr: bigint) => void) {
374         return () => {
375                 free_fn(ptr);
376         }
377 }
378
379 export class CommonBase {
380         protected ptr: bigint;
381         protected ptrs_to: object[] = [];
382         protected constructor(ptr: bigint, free_fn: (ptr: bigint) => void) {
383                 this.ptr = ptr;
384                 if (ptr != 0n){
385                         finalizer.register(this, get_freeer(ptr, free_fn), this);
386                 }
387         }
388         // In Java, protected means "any subclass can access fields on any other subclass'"
389         // In TypeScript, protected means "any subclass can access parent fields on instances of itself"
390         // To work around this, we add accessors for other instances' protected fields here.
391         protected static add_ref_from(holder: CommonBase|null, referent: object|null) {
392                 if (holder !== null && referent !== null) { holder.ptrs_to.push(referent); }
393         }
394         protected static get_ptr_of(o: CommonBase) {
395                 return o.ptr;
396         }
397         protected static set_null_skip_free(o: CommonBase) {
398                 o.ptr = 0n;
399                 // @ts-ignore TypeScript is wrong about the returnvalue of unregister here!
400                 const did_unregister: boolean = finalizer.unregister(o);
401                 if (!did_unregister)
402                         throw new Error("FinalizationRegistry unregister should always unregister unless you double-free'd");
403         }
404 }
405
406 export class UInt5 {
407         public constructor(private val: number) {
408                 if (val > 32 || val < 0) throw new Error("UInt5 value is out of range");
409         }
410         public getVal(): number {
411                 return this.val;
412         }
413 }
414
415 export class WitnessVersion {
416         public constructor(private val: number) {
417                 if (val > 16 || val < 0) throw new Error("WitnessVersion value is out of range");
418         }
419         public getVal(): number {
420                 return this.val;
421         }
422 }
423
424 export class UnqualifiedError {
425         public constructor(_val: number) {}
426 }
427 """
428
429         self.txout_defn = """export class TxOut extends CommonBase {
430         /** The script_pubkey in this output */
431         public script_pubkey: Uint8Array;
432         /** The value, in satoshis, of this output */
433         public value: bigint;
434
435         /* @internal */
436         public constructor(_dummy: null, ptr: bigint) {
437                 super(ptr, bindings.TxOut_free);
438                 this.script_pubkey = bindings.decodeUint8Array(bindings.TxOut_get_script_pubkey(ptr));
439                 this.value = bindings.TxOut_get_value(ptr);
440         }
441         public static constructor_new(value: bigint, script_pubkey: Uint8Array): TxOut {
442                 return new TxOut(null, bindings.TxOut_new(bindings.encodeUint8Array(script_pubkey), value));
443         }
444 }"""
445         self.obj_defined(["TxOut"], "structs")
446
447         self.scalar_defn = """export class BigEndianScalar extends CommonBase {
448         /** The bytes of the scalar value, in big endian */
449         public scalar_bytes: Uint8Array;
450
451         /* @internal */
452         public constructor(_dummy: null, ptr: bigint) {
453                 super(ptr, bindings.BigEndianScalar_free);
454                 this.scalar_bytes = bindings.decodeUint8Array(bindings.BigEndianScalar_get_bytes(ptr));
455         }
456         public static constructor_new(scalar_bytes: Uint8Array): BigEndianScalar {
457                 return new BigEndianScalar(null, bindings.BigEndianScalar_new(bindings.encodeUint8Array(scalar_bytes)));
458         }
459 }"""
460         self.obj_defined(["BigEndianScalar"], "structs")
461
462         self.c_file_pfx = """#include "js-wasm.h"
463 #include <stdatomic.h>
464 #include <lightning.h>
465
466 // These should be provided...somehow...
467 void *memset(void *s, int c, size_t n);
468 void *memcpy(void *dest, const void *src, size_t n);
469 int memcmp(const void *s1, const void *s2, size_t n);
470
471 extern void __attribute__((noreturn)) abort(void);
472 static inline void assert(bool expression) {
473         if (!expression) { abort(); }
474 }
475
476 uint32_t __attribute__((export_name("test_bigint_pass_deadbeef0badf00d"))) test_bigint_pass_deadbeef0badf00d(uint64_t val) {
477         return val == 0xdeadbeef0badf00dULL;
478 }
479
480 """
481
482         if not DEBUG:
483             self.c_file_pfx += """
484 void *malloc(size_t size);
485 void free(void *ptr);
486
487 #define MALLOC(a, _) malloc(a)
488 #define do_MALLOC(a, _b, _c) malloc(a)
489 #define FREE(p) if ((unsigned long)(p) > 4096) { free(p); }
490 #define DO_ASSERT(a) (void)(a)
491 #define CHECK(a)
492 #define CHECK_ACCESS(p)
493 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
494 """
495         else:
496             self.c_file_pfx += """
497 extern int snprintf(char *str, size_t size, const char *format, ...);
498 typedef int32_t ssize_t;
499 ssize_t write(int fd, const void *buf, size_t count);
500 #define DEBUG_PRINT(...) do { \\
501         char debug_str[1024]; \\
502         int s_len = snprintf(debug_str, 1023, __VA_ARGS__); \\
503         write(2, debug_str, s_len); \\
504 } while (0);
505
506 // Always run a, then assert it is true:
507 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
508 // Assert a is true or do nothing
509 #define CHECK(a) DO_ASSERT(a)
510
511 // Running a leak check across all the allocations and frees of the JDK is a mess,
512 // so instead we implement our own naive leak checker here, relying on the -wrap
513 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
514 // and free'd in Rust or C across the generated bindings shared library.
515
516 #define BT_MAX 128
517 typedef struct allocation {
518         struct allocation* next;
519         void* ptr;
520         const char* struct_name;
521         int lineno;
522 } allocation;
523 static allocation* allocation_ll = NULL;
524 static allocation* freed_ll = NULL;
525
526 extern void* __real_malloc(size_t len);
527 extern void* __real_calloc(size_t nmemb, size_t len);
528 extern void* __real_aligned_alloc(size_t alignment, size_t size);
529 static void new_allocation(void* res, const char* struct_name, int lineno) {
530         allocation* new_alloc = __real_malloc(sizeof(allocation));
531         new_alloc->ptr = res;
532         new_alloc->struct_name = struct_name;
533         new_alloc->next = allocation_ll;
534         new_alloc->lineno = lineno;
535         allocation_ll = new_alloc;
536 }
537 static void* do_MALLOC(size_t len, const char* struct_name, int lineno) {
538         void* res = __real_malloc(len);
539         new_allocation(res, struct_name, lineno);
540         return res;
541 }
542 #define MALLOC(len, struct_name) do_MALLOC(len, struct_name, __LINE__)
543
544 void __real_free(void* ptr);
545 static void alloc_freed(void* ptr, int lineno) {
546         allocation* p = NULL;
547         allocation* it = allocation_ll;
548         while (it->ptr != ptr) {
549                 p = it; it = it->next;
550                 if (it == NULL) {
551                         p = NULL;
552                         it = freed_ll;
553                         while (it && it->ptr != ptr) { p = it; it = it->next; }
554                         if (it == NULL) {
555                                 DEBUG_PRINT("Tried to free unknown pointer %p at line %d.\\n", ptr, lineno);
556                         } else {
557                                 DEBUG_PRINT("Tried to free unknown pointer %p at line %d.\\n Possibly double-free from %s, allocated on line %d.", ptr, lineno, it->struct_name, it->lineno);
558                         }
559                         abort();
560                 }
561         }
562         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
563         DO_ASSERT(it->ptr == ptr);
564         it->next = freed_ll;
565         freed_ll = it;
566 }
567 static void do_FREE(void* ptr, int lineno) {
568         if ((unsigned long)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
569         alloc_freed(ptr, lineno);
570         __real_free(ptr);
571 }
572 #define FREE(ptr) do_FREE(ptr, __LINE__)
573
574 static void CHECK_ACCESS(const void* ptr) {
575         allocation* it = allocation_ll;
576         while (it->ptr != ptr) {
577                 it = it->next;
578                 if (it == NULL) {
579                         return; // addrsan should catch malloc-unknown and print more info than we have
580                 }
581         }
582 }
583 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
584         if (v.is_owned && v.inner != NULL) { \\
585                 const void *p = __unmangle_inner_ptr(v.inner); \\
586                 if (p != NULL) { \\
587                         CHECK_ACCESS(p); \\
588                 } \\
589         }
590
591 void* __wrap_malloc(size_t len) {
592         void* res = __real_malloc(len);
593         new_allocation(res, "malloc call", 0);
594         return res;
595 }
596 void* __wrap_calloc(size_t nmemb, size_t len) {
597         void* res = __real_calloc(nmemb, len);
598         new_allocation(res, "calloc call", 0);
599         return res;
600 }
601 void* __wrap_aligned_alloc(size_t alignment, size_t size) {
602         void* res = __real_aligned_alloc(alignment, size);
603         new_allocation(res, "aligned_alloc call", 0);
604         return res;
605 }
606 void __wrap_free(void* ptr) {
607         if (ptr == NULL) return;
608         alloc_freed(ptr, 0);
609         __real_free(ptr);
610 }
611
612 void* __real_realloc(void* ptr, size_t newlen);
613 void* __wrap_realloc(void* ptr, size_t len) {
614         if (ptr != NULL) alloc_freed(ptr, 0);
615         void* res = __real_realloc(ptr, len);
616         new_allocation(res, "realloc call", 0);
617         return res;
618 }
619 void __wrap_reallocarray(void* ptr, size_t new_sz) {
620         // Rust doesn't seem to use reallocarray currently
621         DO_ASSERT(false);
622 }
623
624 uint32_t __attribute__((export_name("TS_allocs_remaining"))) allocs_remaining() {
625         uint32_t count = 0;
626         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
627                 count++;
628         }
629         return count;
630 }
631 void __attribute__((export_name("TS_print_leaks"))) print_leaks() {
632         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
633                 DEBUG_PRINT("%s %p remains. Allocated on line %d\\n", a->struct_name, a->ptr, a->lineno);
634         }
635 }
636 """
637         self.c_file_pfx = self.c_file_pfx + """
638 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
639 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
640 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
641 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
642
643 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
644
645 #define DECL_ARR_TYPE(ty, name) \\
646         struct name##array { \\
647                 uint64_t arr_len; /* uint32_t would suffice but we want to align uint64_ts as well */ \\
648                 ty elems[]; \\
649         }; \\
650         typedef struct name##array * name##Array; \\
651         static inline name##Array init_##name##Array(size_t arr_len, int lineno) { \\
652                 name##Array arr = (name##Array)do_MALLOC(arr_len * sizeof(ty) + sizeof(uint64_t), #name" array init", lineno); \\
653                 arr->arr_len = arr_len; \\
654                 return arr; \\
655         }
656
657 DECL_ARR_TYPE(int64_t, int64_t);
658 DECL_ARR_TYPE(uint64_t, uint64_t);
659 DECL_ARR_TYPE(int8_t, int8_t);
660 DECL_ARR_TYPE(int16_t, int16_t);
661 DECL_ARR_TYPE(uint32_t, uint32_t);
662 DECL_ARR_TYPE(void*, ptr);
663 DECL_ARR_TYPE(char, char);
664 typedef charArray jstring;
665
666 static inline jstring str_ref_to_ts(const char* chars, size_t len) {
667         charArray arr = init_charArray(len, __LINE__);
668         memcpy(arr->elems, chars, len);
669         return arr;
670 }
671 static inline LDKStr str_ref_to_owned_c(const jstring str) {
672         char* newchars = MALLOC(str->arr_len + 1, "String chars");
673         memcpy(newchars, str->elems, str->arr_len);
674         newchars[str->arr_len] = 0;
675         LDKStr res = {
676                 .chars = newchars,
677                 .len = str->arr_len,
678                 .chars_is_owned = true
679         };
680         return res;
681 }
682
683 typedef bool jboolean;
684
685 uint32_t __attribute__((export_name("TS_malloc"))) TS_malloc(uint32_t size) {
686         return (uint32_t)MALLOC(size, "JS-Called malloc");
687 }
688 void __attribute__((export_name("TS_free"))) TS_free(uint32_t ptr) {
689         FREE((void*)ptr);
690 }
691
692 jstring __attribute__((export_name("TS_get_ldk_c_bindings_version"))) TS_get_ldk_c_bindings_version() {
693         const char *res = check_get_ldk_bindings_version();
694         if (res == NULL) return NULL;
695         return str_ref_to_ts(res, strlen(res));
696 }
697 jstring __attribute__((export_name("TS_get_ldk_version"))) get_ldk_version() {
698         const char *res = check_get_ldk_version();
699         if (res == NULL) return NULL;
700         return str_ref_to_ts(res, strlen(res));
701 }
702 #include "version.c"
703 """
704
705         self.c_version_file = """jstring __attribute__((export_name("TS_get_lib_version_string"))) TS_get_lib_version_string() {
706         return str_ref_to_ts("<git_version_ldk_garbagecollected>", strlen("<git_version_ldk_garbagecollected>"));
707 }"""
708
709         self.hu_struct_file_prefix = """
710 import { CommonBase, UInt5, WitnessVersion, UnqualifiedError } from './CommonBase.mjs';
711 import * as bindings from '../bindings.mjs'
712
713 """
714         self.hu_struct_file_suffix = ""
715         self.util_fn_pfx = self.hu_struct_file_prefix + "\nexport class UtilMethods extends CommonBase {\n"
716         self.util_fn_sfx = "}"
717         self.c_fn_ty_pfx = ""
718         self.file_ext = ".mts"
719         self.ptr_c_ty = "uint64_t"
720         self.ptr_native_ty = "bigint"
721         self.u128_native_ty = "bigint"
722         self.usize_c_ty = "uint32_t"
723         self.usize_native_ty = "number"
724         self.native_zero_ptr = "0n"
725         self.result_c_ty = "uint32_t"
726         self.ptr_arr = "ptrArray"
727         self.is_arr_some_check = ("", " != 0")
728         self.get_native_arr_len_call = ("", "->arr_len")
729
730     def bindings_footer(self):
731         return ""
732
733     def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
734         return None
735     def create_native_arr_call(self, arr_len, ty_info):
736         if ty_info.c_ty == "ptrArray":
737             assert ty_info.rust_obj == "LDKCVec_U5Z" or (ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array"))
738         return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
739     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
740         if ty_info.c_ty == "int8_tArray":
741             return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
742         elif ty_info.c_ty == "int16_tArray":
743             return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + " * 2)")
744         else:
745             assert False
746     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
747         if ty_info.c_ty == "int8_tArray" or ty_info.c_ty == "int16_tArray":
748             if copy:
749                 byte_len = arr_len
750                 if ty_info.c_ty == "int16_tArray":
751                     byte_len = arr_len + " * 2"
752                 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + byte_len + "); FREE(" + arr_name + ")"
753         assert not copy
754         if ty_info.c_ty == "ptrArray":
755             return "(void*) " + arr_name + "->elems"
756         else:
757             return arr_name + "->elems"
758     def get_native_arr_elem(self, arr_name, idxc, ty_info):
759         assert False # Only called if above is None
760     def get_native_arr_ptr_call(self, ty_info):
761         if ty_info.subty is not None:
762             return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 8)"
763         return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 8)"
764     def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
765         return None
766     def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
767         if ty_info.c_ty == "int8_tArray":
768             return "FREE(" + arr_name + ");"
769         else:
770             return "FREE(" + arr_name + ")"
771
772     def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty):
773         if elem_ty.rust_obj == "LDKU5":
774             return arr_name + " != null ? bindings.uint5ArrToBytes(" + arr_name + ") : null"
775         assert elem_ty.c_ty == "uint64_t" or elem_ty.c_ty.endswith("Array")
776         return arr_name + " != null ? " + arr_name + ".map(" + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
777
778     def str_ref_to_native_call(self, var_name, str_len):
779         return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
780     def str_ref_to_c_call(self, var_name):
781         return "str_ref_to_owned_c(" + var_name + ")"
782     def str_to_hu_conv(self, var_name):
783         return "const " + var_name + "_conv: string = bindings.decodeString(" + var_name + ");"
784     def str_from_hu_conv(self, var_name):
785         return ("bindings.encodeString(" + var_name + ")", "")
786
787     def c_fn_name_define_pfx(self, fn_name, have_args):
788         return " __attribute__((export_name(\"TS_" + fn_name + "\"))) TS_" + fn_name + "("
789
790     def init_str(self):
791         return ""
792
793     def get_java_arr_len(self, arr_name):
794         return "bindings.getArrayLength(" + arr_name + ")"
795     def get_java_arr_elem(self, elem_ty, arr_name, idx):
796         if elem_ty.c_ty.endswith("Array") or elem_ty.c_ty == "uintptr_t":
797             return "bindings.getU32ArrayElem(" + arr_name + ", " + idx + ")"
798         elif elem_ty.c_ty == "uint64_t":
799             return "bindings.getU64ArrayElem(" + arr_name + ", " + idx + ")"
800         elif elem_ty.rust_obj == "LDKU5":
801             return "bindings.getU8ArrayElem(" + arr_name + ", " + idx + ")"
802         else:
803             assert False
804     def constr_hu_array(self, ty_info, arr_len):
805         return "new Array(" + arr_len + ").fill(null)"
806     def cleanup_converted_native_array(self, ty_info, arr_name):
807         return "bindings.freeWasmMemory(" + arr_name + ")"
808
809     def primitive_arr_from_hu(self, arr_ty, fixed_len, arr_name):
810         mapped_ty = arr_ty.subty
811         inner = arr_name
812         if arr_ty.rust_obj == "LDKU128":
813             return ("bindings.encodeUint128(" + inner + ")", "")
814         if fixed_len is not None:
815             if mapped_ty.c_ty == "int8_t":
816                 inner = "bindings.check_arr_len(" + arr_name + ", " + fixed_len + ")"
817             elif mapped_ty.c_ty == "int16_t":
818                 inner = "bindings.check_16_arr_len(" + arr_name + ", " + fixed_len + ")"
819         if mapped_ty.c_ty.endswith("Array"):
820             return ("bindings.encodeUint32Array(" + inner + ")", "")
821         elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
822             return ("bindings.encodeUint8Array(" + inner + ")", "")
823         elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
824             return ("bindings.encodeUint16Array(" + inner + ")", "")
825         elif mapped_ty.c_ty == "uint32_t":
826             return ("bindings.encodeUint32Array(" + inner + ")", "")
827         elif mapped_ty.c_ty == "int64_t" or mapped_ty.c_ty == "uint64_t":
828             return ("bindings.encodeUint64Array(" + inner + ")", "")
829         else:
830             print(mapped_ty.c_ty)
831             assert False
832
833     def primitive_arr_to_hu(self, arr_ty, fixed_len, arr_name, conv_name):
834         mapped_ty = arr_ty.subty
835         if arr_ty.rust_obj == "LDKU128":
836             return "const " + conv_name + ": bigint = bindings.decodeUint128(" + arr_name + ");"
837         elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
838             return "const " + conv_name + ": Uint8Array = bindings.decodeUint8Array(" + arr_name + ");"
839         elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
840             return "const " + conv_name + ": Uint16Array = bindings.decodeUint16Array(" + arr_name + ");"
841         elif mapped_ty.c_ty == "uint64_t" or mapped_ty.c_ty == "int64_t":
842             return "const " + conv_name + ": bigint[] = bindings.decodeUint64Array(" + arr_name + ");"
843         else:
844             assert False
845
846     def var_decl_statement(self, ty_string, var_name, statement):
847         return "const " + var_name + ": " + ty_string + " = " + statement
848
849     def java_arr_ty_str(self, elem_ty_str):
850         return "number"
851
852     def for_n_in_range(self, n, minimum, maximum):
853         return "for (var " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
854     def for_n_in_arr(self, n, arr_name, arr_elem_ty):
855         return (arr_name + ".forEach((" + n + ": " + arr_elem_ty.java_hu_ty + ") => { ", " })")
856
857     def get_ptr(self, var):
858         return "CommonBase.get_ptr_of(" + var + ")"
859     def set_null_skip_free(self, var):
860         return "CommonBase.set_null_skip_free(" + var + ");"
861
862     def add_ref(self, holder, referent):
863         return "CommonBase.add_ref_from(" + holder + ", " + referent + ")"
864
865     def obj_defined(self, struct_names, folder):
866         with open(self.outdir + "/index.mts", 'a') as index:
867             index.write(f"export * from './{folder}/{struct_names[0]}.mjs';\n")
868         with open(self.outdir + "/imports.mts.part", 'a') as imports:
869             imports.write(f"import {{ {', '.join(struct_names)} }} from '../{folder}/{struct_names[0]}.mjs';\n")
870
871     def fully_qualified_hu_ty_path(self, ty):
872         return ty.java_hu_ty
873
874     def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
875         out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_js(int32_t ord) {\n"
876         out_c = out_c + "\tswitch (ord) {\n"
877         ord_v = 0
878
879         out_typescript_enum_fields = ""
880
881         for var, var_docs in variants:
882             out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
883             ord_v = ord_v + 1
884             if var_docs is not None:
885                 var_docs_repld = var_docs.replace("\n", "\n\t")
886                 out_typescript_enum_fields += f"/**\n\t * {var_docs_repld}\n\t */\n"
887             out_typescript_enum_fields += f"\t{var},\n\t"
888         out_c = out_c + "\t}\n"
889         out_c = out_c + "\tabort();\n"
890         out_c = out_c + "}\n"
891
892         out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
893         out_c = out_c + "\tswitch (val) {\n"
894         ord_v = 0
895         for var, _ in variants:
896             out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
897             ord_v = ord_v + 1
898         out_c = out_c + "\t\tdefault: abort();\n"
899         out_c = out_c + "\t}\n"
900         out_c = out_c + "}\n"
901
902         # Note that this is *not* marked /* @internal */ as we re-expose it directly in enums/
903         enum_comment_formatted = enum_doc_comment.replace("\n", "\n * ")
904         out_typescript = f"""
905 /**
906  * {enum_comment_formatted}
907  */
908 export enum {struct_name} {{
909         {out_typescript_enum_fields}
910 }}
911 """
912         out_typescript_enum = f"export {{ {struct_name} }} from \"../bindings.mjs\";"
913         self.obj_defined([struct_name], "enums")
914         return (out_c, out_typescript_enum, out_typescript)
915
916     def c_unitary_enum_to_native_call(self, ty_info):
917         return (ty_info.rust_obj + "_to_js(", ")")
918     def native_unitary_enum_to_c_call(self, ty_info):
919         return (ty_info.rust_obj + "_from_js(", ")")
920
921     def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
922         out_typescript_bindings = ""
923         super_instantiator = ""
924         bindings_instantiator = ""
925         pointer_to_adder = ""
926         impl_constructor_arguments = ""
927         for var in flattened_field_var_conversions:
928             if isinstance(var, ConvInfo):
929                 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
930                 super_instantiator += first_to_lower(var.arg_name) + ", "
931                 if var.from_hu_conv is not None:
932                     bindings_instantiator += ", " + var.from_hu_conv[0]
933                     if var.from_hu_conv[1] != "":
934                         pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
935                 else:
936                     bindings_instantiator += ", " + first_to_lower(var.arg_name)
937             else:
938                 bindings_instantiator += ", " + first_to_lower(var[1]) + ".instance_idx!"
939                 super_instantiator += first_to_lower(var[1]) + "_impl, "
940                 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
941                 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}Interface"
942
943         super_constructor_statements = ""
944         trait_constructor_arguments = ""
945         for var in field_var_conversions:
946             if isinstance(var, ConvInfo):
947                 trait_constructor_arguments += ", " + var.arg_name
948             else:
949                 super_constructor_statements += "\t\tconst " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + super_instantiator + ");\n"
950                 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".instance_idx!"
951                 for suparg in var[2]:
952                     if isinstance(suparg, ConvInfo):
953                         trait_constructor_arguments += ", " + suparg.arg_name
954                     else:
955                         trait_constructor_arguments += ", " + suparg[1]
956
957         # BUILD INTERFACE METHODS
958         out_java_interface = ""
959         out_interface_implementation_overrides = ""
960         java_methods = []
961         for fn_line in field_function_lines:
962             java_method_descriptor = ""
963             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
964                 out_java_interface += "\t/**" + fn_line.docs.replace("\n", "\n\t * ") + "\n\t */\n"
965                 out_java_interface += "\t" + fn_line.fn_name + "("
966                 out_interface_implementation_overrides += f"\t\t\t{fn_line.fn_name} ("
967
968                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
969                     if idx >= 1:
970                         out_java_interface += ", "
971                         out_interface_implementation_overrides += ", "
972                     out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
973                     out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
974                     java_method_descriptor += arg_conv_info.java_fn_ty_arg
975                 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n"
976                 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
977                 java_methods.append((fn_line.fn_name, java_method_descriptor))
978
979                 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
980
981                 for arg_info in fn_line.args_ty:
982                     if arg_info.to_hu_conv is not None:
983                         out_interface_implementation_overrides += "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
984
985                 if fn_line.ret_ty_info.java_ty != "void":
986                     out_interface_implementation_overrides += "\t\t\t\tconst ret: " + fn_line.ret_ty_info.java_hu_ty + " = arg." + fn_line.fn_name + "("
987                 else:
988                     out_interface_implementation_overrides += f"\t\t\t\targ." + fn_line.fn_name + "("
989
990                 for idx, arg_info in enumerate(fn_line.args_ty):
991                     if idx != 0:
992                         out_interface_implementation_overrides += ", "
993                     if arg_info.to_hu_conv_name is not None:
994                         out_interface_implementation_overrides += arg_info.to_hu_conv_name
995                     else:
996                         out_interface_implementation_overrides += arg_info.arg_name
997
998                 out_interface_implementation_overrides += ");\n"
999                 if fn_line.ret_ty_info.java_ty != "void":
1000                     if fn_line.ret_ty_info.from_hu_conv is not None:
1001                         out_interface_implementation_overrides += "\t\t\t\t" + f"const result: {fn_line.ret_ty_info.java_ty} = " + fn_line.ret_ty_info.from_hu_conv[0].replace("\n", "\n\t\t\t\t") + ";\n"
1002                         if fn_line.ret_ty_info.from_hu_conv[1] != "":
1003                             out_interface_implementation_overrides += "\t\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held").replace("\n", "\n\t\t\t\t") + ";\n"
1004                         #if fn_line.ret_ty_info.rust_obj in result_types:
1005                         # XXX: We need to handle this in conversion logic so that its cross-language!
1006                         # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
1007                         #    out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
1008                         out_interface_implementation_overrides += "\t\t\t\treturn result;\n"
1009                     else:
1010                         out_interface_implementation_overrides += "\t\t\t\treturn ret;\n"
1011                 out_interface_implementation_overrides += f"\t\t\t}},\n"
1012
1013         formatted_trait_docs = trait_doc_comment.replace("\n", "\n * ")
1014         out_typescript_human = f"""
1015 {self.hu_struct_file_prefix}
1016
1017 /** An implementation of {struct_name.replace("LDK","")} */
1018 export interface {struct_name.replace("LDK", "")}Interface {{
1019 {out_java_interface}}}
1020
1021 class {struct_name}Holder {{
1022         held: {struct_name.replace("LDK", "")}|null = null;
1023 }}
1024
1025 /**
1026  * {formatted_trait_docs}
1027  */
1028 export class {struct_name.replace("LDK","")} extends CommonBase {{
1029         /* @internal */
1030         public bindings_instance: bindings.{struct_name}|null;
1031
1032         /* @internal */
1033         public instance_idx?: number;
1034
1035         /* @internal */
1036         constructor(_dummy: null, ptr: bigint) {{
1037                 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1038                 this.bindings_instance = null;
1039         }}
1040
1041         /** Creates a new instance of {struct_name.replace("LDK","")} from a given implementation */
1042         public static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
1043                 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
1044                 let structImplementation = {{
1045 {out_interface_implementation_overrides}                }} as bindings.{struct_name};
1046 {super_constructor_statements}          const ptr_idx: [bigint, number] = bindings.{struct_name}_new(structImplementation{bindings_instantiator});
1047
1048                 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr_idx[0]);
1049                 impl_holder.held.instance_idx = ptr_idx[1];
1050                 impl_holder.held.bindings_instance = structImplementation;
1051 {pointer_to_adder}              return impl_holder.held!;
1052         }}
1053
1054 """
1055         self.obj_defined([struct_name.replace("LDK", ""), struct_name.replace("LDK", "") + "Interface"], "structs")
1056
1057         out_typescript_bindings += "/* @internal */\nexport interface " + struct_name + " {\n"
1058         java_meths = []
1059         for fn_line in field_function_lines:
1060             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1061                 out_typescript_bindings += f"\t{fn_line.fn_name} ("
1062
1063                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
1064                     if idx >= 1:
1065                         out_typescript_bindings = out_typescript_bindings + ", "
1066                     out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1067
1068                 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
1069
1070         out_typescript_bindings += "}\n\n"
1071
1072         c_call_extra_args = ""
1073         out_typescript_bindings += f"/* @internal */\nexport function {struct_name}_new(impl: {struct_name}"
1074         for var in flattened_field_var_conversions:
1075             if isinstance(var, ConvInfo):
1076                 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
1077                 c_call_extra_args += f", {var.arg_name}"
1078             else:
1079                 out_typescript_bindings += f", {var[1]}: number"
1080                 c_call_extra_args += f", {var[1]}"
1081
1082
1083         out_typescript_bindings += f"""): [bigint, number] {{
1084         if(!isWasmInitialized) {{
1085                 throw new Error("initializeWasm() must be awaited first!");
1086         }}
1087         var new_obj_idx = js_objs.length;
1088         for (var i = 0; i < js_objs.length; i++) {{
1089                 if (js_objs[i] == null || js_objs[i] == undefined) {{ new_obj_idx = i; break; }}
1090         }}
1091         js_objs[i] = new WeakRef(impl);
1092         return [wasm.TS_{struct_name}_new(i{c_call_extra_args}), i];
1093 }}
1094 """
1095
1096         # Now that we've written out our java code (and created java_meths), generate C
1097         out_c = "typedef struct " + struct_name + "_JCalls {\n"
1098         out_c += "\tatomic_size_t refcnt;\n"
1099         out_c += "\tuint32_t instance_ptr;\n"
1100         for var in flattened_field_var_conversions:
1101             if isinstance(var, ConvInfo):
1102                 # We're a regular ol' field
1103                 pass
1104             else:
1105                 # We're a supertrait
1106                 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
1107         out_c = out_c + "} " + struct_name + "_JCalls;\n"
1108
1109         for fn_line in field_function_lines:
1110             if fn_line.fn_name == "free":
1111                 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
1112                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
1113                 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
1114                 out_c = out_c + "\t\tFREE(j_calls);\n"
1115                 out_c = out_c + "\t}\n}\n"
1116
1117         for idx, fn_line in enumerate(field_function_lines):
1118             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1119                 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
1120                 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
1121                 if fn_line.self_is_const:
1122                     out_c = out_c + "const void* this_arg"
1123                 else:
1124                     out_c = out_c + "void* this_arg"
1125
1126                 for idx, arg in enumerate(fn_line.args_ty):
1127                     out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
1128
1129                 out_c = out_c + ") {\n"
1130                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
1131
1132                 for arg_info in fn_line.args_ty:
1133                     if arg_info.ret_conv is not None:
1134                         out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
1135                         out_c = out_c + arg_info.arg_name
1136                         out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
1137
1138                 fn_suffix = ""
1139                 assert len(fn_line.args_ty) < 7
1140                 for arg_info in fn_line.args_ty:
1141                     if arg_info.c_ty == "uint64_t" or arg_info.c_ty == "int64_t":
1142                         fn_suffix += "b"
1143                     else:
1144                         fn_suffix += "u"
1145                 for i in range(0, 6 - len(fn_line.args_ty)):
1146                     fn_suffix += "u"
1147                 if fn_line.ret_ty_info.c_ty.endswith("Array"):
1148                     out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
1149                     out_c += "js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1150                 elif fn_line.ret_ty_info.java_ty == "void":
1151                     out_c = out_c + "\tjs_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1152                 elif fn_line.ret_ty_info.java_hu_ty == "string":
1153                     out_c += "\tjstring ret = (jstring)js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1154                 elif fn_line.ret_ty_info.arg_conv is None:
1155                     out_c += "\treturn js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1156                 else:
1157                     out_c += "\tuint64_t ret = js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1158
1159                 self.function_ptrs[self.function_ptr_counter] = (struct_name, fn_line.fn_name)
1160                 self.function_ptr_counter += 1
1161
1162                 for idx, arg_info in enumerate(fn_line.args_ty):
1163                     if arg_info.ret_conv is not None:
1164                         if arg_info.c_ty.endswith("Array"):
1165                             out_c += ", (uint32_t)" + arg_info.ret_conv_name
1166                         else:
1167                             out_c += ", " + arg_info.ret_conv_name
1168                     else:
1169                         assert False # TODO: Would we need some conversion here?
1170                         out_c += ", (uint32_t)" + arg_info.arg_name
1171                 for i in range(0, 6 - len(fn_line.args_ty)):
1172                     out_c += ", 0"
1173                 out_c = out_c + ");\n"
1174                 if fn_line.ret_ty_info.arg_conv is not None:
1175                     out_c = out_c + "\t" + fn_line.ret_ty_info.arg_conv.replace("\n", "\n\t") + "\n\treturn " + fn_line.ret_ty_info.arg_conv_name + ";\n"
1176
1177                 out_c = out_c + "}\n"
1178
1179         # Write out a clone function whether we need one or not, as we use them in moving to rust
1180         out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
1181         out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
1182         out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
1183         for var in field_var_conversions:
1184             if not isinstance(var, ConvInfo):
1185                 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
1186         out_c = out_c + "}\n"
1187
1188         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (JSValue o"
1189         for var in flattened_field_var_conversions:
1190             if isinstance(var, ConvInfo):
1191                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1192             else:
1193                 out_c = out_c + ", JSValue " + var[1]
1194         out_c = out_c + ") {\n"
1195
1196         out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
1197         out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
1198         out_c = out_c + "\tcalls->instance_ptr = o;\n"
1199
1200         for (fn_name, java_meth_descr) in java_meths:
1201             if fn_name != "free" and fn_name != "cloned":
1202                 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
1203                 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
1204
1205         for var in flattened_field_var_conversions:
1206             if isinstance(var, ConvInfo) and var.arg_conv is not None:
1207                 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
1208         out_c = out_c + "\n\t" + struct_name + " ret = {\n"
1209         out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
1210         for fn_line in field_function_lines:
1211             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1212                 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
1213             elif fn_line.fn_name == "free":
1214                 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
1215             else:
1216                 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
1217         for var in field_var_conversions:
1218             if isinstance(var, ConvInfo):
1219                 if var.arg_conv_name is not None:
1220                     out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
1221                     out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
1222                 else:
1223                     out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
1224                     out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
1225             else:
1226                 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
1227                 for suparg in var[2]:
1228                     if isinstance(suparg, ConvInfo):
1229                         out_c += ", " + suparg.arg_name
1230                     else:
1231                         out_c += ", " + suparg[1]
1232                 out_c += "),\n"
1233         out_c = out_c + "\t};\n"
1234         for var in flattened_field_var_conversions:
1235             if not isinstance(var, ConvInfo):
1236                 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
1237         out_c = out_c + "\treturn ret;\n"
1238         out_c = out_c + "}\n"
1239
1240         out_c = out_c + self.c_fn_ty_pfx + "uint64_t " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "JSValue o"
1241         for var in flattened_field_var_conversions:
1242             if isinstance(var, ConvInfo):
1243                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1244             else:
1245                 out_c = out_c + ", JSValue " + var[1]
1246         out_c = out_c + ") {\n"
1247         out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
1248         out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
1249         for var in flattened_field_var_conversions:
1250             if isinstance(var, ConvInfo):
1251                 out_c = out_c + ", " + var.arg_name
1252             else:
1253                 out_c = out_c + ", " + var[1]
1254         out_c = out_c + ");\n"
1255         out_c = out_c + "\treturn tag_ptr(res_ptr, true);\n"
1256         out_c = out_c + "}\n"
1257
1258         return (out_typescript_bindings, out_typescript_human, out_c)
1259
1260     def trait_struct_inc_refcnt(self, ty_info):
1261         base_conv = "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
1262         base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
1263         base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_cloned(&" + ty_info.var_name + "_conv);\n}"
1264         return base_conv
1265
1266     def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
1267         bindings_type = struct_name.replace("LDK", "")
1268         java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
1269
1270         out_java_enum = ""
1271         out_java = ""
1272         out_c = ""
1273
1274         out_java_enum += (self.hu_struct_file_prefix)
1275
1276         java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
1277         java_hu_class += "export class " + java_hu_type + " extends CommonBase {\n"
1278         java_hu_class += "\tprotected constructor(_dummy: null, ptr: bigint) { super(ptr, bindings." + bindings_type + "_free); }\n"
1279         java_hu_class += "\t/* @internal */\n"
1280         java_hu_class += f"\tpublic static constr_from_ptr(ptr: bigint): {java_hu_type} {{\n"
1281         java_hu_class += f"\t\tconst raw_ty: number = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
1282         out_c += self.c_fn_ty_pfx + "uint32_t" + self.c_fn_name_define_pfx(struct_name + "_ty_from_ptr", True) + self.ptr_c_ty + " ptr) {\n"
1283         out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1284         out_c += "\tswitch(obj->tag) {\n"
1285         java_hu_class += "\t\tswitch (raw_ty) {\n"
1286         java_hu_subclasses = ""
1287
1288         out_java += "/* @internal */\nexport class " + struct_name + " {\n"
1289         out_java += "\tprotected constructor() {}\n"
1290         var_idx = 0
1291         for var in variant_list:
1292             java_hu_subclasses += "/** A " + java_hu_type + " of type " + var.var_name + " */\n"
1293             java_hu_subclasses += "export class " + java_hu_type + "_" + var.var_name + " extends " + java_hu_type + " {\n"
1294             java_hu_class += f"\t\t\tcase {var_idx}: "
1295             java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
1296             out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
1297             hu_conv_body = ""
1298             for idx, (field_ty, field_docs) in enumerate(var.fields):
1299                 if field_docs is not None:
1300                     java_hu_subclasses += "\t/**\n\t * " + field_docs.replace("\n", "\n\t * ") + "\n\t */\n"
1301                 java_hu_subclasses += "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
1302                 if field_ty.to_hu_conv is not None:
1303                     hu_conv_body += f"\t\tconst {field_ty.arg_name}: {field_ty.java_ty} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1304                     hu_conv_body += f"\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1305                     hu_conv_body += f"\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1306                 else:
1307                     hu_conv_body += f"\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1308             java_hu_subclasses += "\t/* @internal */\n"
1309             java_hu_subclasses += "\tpublic constructor(ptr: bigint) {\n\t\tsuper(null, ptr);\n"
1310             java_hu_subclasses = java_hu_subclasses + hu_conv_body
1311             java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
1312             var_idx += 1
1313         out_java += "}\n"
1314         java_hu_class += "\t\t\tdefault:\n\t\t\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t\t}\n\t}\n\n"
1315         out_java += self.fn_call_body(struct_name + "_ty_from_ptr", "uint32_t", "number", "ptr: bigint", "ptr")
1316         out_c += ("\t\tdefault: abort();\n")
1317         out_c += ("\t}\n}\n")
1318
1319         for var in variant_list:
1320             for idx, (field_map, _) in enumerate(var.fields):
1321                 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1322                 out_c += self.c_fn_ty_pfx + field_map.c_ty + self.c_fn_name_define_pfx(fn_name, True) + self.ptr_c_ty + " ptr) {\n"
1323                 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1324                 out_c += f"\tassert(obj->tag == {struct_name}_{var.var_name});\n"
1325                 if field_map.ret_conv is not None:
1326                     out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1327                     if var.tuple_variant:
1328                         out_c += "obj->" + camel_to_snake(var.var_name)
1329                     else:
1330                         out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1331                     out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1332                     out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1333                 else:
1334                     if var.tuple_variant:
1335                         out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1336                     else:
1337                         out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1338                 out_c += "}\n"
1339                 out_java += self.fn_call_body(fn_name, field_map.c_ty, field_map.java_ty, "ptr: bigint", "ptr")
1340         out_java_enum += java_hu_class
1341         self.struct_file_suffixes[java_hu_type] = java_hu_subclasses
1342         self.obj_defined([java_hu_type], "structs")
1343         return (out_java, out_java_enum, out_c)
1344
1345     def map_opaque_struct(self, struct_name, struct_doc_comment):
1346         method_header = ""
1347
1348         hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1349         out_opaque_struct_human = f"{self.hu_struct_file_prefix}"
1350         constructor_body = "super(ptr, bindings." + struct_name.replace("LDK","") + "_free);"
1351         extra_docs = ""
1352         extra_body = ""
1353         if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1354             extra_docs = "\n * This type represents a lock and MUST BE MANUALLY FREE'd!"
1355             constructor_body = 'super(ptr, () => { throw new Error("Locks must be manually freed with free()"); });'
1356             extra_body = f"""
1357         /** Releases this lock */
1358         public free() {{
1359                 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
1360                 CommonBase.set_null_skip_free(this);
1361         }}"""
1362         formatted_doc_comment = struct_doc_comment.replace("\n", "\n * ")
1363         out_opaque_struct_human += f"""
1364 /**{extra_docs}
1365  * {formatted_doc_comment}
1366  */
1367 export class {hu_name} extends CommonBase {{
1368         /* @internal */
1369         public constructor(_dummy: null, ptr: bigint) {{
1370                 {constructor_body}
1371         }}{extra_body}
1372
1373 """
1374         self.obj_defined([hu_name], "structs")
1375         return out_opaque_struct_human
1376
1377     def map_tuple(self, struct_name):
1378         return self.map_opaque_struct(struct_name, "A Tuple")
1379
1380     def map_result(self, struct_name, res_map, err_map):
1381         human_ty = struct_name.replace("LDKCResult", "Result")
1382
1383         suffixes = f"export class {human_ty}_OK extends {human_ty} {{\n"
1384         if res_map.java_hu_ty != "void":
1385             suffixes += "\tpublic res: " + res_map.java_hu_ty + ";\n"
1386         suffixes += f"""
1387         /* @internal */
1388         public constructor(_dummy: null, ptr: bigint) {{
1389                 super(_dummy, ptr);
1390 """
1391         if res_map.java_hu_ty == "void":
1392             pass
1393         elif res_map.to_hu_conv is not None:
1394             suffixes += "\t\tconst res: " + res_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1395             suffixes += "\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t")
1396             suffixes += "\n\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1397         else:
1398             suffixes += "\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1399         suffixes += "\t}\n}\n"
1400
1401         suffixes += f"export class {human_ty}_Err extends {human_ty} {{\n"
1402         if err_map.java_hu_ty != "void":
1403             suffixes += "\tpublic err: " + err_map.java_hu_ty + ";\n"
1404         suffixes += f"""
1405         /* @internal */
1406         public constructor(_dummy: null, ptr: bigint) {{
1407                 super(_dummy, ptr);
1408 """
1409         if err_map.java_hu_ty == "void":
1410             pass
1411         elif err_map.to_hu_conv is not None:
1412             suffixes += "\t\tconst err: " + err_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1413             suffixes += "\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t")
1414             suffixes += "\n\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1415         else:
1416             suffixes += "\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1417         suffixes += "\t}\n}"
1418
1419         self.struct_file_suffixes[human_ty] = suffixes
1420         self.obj_defined([human_ty], "structs")
1421
1422         return f"""{self.hu_struct_file_prefix}
1423
1424 export class {human_ty} extends CommonBase {{
1425         protected constructor(_dummy: null, ptr: bigint) {{
1426                 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1427         }}
1428         /* @internal */
1429         public static constr_from_ptr(ptr: bigint): {human_ty} {{
1430                 if (bindings.{struct_name.replace("LDK", "")}_is_ok(ptr)) {{
1431                         return new {human_ty}_OK(null, ptr);
1432                 }} else {{
1433                         return new {human_ty}_Err(null, ptr);
1434                 }}
1435         }}
1436 """
1437
1438     def fn_call_body(self, method_name, return_c_ty, return_java_ty, method_argument_string, native_call_argument_string):
1439         has_return_value = return_c_ty != 'void'
1440         return_statement = 'return nativeResponseValue;'
1441         if not has_return_value:
1442             return_statement = '// debug statements here'
1443
1444         return f"""/* @internal */
1445 export function {method_name}({method_argument_string}): {return_java_ty} {{
1446         if(!isWasmInitialized) {{
1447                 throw new Error("initializeWasm() must be awaited first!");
1448         }}
1449         const nativeResponseValue = wasm.TS_{method_name}({native_call_argument_string});
1450         {return_statement}
1451 }}
1452 """
1453     def map_function(self, argument_types, c_call_string, method_name, meth_n, return_type_info, struct_meth, default_constructor_args, takes_self, takes_self_as_ref, args_known, type_mapping_generator, doc_comment):
1454         out_java = ""
1455         out_c = ""
1456         out_java_struct = None
1457
1458         out_java += ("\t")
1459         out_c += (self.c_fn_ty_pfx)
1460         out_c += (return_type_info.c_ty)
1461         out_java += (return_type_info.java_ty)
1462         if return_type_info.ret_conv is not None:
1463             ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1464         out_java += (" " + method_name + "(")
1465         out_c += (" "  + self.c_fn_name_define_pfx(method_name, True))
1466
1467         method_argument_string = ""
1468         native_call_argument_string = ""
1469         for idx, arg_conv_info in enumerate(argument_types):
1470             if idx != 0:
1471                 method_argument_string += (", ")
1472                 native_call_argument_string += ', '
1473                 out_c += (", ")
1474             if arg_conv_info.c_ty != "void":
1475                 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1476                 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1477                 native_call_argument_string += arg_conv_info.arg_name
1478         out_java = self.fn_call_body(method_name, return_type_info.c_ty, return_type_info.java_ty, method_argument_string, native_call_argument_string)
1479
1480         out_java_struct = ""
1481         if doc_comment is not None:
1482             out_java_struct = "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1483
1484         if not args_known:
1485             out_java_struct += ("\t// Skipped " + method_name + "\n")
1486         else:
1487             if not takes_self:
1488                 out_java_struct += (
1489                         "\tpublic static constructor_" + meth_n + "(")
1490             else:
1491                 out_java_struct += ("\tpublic " + meth_n + "(")
1492             for idx, arg in enumerate(argument_types):
1493                 if idx != 0:
1494                     if not takes_self or idx > 1:
1495                         out_java_struct += (", ")
1496                 elif takes_self:
1497                     continue
1498                 if arg.java_ty != "void":
1499                     if arg.arg_name in default_constructor_args:
1500                         for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1501                             if explode_idx != 0:
1502                                 out_java_struct += (", ")
1503                             out_java_struct += arg.arg_name + "_" + explode_arg.arg_name + ": " + explode_arg.java_hu_ty
1504                     else:
1505                         out_java_struct += arg.arg_name + ": " + arg.java_hu_ty
1506                         if arg.nullable:
1507                             out_java_struct += "|null"
1508
1509         out_c += (") {\n")
1510         if out_java_struct is not None:
1511             out_java_struct += "): " + return_type_info.java_hu_ty + " {\n"
1512         for info in argument_types:
1513             if info.arg_conv is not None:
1514                 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1515         if return_type_info.ret_conv is not None:
1516             out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1517         elif return_type_info.c_ty != "void":
1518             out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1519         else:
1520             out_c += ("\t")
1521         if c_call_string is None:
1522             out_c += (method_name + "(")
1523         else:
1524             out_c += (c_call_string)
1525         for idx, info in enumerate(argument_types):
1526             if info.arg_conv_name is not None:
1527                 if idx != 0:
1528                     out_c += (", ")
1529                 elif c_call_string is not None:
1530                     continue
1531                 out_c += (info.arg_conv_name)
1532         out_c += (")")
1533         if return_type_info.ret_conv is not None:
1534             out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1535         else:
1536             out_c += (";")
1537         for info in argument_types:
1538             if info.arg_conv_cleanup is not None:
1539                 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1540         if return_type_info.ret_conv is not None:
1541             out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1542         elif return_type_info.c_ty != "void":
1543             out_c += ("\n\treturn ret_val;")
1544         out_c += ("\n}\n\n")
1545
1546         if args_known:
1547             out_java_struct += ("\t\t")
1548             if return_type_info.java_ty != "void":
1549                 out_java_struct += "const ret: " + return_type_info.java_ty + " = "
1550             out_java_struct += ("bindings." + method_name + "(")
1551             for idx, info in enumerate(argument_types):
1552                 if idx != 0:
1553                     out_java_struct += (", ")
1554                 if idx == 0 and takes_self:
1555                     out_java_struct += ("this.ptr")
1556                 elif info.arg_name in default_constructor_args:
1557                     out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1558                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1559                         if explode_idx != 0:
1560                             out_java_struct += (", ")
1561                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1562                         if explode_arg.from_hu_conv is not None:
1563                             out_java_struct += (
1564                                 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1565                         else:
1566                             out_java_struct += (expl_arg_name)
1567                     out_java_struct += (")")
1568                 elif info.from_hu_conv is not None:
1569                     out_java_struct += (info.from_hu_conv[0])
1570                 else:
1571                     out_java_struct += (info.arg_name)
1572             out_java_struct += (");\n")
1573             if return_type_info.to_hu_conv is not None:
1574                 if not takes_self:
1575                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1576                                                                                                              return_type_info.to_hu_conv_name) + "\n")
1577                 else:
1578                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1579
1580             for idx, info in enumerate(argument_types):
1581                 if idx == 0 and takes_self:
1582                     pass
1583                 elif info.arg_name in default_constructor_args:
1584                     for explode_arg in default_constructor_args[info.arg_name]:
1585                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1586                         if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1587                             out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1588                                                                                              expl_arg_name).replace(
1589                                 "this", return_type_info.to_hu_conv_name) + ";\n")
1590                 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1591                     if not takes_self and return_type_info.to_hu_conv_name is not None:
1592                         out_java_struct += (
1593                                 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1594                     else:
1595                         out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1596
1597             if return_type_info.to_hu_conv_name is not None:
1598                 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1599             elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1600                 out_java_struct += ("\t\treturn ret;\n")
1601             out_java_struct += ("\t}\n\n")
1602
1603         return (out_java, out_c, out_java_struct)
1604
1605     def cleanup(self):
1606         for struct in self.struct_file_suffixes:
1607             with open(self.outdir + "/structs/" + struct + self.file_ext, "a") as src:
1608                 src.write(self.struct_file_suffixes[struct])
1609
1610         with open(self.outdir + "/bindings.mts", "a") as bindings:
1611             bindings.write("""
1612
1613 js_invoke = function(obj_ptr: number, fn_id: number, arg1: bigint|number, arg2: bigint|number, arg3: bigint|number, arg4: bigint|number, arg5: bigint|number, arg6: bigint|number, arg7: bigint|number, arg8: bigint|number, arg9: bigint|number, arg10: bigint|number) {
1614         const weak: WeakRef<object>|undefined = js_objs[obj_ptr];
1615         if (weak == null || weak == undefined) {
1616                 console.error("Got function call on unknown/free'd JS object!");
1617                 throw new Error("Got function call on unknown/free'd JS object!");
1618         }
1619         const obj = weak.deref();
1620         if (obj == null || obj == undefined) {
1621                 console.error("Got function call on GC'd JS object!");
1622                 throw new Error("Got function call on GC'd JS object!");
1623         }
1624         var fn;
1625 """)
1626             bindings.write("\tswitch (fn_id) {\n")
1627             for f in self.function_ptrs:
1628                 bindings.write(f"\t\tcase {str(f)}: fn = Object.getOwnPropertyDescriptor(obj, \"{self.function_ptrs[f][1]}\"); break;\n")
1629
1630             bindings.write("""\t\tdefault:
1631                         console.error("Got unknown function call from C!");
1632                         throw new Error("Got unknown function call from C!");
1633         }
1634         if (fn == null || fn == undefined) {
1635                 console.error("Got function call on incorrect JS object!");
1636                 throw new Error("Got function call on incorrect JS object!");
1637         }
1638         const ret = fn.value.bind(obj)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
1639         if (ret === undefined || ret === null) return BigInt(0);
1640         return BigInt(ret);
1641 }""")