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