From da348ad8a3a1f4976fabfaa6415b69650c7050be Mon Sep 17 00:00:00 2001 From: Richard Moore Date: Mon, 24 Jul 2023 17:38:32 -0400 Subject: [PATCH] Return undefined for Contract properties that do not exist instead of throwing an error (#4266). --- src.ts/contract/contract.ts | 45 +++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/src.ts/contract/contract.ts b/src.ts/contract/contract.ts index 6d4df700ff..ba2a35733e 100644 --- a/src.ts/contract/contract.ts +++ b/src.ts/contract/contract.ts @@ -5,7 +5,7 @@ import { isAddressable, resolveAddress } from "../address/index.js"; import { copyRequest, Log, TransactionResponse } from "../providers/provider.js"; import { defineProperties, getBigInt, isCallException, isHexString, resolveProperties, - makeError, assert, assertArgument + isError, makeError, assert, assertArgument } from "../utils/index.js"; import { @@ -724,18 +724,21 @@ export class BaseContract implements Addressable, EventEmitterable { + get: (target, prop, receiver) => { // Pass important checks (like `then` for Promise) through - if (passProperties.indexOf(_prop) >= 0) { - return Reflect.get(target, _prop, receiver); + if (typeof(prop) === "symbol" || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); } - const prop = String(_prop); - - const result = this.getEvent(prop); - if (result) { return result; } + try { + return this.getEvent(prop); + } catch (error) { + if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") { + throw error; + } + } - throw new Error(`unknown contract event: ${ prop }`); + return undefined; }, has: (target, prop) => { // Pass important checks (like `then` for Promise) through @@ -754,24 +757,28 @@ export class BaseContract implements Addressable, EventEmitterable { - if (_prop in target || passProperties.indexOf(_prop) >= 0 || typeof(_prop) === "symbol") { - return Reflect.get(target, _prop, receiver); + get: (target, prop, receiver) => { + if (typeof(prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); } - const prop = String(_prop); - - const result = target.getFunction(prop); - if (result) { return result; } + // Undefined properties should return undefined + try { + return target.getFunction(prop); + } catch (error) { + if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") { + throw error; + } + } - throw new Error(`unknown contract method: ${ prop }`); + return undefined; }, has: (target, prop) => { - if (prop in target || passProperties.indexOf(prop) >= 0 || typeof(prop) === "symbol") { + if (typeof(prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) { return Reflect.has(target, prop); } - return target.interface.hasFunction(String(prop)); + return target.interface.hasFunction(prop); } });