Update CI references to 0.0.122
[ldk-java] / typescript_strings.py
index cc7b236315c6be51e1f593b74f3a04be3916fb4f..afb2b67f69cc3e99db4a69de29b34521e8383f51 100644 (file)
@@ -17,10 +17,13 @@ class Consts:
         self.function_ptr_counter = 0
         self.function_ptrs = {}
         self.c_type_map = dict(
+            bool = ['boolean', 'boolean', 'XXX'],
             uint8_t = ['number', 'number', 'Uint8Array'],
             uint16_t = ['number', 'number', 'Uint16Array'],
             uint32_t = ['number', 'number', 'Uint32Array'],
+            int64_t = ['bigint', 'bigint', 'BigInt64Array'],
             uint64_t = ['bigint', 'bigint', 'BigUint64Array'],
+            double = ['number', 'number', 'Float64Array'],
         )
         self.java_type_map = dict(
             String = "number"
@@ -53,7 +56,7 @@ imports.wasi_snapshot_preview1 = {
                for (var i = 0; i < iovec_array_len; i++) {
                        const bytes_view = new Uint8Array(wasm.memory.buffer, ptr_len_view[i*2], ptr_len_view[i*2+1]);
                        console.log("[fd " + fd + "]: " + String.fromCharCode(...bytes_view));
-                       bytes_written += ptr_len_view[i*2+1];
+                       bytes_written += ptr_len_view[i*2+1]!;
                }
                const written_view = new Uint32Array(wasm.memory.buffer, bytes_written_ptr, 1);
                written_view[0] = bytes_written;
@@ -82,7 +85,7 @@ imports.wasi_snapshot_preview1 = {
                out_len_view[0] = 0;
                return 0;
        },
-       "environ_get": (environ_ptr: number, environ_buf_ptr: number) => {
+       "environ_get": (_environ_ptr: number, _environ_buf_ptr: number) => {
                // This is called before fd_write to format + print panic messages,
                // but only if we have variables in environ_sizes_get, so shouldn't ever actually happen!
                console.log("wasi_snapshot_preview1:environ_get");
@@ -125,8 +128,8 @@ async function finishInitializeWasm(wasmInstance: WebAssembly.Instance) {
        isWasmInitialized = true;
 }
 
-const fn_list = ["uuuuuu", "buuuuu", "bbuuuu", "bbbuuu", "bbbbuu",
-       "bbbbbb", "ubuubu", "ubuuuu", "ubbuuu", "uubuuu", "uububu"];
+const fn_list = ["uuuuuu", "buuuuu", "bbuuuu", "bbbuuu", "bbbbuu", "bbbbbu",
+       "bbbbbb", "ubuubu", "ubuuuu", "ubbuuu", "uubuuu", "uubbuu", "uububu", "ububuu"];
 
 /* @internal */
 export async function initializeWasmFromUint8Array(wasmBinary: Uint8Array) {
@@ -150,7 +153,7 @@ export async function initializeWasmFetch(uri: string) {
 export function uint5ArrToBytes(inputArray: Array<UInt5>): Uint8Array {
        const arr = new Uint8Array(inputArray.length);
        for (var i = 0; i < inputArray.length; i++) {
-               arr[i] = inputArray[i].getVal();
+               arr[i] = inputArray[i]!.getVal();
        }
        return arr;
 }
@@ -159,7 +162,7 @@ export function uint5ArrToBytes(inputArray: Array<UInt5>): Uint8Array {
 export function WitnessVersionArrToBytes(inputArray: Array<WitnessVersion>): Uint8Array {
        const arr = new Uint8Array(inputArray.length);
        for (var i = 0; i < inputArray.length; i++) {
-               arr[i] = inputArray[i].getVal();
+               arr[i] = inputArray[i]!.getVal();
        }
        return arr;
 }
@@ -167,7 +170,18 @@ export function WitnessVersionArrToBytes(inputArray: Array<WitnessVersion>): Uin
 
 
 /* @internal */
-export function encodeUint8Array (inputArray: Uint8Array): number {
+export function encodeUint128 (inputVal: bigint): number {
+       if (inputVal >= 0x10000000000000000000000000000000n) throw "U128s cannot exceed 128 bits";
+       const cArrayPointer = wasm.TS_malloc(16 + 8);
+       const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
+       arrayLengthView[0] = BigInt(16);
+       const arrayMemoryView = new Uint8Array(wasm.memory.buffer, cArrayPointer + 8, 16);
+       for (var i = 0; i < 16; i++) arrayMemoryView[i] = Number((inputVal >> BigInt(i)*8n) & 0xffn);
+       return cArrayPointer;
+}
+/* @internal */
+export function encodeUint8Array (inputArray: Uint8Array|null): number {
+       if (inputArray == null) return 0;
        const cArrayPointer = wasm.TS_malloc(inputArray.length + 8);
        const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
        arrayLengthView[0] = BigInt(inputArray.length);
@@ -176,7 +190,18 @@ export function encodeUint8Array (inputArray: Uint8Array): number {
        return cArrayPointer;
 }
 /* @internal */
-export function encodeUint32Array (inputArray: Uint32Array|Array<number>): number {
+export function encodeUint16Array (inputArray: Uint16Array|Array<number>|null): number {
+       if (inputArray == null) return 0;
+       const cArrayPointer = wasm.TS_malloc((inputArray.length + 4) * 2);
+       const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
+       arrayLengthView[0] = BigInt(inputArray.length);
+       const arrayMemoryView = new Uint16Array(wasm.memory.buffer, cArrayPointer + 8, inputArray.length);
+       arrayMemoryView.set(inputArray);
+       return cArrayPointer;
+}
+/* @internal */
+export function encodeUint32Array (inputArray: Uint32Array|Array<number>|null): number {
+       if (inputArray == null) return 0;
        const cArrayPointer = wasm.TS_malloc((inputArray.length + 2) * 4);
        const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
        arrayLengthView[0] = BigInt(inputArray.length);
@@ -185,28 +210,50 @@ export function encodeUint32Array (inputArray: Uint32Array|Array<number>): numbe
        return cArrayPointer;
 }
 /* @internal */
-export function encodeUint64Array (inputArray: BigUint64Array|Array<bigint>): number {
+export function encodeUint64Array (inputArray: BigUint64Array|Array<bigint>|null): number {
+       if (inputArray == null) return 0;
        const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 8);
-       const arrayMemoryView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
-       arrayMemoryView.set(inputArray, 1);
+       const arrayMemoryView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, inputArray.length + 1);
        arrayMemoryView[0] = BigInt(inputArray.length);
+       arrayMemoryView.set(inputArray, 1);
        return cArrayPointer;
 }
 
 /* @internal */
-export function check_arr_len(arr: Uint8Array, len: number): Uint8Array {
-       if (arr.length != len) { throw new Error("Expected array of length " + len + " got " + arr.length); }
+export function check_arr_len(arr: Uint8Array|null, len: number): Uint8Array|null {
+       if (arr !== null && arr.length != len) { throw new Error("Expected array of length " + len + " got " + arr.length); }
+       return arr;
+}
+
+/* @internal */
+export function check_16_arr_len(arr: Uint16Array|null, len: number): Uint16Array|null {
+       if (arr !== null && arr.length != len) { throw new Error("Expected array of length " + len + " got " + arr.length); }
        return arr;
 }
 
 /* @internal */
 export function getArrayLength(arrayPointer: number): number {
        const arraySizeViewer = new BigUint64Array(wasm.memory.buffer, arrayPointer, 1);
-       const len = arraySizeViewer[0];
+       const len = arraySizeViewer[0]!;
        if (len >= (2n ** 32n)) throw new Error("Bogus Array Size");
        return Number(len % (2n ** 32n));
 }
 /* @internal */
+export function decodeUint128 (arrayPointer: number, free = true): bigint {
+       const arraySize = getArrayLength(arrayPointer);
+       if (arraySize != 16) throw "Need 16 bytes for a uint128";
+       const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, arraySize);
+       var val = 0n;
+       for (var i = 0; i < 16; i++) {
+               val <<= 8n;
+               val |= BigInt(actualArrayViewer[i]!);
+       }
+       if (free) {
+               wasm.TS_free(arrayPointer);
+       }
+       return val;
+}
+/* @internal */
 export function decodeUint8Array (arrayPointer: number, free = true): Uint8Array {
        const arraySize = getArrayLength(arrayPointer);
        const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, arraySize);
@@ -219,15 +266,13 @@ export function decodeUint8Array (arrayPointer: number, free = true): Uint8Array
        }
        return actualArray;
 }
-const decodeUint32Array = (arrayPointer: number, free = true) => {
+/* @internal */
+export function decodeUint16Array (arrayPointer: number, free = true): Uint16Array {
        const arraySize = getArrayLength(arrayPointer);
-       const actualArrayViewer = new Uint32Array(
-               wasm.memory.buffer, // value
-               arrayPointer + 8, // offset (ignoring length bytes)
-               arraySize // uint32 count
-       );
+       const actualArrayViewer = new Uint16Array(wasm.memory.buffer, arrayPointer + 8, arraySize);
        // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
        // will free the underlying memory when it becomes unreachable instead of copying here.
+       // Note that doing so may have edge-case interactions with memory resizing (invalidating the buffer).
        const actualArray = actualArrayViewer.slice(0, arraySize);
        if (free) {
                wasm.TS_free(arrayPointer);
@@ -257,19 +302,19 @@ export function freeWasmMemory(pointer: number) { wasm.TS_free(pointer); }
 /* @internal */
 export function getU64ArrayElem(arrayPointer: number, idx: number): bigint {
        const actualArrayViewer = new BigUint64Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
-       return actualArrayViewer[idx];
+       return actualArrayViewer[idx]!;
 }
 
 /* @internal */
 export function getU32ArrayElem(arrayPointer: number, idx: number): number {
        const actualArrayViewer = new Uint32Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
-       return actualArrayViewer[idx];
+       return actualArrayViewer[idx]!;
 }
 
 /* @internal */
 export function getU8ArrayElem(arrayPointer: number, idx: number): number {
        const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
-       return actualArrayViewer[idx];
+       return actualArrayViewer[idx]!;
 }
 
 
@@ -318,14 +363,13 @@ export async function initializeWasmFromBinary(bin: Uint8Array) {
        await initializeWasmFromUint8Array(bin);
 }
 
+export * from './structs/UtilMethods.mjs';
 """)
 
         self.bindings_version_file = """export function get_ldk_java_bindings_version(): String {
        return "<git_version_ldk_garbagecollected>";
 }"""
 
-        self.bindings_footer = ""
-
         self.common_base = """
 function freer(f: () => void) { f() }
 const finalizer = new FinalizationRegistry(freer);
@@ -347,8 +391,8 @@ export class CommonBase {
        // In Java, protected means "any subclass can access fields on any other subclass'"
        // In TypeScript, protected means "any subclass can access parent fields on instances of itself"
        // To work around this, we add accessors for other instances' protected fields here.
-       protected static add_ref_from(holder: CommonBase, referent: object) {
-               if (holder !== null) { holder.ptrs_to.push(referent); }
+       protected static add_ref_from(holder: CommonBase|null, referent: object|null) {
+               if (holder !== null && referent !== null) { holder.ptrs_to.push(referent); }
        }
        protected static get_ptr_of(o: CommonBase) {
                return o.ptr;
@@ -381,7 +425,7 @@ export class WitnessVersion {
 }
 
 export class UnqualifiedError {
-       public constructor(val: number) {}
+       public constructor(_val: number) {}
 }
 """
 
@@ -392,7 +436,7 @@ export class UnqualifiedError {
        public value: bigint;
 
        /* @internal */
-       public constructor(_dummy: object, ptr: bigint) {
+       public constructor(_dummy: null, ptr: bigint) {
                super(ptr, bindings.TxOut_free);
                this.script_pubkey = bindings.decodeUint8Array(bindings.TxOut_get_script_pubkey(ptr));
                this.value = bindings.TxOut_get_value(ptr);
@@ -403,6 +447,70 @@ export class UnqualifiedError {
 }"""
         self.obj_defined(["TxOut"], "structs")
 
+        self.txin_defn = """export class TxIn extends CommonBase {
+       /** The witness in this input, in serialized form */
+       public witness: Uint8Array;
+       /** The script_sig in this input */
+       public script_sig: Uint8Array;
+       /** The transaction output's sequence number */
+       public sequence: number;
+       /** The txid this input is spending */
+       public previous_txid: Uint8Array;
+       /** The output index within the spent transaction of the output this input is spending */
+       public previous_vout: number;
+
+       /* @internal */
+       public constructor(_dummy: null, ptr: bigint) {
+               super(ptr, bindings.TxIn_free);
+               this.witness = bindings.decodeUint8Array(bindings.TxIn_get_witness(ptr));
+               this.script_sig = bindings.decodeUint8Array(bindings.TxIn_get_script_sig(ptr));
+               this.sequence = bindings.TxIn_get_sequence(ptr);
+               this.previous_txid = bindings.decodeUint8Array(bindings.TxIn_get_previous_txid(ptr));
+               this.previous_vout = bindings.TxIn_get_previous_vout(ptr);
+       }
+    public static constructor_new(witness: Uint8Array, script_sig: Uint8Array, sequence: number, previous_txid: Uint8Array, previous_vout: number): TxIn {
+               return new TxIn(null, bindings.TxIn_new(bindings.encodeUint8Array(witness), bindings.encodeUint8Array(script_sig), sequence, bindings.encodeUint8Array(previous_txid), previous_vout));
+       }
+}"""
+        self.obj_defined(["TxIn"], "structs")
+
+        self.scalar_defn = """export class BigEndianScalar extends CommonBase {
+       /** The bytes of the scalar value, in big endian */
+       public scalar_bytes: Uint8Array;
+
+       /* @internal */
+       public constructor(_dummy: null, ptr: bigint) {
+               super(ptr, bindings.BigEndianScalar_free);
+               this.scalar_bytes = bindings.decodeUint8Array(bindings.BigEndianScalar_get_bytes(ptr));
+       }
+       public static constructor_new(scalar_bytes: Uint8Array): BigEndianScalar {
+               return new BigEndianScalar(null, bindings.BigEndianScalar_new(bindings.encodeUint8Array(scalar_bytes)));
+       }
+}"""
+        self.obj_defined(["BigEndianScalar"], "structs")
+
+        self.witness_program_defn = """export class WitnessProgram extends CommonBase {
+       /** The witness program bytes themselves */
+       public program: Uint8Array;
+       /** The witness program version */
+       public version: WitnessVersion;
+
+       /* @internal */
+       public constructor(_dummy: null, ptr: bigint) {
+               super(ptr, bindings.WitnessProgram_free);
+               this.program = bindings.decodeUint8Array(bindings.WitnessProgram_get_program(ptr));
+               this.version = new WitnessVersion(bindings.WitnessProgram_get_version(ptr));
+       }
+       public static constructor_new(program: Uint8Array, version: WitnessVersion): WitnessProgram {
+               if (program.length < 2 || program.length > 40)
+                       throw new Error("WitnessProgram must be between 2 and 40 bytes long");
+               if (version.getVal() == 0 && program.length != 20 && program.length != 32)
+                       throw new Error("WitnessProgram for version 0 must be between either 20 or 30 bytes");
+               return new WitnessProgram(null, bindings.WitnessProgram_new(version.getVal(), bindings.encodeUint8Array(program)));
+       }
+}"""
+        self.obj_defined(["WitnessProgram"], "structs")
+
         self.c_file_pfx = """#include "js-wasm.h"
 #include <stdatomic.h>
 #include <lightning.h>
@@ -601,6 +709,7 @@ _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
 DECL_ARR_TYPE(int64_t, int64_t);
 DECL_ARR_TYPE(uint64_t, uint64_t);
 DECL_ARR_TYPE(int8_t, int8_t);
+DECL_ARR_TYPE(int16_t, int16_t);
 DECL_ARR_TYPE(uint32_t, uint32_t);
 DECL_ARR_TYPE(void*, ptr);
 DECL_ARR_TYPE(char, char);
@@ -654,35 +763,45 @@ import { CommonBase, UInt5, WitnessVersion, UnqualifiedError } from './CommonBas
 import * as bindings from '../bindings.mjs'
 
 """
+        self.hu_struct_file_suffix = ""
         self.util_fn_pfx = self.hu_struct_file_prefix + "\nexport class UtilMethods extends CommonBase {\n"
         self.util_fn_sfx = "}"
         self.c_fn_ty_pfx = ""
         self.file_ext = ".mts"
         self.ptr_c_ty = "uint64_t"
         self.ptr_native_ty = "bigint"
+        self.u128_native_ty = "bigint"
         self.usize_c_ty = "uint32_t"
         self.usize_native_ty = "number"
         self.native_zero_ptr = "0n"
-        self.result_c_ty = "uint32_t"
+        self.unitary_enum_c_ty = "uint32_t"
         self.ptr_arr = "ptrArray"
         self.is_arr_some_check = ("", " != 0")
         self.get_native_arr_len_call = ("", "->arr_len")
 
+    def bindings_footer(self):
+        return ""
+
     def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
         return None
     def create_native_arr_call(self, arr_len, ty_info):
         if ty_info.c_ty == "ptrArray":
-            assert ty_info.rust_obj == "LDKCVec_u5Z" or (ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array"))
+            assert ty_info.rust_obj == "LDKCVec_U5Z" or (ty_info.subty is not None and (ty_info.subty.c_ty.endswith("Array") or ty_info.subty.rust_obj == "LDKStr"))
         return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
         if ty_info.c_ty == "int8_tArray":
             return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
+        elif ty_info.c_ty == "int16_tArray":
+            return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + " * 2)")
         else:
             assert False
     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
-        if ty_info.c_ty == "int8_tArray":
+        if ty_info.c_ty == "int8_tArray" or ty_info.c_ty == "int16_tArray":
             if copy:
-                return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + arr_len + "); FREE(" + arr_name + ")"
+                byte_len = arr_len
+                if ty_info.c_ty == "int16_tArray":
+                    byte_len = arr_len + " * 2"
+                return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + byte_len + "); FREE(" + arr_name + ")"
         assert not copy
         if ty_info.c_ty == "ptrArray":
             return "(void*) " + arr_name + "->elems"
@@ -702,11 +821,14 @@ import * as bindings from '../bindings.mjs'
         else:
             return "FREE(" + arr_name + ")"
 
-    def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty):
-        if elem_ty.rust_obj == "LDKu5":
+    def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty, is_nullable):
+        if elem_ty.rust_obj == "LDKU5":
             return arr_name + " != null ? bindings.uint5ArrToBytes(" + arr_name + ") : null"
-        assert elem_ty.c_ty == "uint64_t" or elem_ty.c_ty.endswith("Array")
-        return arr_name + " != null ? " + arr_name + ".map(" + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
+        assert elem_ty.c_ty == "uint64_t" or elem_ty.c_ty.endswith("Array") or elem_ty.rust_obj == "LDKStr"
+        if is_nullable:
+            return arr_name + " != null ? " + arr_name + ".map(" + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
+        else:
+            return arr_name + ".map(" + conv_name + " => " + elem_ty.from_hu_conv[0] + ")"
 
     def str_ref_to_native_call(self, var_name, str_len):
         return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
@@ -730,8 +852,10 @@ import * as bindings from '../bindings.mjs'
             return "bindings.getU32ArrayElem(" + arr_name + ", " + idx + ")"
         elif elem_ty.c_ty == "uint64_t":
             return "bindings.getU64ArrayElem(" + arr_name + ", " + idx + ")"
-        elif elem_ty.rust_obj == "LDKu5":
+        elif elem_ty.rust_obj == "LDKU5":
             return "bindings.getU8ArrayElem(" + arr_name + ", " + idx + ")"
+        elif elem_ty.rust_obj == "LDKStr":
+            return "bindings.getU32ArrayElem(" + arr_name + ", " + idx + ")"
         else:
             assert False
     def constr_hu_array(self, ty_info, arr_len):
@@ -739,16 +863,23 @@ import * as bindings from '../bindings.mjs'
     def cleanup_converted_native_array(self, ty_info, arr_name):
         return "bindings.freeWasmMemory(" + arr_name + ")"
 
-    def primitive_arr_from_hu(self, mapped_ty, fixed_len, arr_name):
+    def primitive_arr_from_hu(self, arr_ty, fixed_len, arr_name):
+        mapped_ty = arr_ty.subty
         inner = arr_name
+        if arr_ty.rust_obj == "LDKU128":
+            return ("bindings.encodeUint128(" + inner + ")", "")
         if fixed_len is not None:
-            assert mapped_ty.c_ty == "int8_t"
-            inner = "bindings.check_arr_len(" + arr_name + ", " + fixed_len + ")"
+            if mapped_ty.c_ty == "int8_t":
+                inner = "bindings.check_arr_len(" + arr_name + ", " + fixed_len + ")"
+            elif mapped_ty.c_ty == "int16_t":
+                inner = "bindings.check_16_arr_len(" + arr_name + ", " + fixed_len + ")"
         if mapped_ty.c_ty.endswith("Array"):
             return ("bindings.encodeUint32Array(" + inner + ")", "")
         elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
             return ("bindings.encodeUint8Array(" + inner + ")", "")
-        elif mapped_ty.c_ty == "uint32_t":
+        elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
+            return ("bindings.encodeUint16Array(" + inner + ")", "")
+        elif mapped_ty.c_ty == "uint32_t" or mapped_ty.rust_obj == "LDKStr":
             return ("bindings.encodeUint32Array(" + inner + ")", "")
         elif mapped_ty.c_ty == "int64_t" or mapped_ty.c_ty == "uint64_t":
             return ("bindings.encodeUint64Array(" + inner + ")", "")
@@ -756,9 +887,14 @@ import * as bindings from '../bindings.mjs'
             print(mapped_ty.c_ty)
             assert False
 
-    def primitive_arr_to_hu(self, mapped_ty, fixed_len, arr_name, conv_name):
-        if mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
+    def primitive_arr_to_hu(self, arr_ty, fixed_len, arr_name, conv_name):
+        mapped_ty = arr_ty.subty
+        if arr_ty.rust_obj == "LDKU128":
+            return "const " + conv_name + ": bigint = bindings.decodeUint128(" + arr_name + ");"
+        elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
             return "const " + conv_name + ": Uint8Array = bindings.decodeUint8Array(" + arr_name + ");"
+        elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
+            return "const " + conv_name + ": Uint16Array = bindings.decodeUint16Array(" + arr_name + ");"
         elif mapped_ty.c_ty == "uint64_t" or mapped_ty.c_ty == "int64_t":
             return "const " + conv_name + ": bigint[] = bindings.decodeUint64Array(" + arr_name + ");"
         else:
@@ -848,7 +984,6 @@ export enum {struct_name} {{
         for var in flattened_field_var_conversions:
             if isinstance(var, ConvInfo):
                 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
-                super_instantiator += first_to_lower(var.arg_name) + ", "
                 if var.from_hu_conv is not None:
                     bindings_instantiator += ", " + var.from_hu_conv[0]
                     if var.from_hu_conv[1] != "":
@@ -856,8 +991,7 @@ export enum {struct_name} {{
                 else:
                     bindings_instantiator += ", " + first_to_lower(var.arg_name)
             else:
-                bindings_instantiator += ", " + first_to_lower(var[1]) + ".bindings_instance"
-                super_instantiator += first_to_lower(var[1]) + "_impl, "
+                bindings_instantiator += ", " + first_to_lower(var[1]) + ".instance_idx!"
                 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
                 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}Interface"
 
@@ -867,12 +1001,21 @@ export enum {struct_name} {{
             if isinstance(var, ConvInfo):
                 trait_constructor_arguments += ", " + var.arg_name
             else:
-                super_constructor_statements += "\t\tconst " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + super_instantiator + ");\n"
-                trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".bindings_instance"
+                super_constructor_statements += "\t\tconst " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + first_to_lower(var[1]) + "_impl"
+                super_instantiator = ""
+                for suparg in var[2]:
+                    if isinstance(suparg, ConvInfo):
+                        super_instantiator += ", " + suparg.arg_name
+                    else:
+                        super_instantiator += ", " + first_to_lower(suparg[1]) + "_impl"
+                super_constructor_statements += super_instantiator + ");\n"
+                trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".instance_idx!"
                 for suparg in var[2]:
                     if isinstance(suparg, ConvInfo):
                         trait_constructor_arguments += ", " + suparg.arg_name
                     else:
+                        # Blindly assume that we can just strip the first arg to build the args for the supertrait
+                        super_constructor_statements += "\t\tconst " + first_to_lower(suparg[1]) + " = " + suparg[1] + ".new_impl(" + super_instantiator.split(", ", 1)[1] + ");\n"
                         trait_constructor_arguments += ", " + suparg[1]
 
         # BUILD INTERFACE METHODS
@@ -940,7 +1083,7 @@ export interface {struct_name.replace("LDK", "")}Interface {{
 {out_java_interface}}}
 
 class {struct_name}Holder {{
-       held: {struct_name.replace("LDK", "")};
+       held: {struct_name.replace("LDK", "")}|null = null;
 }}
 
 /**
@@ -948,10 +1091,13 @@ class {struct_name}Holder {{
  */
 export class {struct_name.replace("LDK","")} extends CommonBase {{
        /* @internal */
-       public bindings_instance?: bindings.{struct_name};
+       public bindings_instance: bindings.{struct_name}|null;
+
+       /* @internal */
+       public instance_idx?: number;
 
        /* @internal */
-       constructor(_dummy: object, ptr: bigint) {{
+       constructor(_dummy: null, ptr: bigint) {{
                super(ptr, bindings.{struct_name.replace("LDK","")}_free);
                this.bindings_instance = null;
        }}
@@ -961,11 +1107,12 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
                const impl_holder: {struct_name}Holder = new {struct_name}Holder();
                let structImplementation = {{
 {out_interface_implementation_overrides}               }} as bindings.{struct_name};
-{super_constructor_statements}         const ptr: bigint = bindings.{struct_name}_new(structImplementation{bindings_instantiator});
+{super_constructor_statements}         const ptr_idx: [bigint, number] = bindings.{struct_name}_new(structImplementation{bindings_instantiator});
 
-               impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr);
+               impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr_idx[0]);
+               impl_holder.held.instance_idx = ptr_idx[1];
                impl_holder.held.bindings_instance = structImplementation;
-{pointer_to_adder}             return impl_holder.held;
+{pointer_to_adder}             return impl_holder.held!;
        }}
 
 """
@@ -986,14 +1133,18 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
 
         out_typescript_bindings += "}\n\n"
 
+        c_call_extra_args = ""
         out_typescript_bindings += f"/* @internal */\nexport function {struct_name}_new(impl: {struct_name}"
         for var in flattened_field_var_conversions:
             if isinstance(var, ConvInfo):
                 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
+                c_call_extra_args += f", {var.arg_name}"
             else:
-                out_typescript_bindings += f", {var[1]}: {var[0]}"
+                out_typescript_bindings += f", {var[1]}: number"
+                c_call_extra_args += f", {var[1]}"
 
-        out_typescript_bindings += f"""): bigint {{
+
+        out_typescript_bindings += f"""): [bigint, number] {{
        if(!isWasmInitialized) {{
                throw new Error("initializeWasm() must be awaited first!");
        }}
@@ -1002,7 +1153,7 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
                if (js_objs[i] == null || js_objs[i] == undefined) {{ new_obj_idx = i; break; }}
        }}
        js_objs[i] = new WeakRef(impl);
-       return wasm.TS_{struct_name}_new(i);
+       return [wasm.TS_{struct_name}_new(i{c_call_extra_args}), i];
 }}
 """
 
@@ -1049,7 +1200,7 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
                         out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
 
                 fn_suffix = ""
-                assert len(fn_line.args_ty) < 6
+                assert len(fn_line.args_ty) < 7
                 for arg_info in fn_line.args_ty:
                     if arg_info.c_ty == "uint64_t" or arg_info.c_ty == "int64_t":
                         fn_suffix += "b"
@@ -1064,10 +1215,10 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
                     out_c = out_c + "\tjs_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
                 elif fn_line.ret_ty_info.java_hu_ty == "string":
                     out_c += "\tjstring ret = (jstring)js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
-                elif not fn_line.ret_ty_info.passed_as_ptr:
+                elif fn_line.ret_ty_info.arg_conv is None:
                     out_c += "\treturn js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
                 else:
-                    out_c += "\tuint32_t ret = js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
+                    out_c += "\tuint64_t ret = js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
 
                 self.function_ptrs[self.function_ptr_counter] = (struct_name, fn_line.fn_name)
                 self.function_ptr_counter += 1
@@ -1093,9 +1244,9 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
         out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
         out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
         out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
-        for var in field_var_conversions:
+        for var in flattened_field_var_conversions:
             if not isinstance(var, ConvInfo):
-                out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
+                out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[2].replace(".", "->") + "->refcnt, 1, memory_order_release);\n"
         out_c = out_c + "}\n"
 
         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (JSValue o"
@@ -1146,7 +1297,7 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
         out_c = out_c + "\t};\n"
         for var in flattened_field_var_conversions:
             if not isinstance(var, ConvInfo):
-                out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
+                out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[2] + ".this_arg;\n"
         out_c = out_c + "\treturn ret;\n"
         out_c = out_c + "}\n"
 
@@ -1188,7 +1339,7 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
 
         java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
         java_hu_class += "export class " + java_hu_type + " extends CommonBase {\n"
-        java_hu_class += "\tprotected constructor(_dummy: object, ptr: bigint) { super(ptr, bindings." + bindings_type + "_free); }\n"
+        java_hu_class += "\tprotected constructor(_dummy: null, ptr: bigint) { super(ptr, bindings." + bindings_type + "_free); }\n"
         java_hu_class += "\t/* @internal */\n"
         java_hu_class += f"\tpublic static constr_from_ptr(ptr: bigint): {java_hu_type} {{\n"
         java_hu_class += f"\t\tconst raw_ty: number = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
@@ -1236,7 +1387,7 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
                 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
                 out_c += f"\tassert(obj->tag == {struct_name}_{var.var_name});\n"
                 if field_map.ret_conv is not None:
-                    out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
+                    out_c += ("\t" + field_map.ret_conv[0].replace("\n", "\n\t"))
                     if var.tuple_variant:
                         out_c += "obj->" + camel_to_snake(var.var_name)
                     else:
@@ -1256,7 +1407,6 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
         return (out_java, out_java_enum, out_c)
 
     def map_opaque_struct(self, struct_name, struct_doc_comment):
-        implementations = ""
         method_header = ""
 
         hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
@@ -1278,9 +1428,9 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
 /**{extra_docs}
  * {formatted_doc_comment}
  */
-export class {hu_name} extends CommonBase {implementations}{{
+export class {hu_name} extends CommonBase {{
        /* @internal */
-       public constructor(_dummy: object, ptr: bigint) {{
+       public constructor(_dummy: null, ptr: bigint) {{
                {constructor_body}
        }}{extra_body}
 
@@ -1299,7 +1449,7 @@ export class {hu_name} extends CommonBase {implementations}{{
             suffixes += "\tpublic res: " + res_map.java_hu_ty + ";\n"
         suffixes += f"""
        /* @internal */
-       public constructor(_dummy: object, ptr: bigint) {{
+       public constructor(_dummy: null, ptr: bigint) {{
                super(_dummy, ptr);
 """
         if res_map.java_hu_ty == "void":
@@ -1317,7 +1467,7 @@ export class {hu_name} extends CommonBase {implementations}{{
             suffixes += "\tpublic err: " + err_map.java_hu_ty + ";\n"
         suffixes += f"""
        /* @internal */
-       public constructor(_dummy: object, ptr: bigint) {{
+       public constructor(_dummy: null, ptr: bigint) {{
                super(_dummy, ptr);
 """
         if err_map.java_hu_ty == "void":
@@ -1336,7 +1486,7 @@ export class {hu_name} extends CommonBase {implementations}{{
         return f"""{self.hu_struct_file_prefix}
 
 export class {human_ty} extends CommonBase {{
-       protected constructor(_dummy: object, ptr: bigint) {{
+       protected constructor(_dummy: null, ptr: bigint) {{
                super(ptr, bindings.{struct_name.replace("LDK","")}_free);
        }}
        /* @internal */
@@ -1417,6 +1567,8 @@ export function {method_name}({method_argument_string}): {return_java_ty} {{
                             out_java_struct += arg.arg_name + "_" + explode_arg.arg_name + ": " + explode_arg.java_hu_ty
                     else:
                         out_java_struct += arg.arg_name + ": " + arg.java_hu_ty
+                        if arg.nullable:
+                            out_java_struct += "|null"
 
         out_c += (") {\n")
         if out_java_struct is not None:
@@ -1523,12 +1675,12 @@ export function {method_name}({method_argument_string}): {return_java_ty} {{
             bindings.write("""
 
 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) {
-       const weak: WeakRef<object> = js_objs[obj_ptr];
+       const weak: WeakRef<object>|undefined = js_objs[obj_ptr];
        if (weak == null || weak == undefined) {
                console.error("Got function call on unknown/free'd JS object!");
                throw new Error("Got function call on unknown/free'd JS object!");
        }
-       const obj: object = weak.deref();
+       const obj = weak.deref();
        if (obj == null || obj == undefined) {
                console.error("Got function call on GC'd JS object!");
                throw new Error("Got function call on GC'd JS object!");
@@ -1540,14 +1692,21 @@ js_invoke = function(obj_ptr: number, fn_id: number, arg1: bigint|number, arg2:
                 bindings.write(f"\t\tcase {str(f)}: fn = Object.getOwnPropertyDescriptor(obj, \"{self.function_ptrs[f][1]}\"); break;\n")
 
             bindings.write("""\t\tdefault:
-                       console.error("Got unknown function call from C!");
-                       throw new Error("Got unknown function call from C!");
+                       console.error("Got unknown function call with id " + fn_id + " from C!");
+                       throw new Error("Got unknown function call with id " + fn_id + " from C!");
        }
        if (fn == null || fn == undefined) {
-               console.error("Got function call on incorrect JS object!");
-               throw new Error("Got function call on incorrect JS object!");
+               console.error("Got function call with id " + fn_id + " on incorrect JS object: " + obj);
+               throw new Error("Got function call with id " + fn_id + " on incorrect JS object: " + obj);
+       }
+       var ret;
+       try {
+               ret = fn.value.bind(obj)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
+       } catch (e) {
+               console.error("Got an exception calling function with id " + fn_id + "! This is fatal.");
+               console.error(e);
+               throw e;
        }
-       const ret = fn.value.bind(obj)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
        if (ret === undefined || ret === null) return BigInt(0);
        return BigInt(ret);
 }""")