From 2f4eb38bce41bd2a2ba56c7e5d841c374011ecb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrei=20B=C4=83ncioiu?= Date: Mon, 27 May 2024 15:03:19 +0300 Subject: [PATCH] Native serializer: for option and optional, handle "undefined" the same as "null" values (missing). --- src/smartcontracts/nativeSerializer.spec.ts | 28 +++++++++++++++++++++ src/smartcontracts/nativeSerializer.ts | 4 +-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/smartcontracts/nativeSerializer.spec.ts b/src/smartcontracts/nativeSerializer.spec.ts index 221f7b05..72df6c90 100644 --- a/src/smartcontracts/nativeSerializer.spec.ts +++ b/src/smartcontracts/nativeSerializer.spec.ts @@ -430,6 +430,34 @@ describe("test native serializer", () => { assert.deepEqual(typedValues[1].valueOf(), []); }); + it("should accept null or undefined for option types and optionals", async () => { + const endpoint = AbiRegistry.create({ + endpoints: [ + { + name: "foo", + inputs: [ + { + type: "Option", + }, + { + type: "optional", + }, + ], + outputs: [], + }, + ], + }).getEndpoint("foo"); + + const typedValuesUsingNull = NativeSerializer.nativeToTypedValues([null, null], endpoint); + const typedValuesUsingUndefined = NativeSerializer.nativeToTypedValues([undefined, undefined], endpoint); + + assert.deepEqual(typedValuesUsingNull, typedValuesUsingUndefined); + assert.deepEqual(typedValuesUsingNull[0].getType(), new OptionType(new NullType())); + assert.deepEqual(typedValuesUsingNull[0].valueOf(), null); + assert.deepEqual(typedValuesUsingNull[1].getType(), new OptionalType(new U32Type())); + assert.deepEqual(typedValuesUsingNull[1].valueOf(), null); + }); + it("should perform type inference (enums)", async () => { const abiRegistry = AbiRegistry.create({ endpoints: [ diff --git a/src/smartcontracts/nativeSerializer.ts b/src/smartcontracts/nativeSerializer.ts index e99ed2db..568ae3d3 100644 --- a/src/smartcontracts/nativeSerializer.ts +++ b/src/smartcontracts/nativeSerializer.ts @@ -204,7 +204,7 @@ export namespace NativeSerializer { } function toOptionValue(native: any, type: Type, errorContext: ArgumentErrorContext): TypedValue { - if (native == null) { + if (native == null || native === undefined) { return OptionValue.newMissing(); } let converted = convertToTypedValue(native, type.getFirstTypeParameter(), errorContext); @@ -212,7 +212,7 @@ export namespace NativeSerializer { } function toOptionalValue(native: any, type: Type, errorContext: ArgumentErrorContext): TypedValue { - if (native == null) { + if (native == null || native === undefined) { return new OptionalValue(type); } let converted = convertToTypedValue(native, type.getFirstTypeParameter(), errorContext);