From 2d88457445304b6ba3d4bfc7d914b033a009b4f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrei=20B=C4=83ncioiu?= Date: Fri, 2 Feb 2024 10:47:50 +0200 Subject: [PATCH 1/3] Run "pretty" (partially). --- .prettierrc | 3 +- src/account.ts | 2 +- src/address.spec.ts | 17 +++--- src/address.ts | 8 ++- src/asyncTimer.spec.ts | 3 +- src/compatibility.ts | 8 ++- src/gasEstimator.spec.ts | 2 +- src/gasEstimator.ts | 8 ++- src/hash.ts | 2 +- src/index.ts | 3 +- src/interfaceOfNetwork.ts | 5 +- src/logger.ts | 3 +- src/networkParams.spec.ts | 10 +++- src/networkParams.ts | 12 +++-- src/signature.ts | 3 +- src/smartcontracts/argSerializer.spec.ts | 23 +++++--- src/smartcontracts/argSerializer.ts | 11 ++-- src/smartcontracts/argumentErrorContext.ts | 16 ++++-- src/smartcontracts/code.spec.ts | 2 +- src/smartcontracts/code.ts | 12 ++--- src/smartcontracts/codeMetadata.spec.ts | 12 +++-- src/smartcontracts/codec/address.ts | 4 +- src/smartcontracts/codec/binary.ts | 16 +----- src/smartcontracts/codec/enum.ts | 10 ++-- src/smartcontracts/codec/fields.ts | 4 +- src/smartcontracts/codec/h256.ts | 4 +- src/smartcontracts/codec/numerical.ts | 14 +++-- src/smartcontracts/codec/primitive.ts | 8 +-- src/smartcontracts/function.ts | 2 +- .../typesystem/abiRegistry.spec.ts | 38 +++++++++++--- src/smartcontracts/typesystem/abiRegistry.ts | 46 +++++++++------- src/smartcontracts/typesystem/address.ts | 2 +- src/smartcontracts/typesystem/algebraic.ts | 2 +- src/smartcontracts/typesystem/boolean.ts | 2 +- .../typesystem/composite.spec.ts | 5 +- src/smartcontracts/typesystem/composite.ts | 4 +- .../typesystem/endpoint.spec.ts | 25 +++++---- src/smartcontracts/typesystem/endpoint.ts | 31 +++++++---- src/smartcontracts/typesystem/enum.spec.ts | 52 ++++++------------- src/smartcontracts/typesystem/enum.ts | 10 ++-- src/smartcontracts/typesystem/event.ts | 13 ++--- src/smartcontracts/typesystem/factory.ts | 4 +- src/smartcontracts/typesystem/fields.ts | 8 +-- src/smartcontracts/typesystem/generic.ts | 2 +- src/smartcontracts/typesystem/index.ts | 1 - src/smartcontracts/typesystem/matchers.ts | 8 +-- src/smartcontracts/typesystem/struct.spec.ts | 15 +++--- src/smartcontracts/typesystem/struct.ts | 8 +-- .../typesystem/tokenIdentifier.ts | 4 +- src/smartcontracts/typesystem/tuple.ts | 8 +-- .../typesystem/typeMapper.spec.ts | 12 +++-- src/smartcontracts/typesystem/typeMapper.ts | 10 ++-- src/smartcontracts/typesystem/types.spec.ts | 45 ++++++++++------ src/smartcontracts/typesystem/types.ts | 49 +++++++++-------- src/testutils/mockProvider.ts | 40 +++++++------- src/testutils/networkProviders.ts | 8 ++- src/testutils/utils.ts | 22 ++++---- src/testutils/wallets.ts | 23 +++++--- src/tokenTransfer.spec.ts | 10 +++- src/tokenTransfer.ts | 15 ++++-- src/tokenTransferBuilders.spec.ts | 21 ++++++-- src/tokens.ts | 6 +-- src/utils.ts | 6 +-- 63 files changed, 446 insertions(+), 336 deletions(-) diff --git a/.prettierrc b/.prettierrc index e7cf084b..9e4d56ad 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,5 +1,6 @@ { "singleQuote": false, "trailingComma": "all", - "tabWidth": 4 + "tabWidth": 4, + "printWidth": 120 } diff --git a/src/account.ts b/src/account.ts index 8d10b89f..68ccf609 100644 --- a/src/account.ts +++ b/src/account.ts @@ -30,7 +30,7 @@ export class Account { /** * Updates account properties (such as nonce, balance). */ - update(obj: { nonce: INonce, balance: IAccountBalance}) { + update(obj: { nonce: INonce; balance: IAccountBalance }) { this.nonce = obj.nonce; this.balance = obj.balance; } diff --git a/src/address.spec.ts b/src/address.spec.ts index ca731f8e..248b858a 100644 --- a/src/address.spec.ts +++ b/src/address.spec.ts @@ -2,7 +2,6 @@ import { assert } from "chai"; import { Address } from "./address"; import * as errors from "./errors"; - describe("test address", () => { let aliceBech32 = "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"; let bobBech32 = "erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"; @@ -41,13 +40,19 @@ describe("test address", () => { assert.throw(() => new Address("foo"), errors.ErrAddressCannotCreate); assert.throw(() => new Address("a".repeat(7)), errors.ErrAddressCannotCreate); assert.throw(() => new Address(Buffer.from("aaaa", "hex")), errors.ErrAddressCannotCreate); - assert.throw(() => new Address("erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2"), errors.ErrAddressCannotCreate); - assert.throw(() => new Address("xerd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz"), errors.ErrAddressCannotCreate); + assert.throw( + () => new Address("erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2"), + errors.ErrAddressCannotCreate, + ); + assert.throw( + () => new Address("xerd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz"), + errors.ErrAddressCannotCreate, + ); }); it("should validate the address without throwing the error", () => { assert.isTrue(Address.isValid(aliceBech32)); - assert.isFalse(Address.isValid('xerd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz')); - assert.isFalse(Address.isValid('erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2')) - }) + assert.isFalse(Address.isValid("xerd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz")); + assert.isFalse(Address.isValid("erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2")); + }); }); diff --git a/src/address.ts b/src/address.ts index 48bfdbaa..54601745 100644 --- a/src/address.ts +++ b/src/address.ts @@ -128,14 +128,12 @@ export class Address { static isValid(value: string): boolean { const decoded = bech32.decodeUnsafe(value); const prefix = decoded?.prefix; - const pubkey = decoded - ? Buffer.from(bech32.fromWords(decoded.words)) - : undefined; + const pubkey = decoded ? Buffer.from(bech32.fromWords(decoded.words)) : undefined; if (prefix !== HRP || pubkey?.length !== PUBKEY_LENGTH) { return false; } - + return true; } @@ -205,7 +203,7 @@ export class Address { toJSON(): object { return { bech32: this.bech32(), - pubkey: this.hex() + pubkey: this.hex(), }; } diff --git a/src/asyncTimer.spec.ts b/src/asyncTimer.spec.ts index 8166ce80..903a4cc9 100644 --- a/src/asyncTimer.spec.ts +++ b/src/asyncTimer.spec.ts @@ -2,7 +2,6 @@ import { assert } from "chai"; import * as errors from "./errors"; import { AsyncTimer } from "./asyncTimer"; - describe("test asyncTimer", () => { it("should start timer and resolve promise", async () => { let timer = new AsyncTimer("test"); @@ -21,7 +20,7 @@ describe("test asyncTimer", () => { let longPromise = longTimer.start(42000); let shortTimerThenAbortLongTimer = shortPromise.then(() => longTimer.abort()); - let longTimerThenCatchAbort = longPromise.catch(reason => error = reason); + let longTimerThenCatchAbort = longPromise.catch((reason) => (error = reason)); await Promise.all([shortTimerThenAbortLongTimer, longTimerThenCatchAbort]); diff --git a/src/compatibility.ts b/src/compatibility.ts index 27442360..3aec4764 100644 --- a/src/compatibility.ts +++ b/src/compatibility.ts @@ -16,9 +16,13 @@ export class Compatibility { } if (!address || address.bech32() == "") { - console.warn(`${context}: address should be set; ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`); + console.warn( + `${context}: address should be set; ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`, + ); } else if (address.bech32() == Address.Zero().bech32()) { - console.warn(`${context}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`); + console.warn( + `${context}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`, + ); } } } diff --git a/src/gasEstimator.spec.ts b/src/gasEstimator.spec.ts index 740ed4ef..e1394717 100644 --- a/src/gasEstimator.spec.ts +++ b/src/gasEstimator.spec.ts @@ -24,7 +24,7 @@ describe("test gas estimator", () => { gasPerDataByte: 3000, gasCostESDTTransfer: 200000, gasCostESDTNFTTransfer: 300000, - gasCostESDTNFTMultiTransfer: 400000 + gasCostESDTNFTMultiTransfer: 400000, }); assert.equal(estimator.forEGLDTransfer(0), 10000); diff --git a/src/gasEstimator.ts b/src/gasEstimator.ts index 6207c1bf..368be5e5 100644 --- a/src/gasEstimator.ts +++ b/src/gasEstimator.ts @@ -17,13 +17,13 @@ export const DefaultGasConfiguration: IGasConfiguration = { gasPerDataByte: 1500, gasCostESDTTransfer: 200000, gasCostESDTNFTTransfer: 200000, - gasCostESDTNFTMultiTransfer: 200000 + gasCostESDTNFTMultiTransfer: 200000, }; // Additional gas to account for eventual increases in gas requirements (thus avoid fast-breaking changes in clients of the library). const ADDITIONAL_GAS_FOR_ESDT_TRANSFER = 100000; -// Additional gas to account for extra blockchain operations (e.g. data movement (between accounts) for NFTs), +// Additional gas to account for extra blockchain operations (e.g. data movement (between accounts) for NFTs), // and for eventual increases in gas requirements (thus avoid fast-breaking changes in clients of the library). const ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER = 800000; @@ -35,9 +35,7 @@ export class GasEstimator { } forEGLDTransfer(dataLength: number) { - const gasLimit = - this.gasConfiguration.minGasLimit + - this.gasConfiguration.gasPerDataByte * dataLength; + const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasPerDataByte * dataLength; return gasLimit; } diff --git a/src/hash.ts b/src/hash.ts index 5f7095a7..40efda32 100644 --- a/src/hash.ts +++ b/src/hash.ts @@ -8,7 +8,7 @@ export class Hash { /** * Creates a new Hash object. - * + * * @param hash The hash, as a Buffer or a hex-encoded string. */ constructor(hash: Buffer | string) { diff --git a/src/index.ts b/src/index.ts index 545ba190..9063e99a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,4 @@ -require('./globals'); +require("./globals"); export * from "./account"; export * from "./address"; @@ -21,4 +21,3 @@ export * from "./transactionPayload"; export * from "./transactionWatcher"; export * from "./transferTransactionsFactory"; export * from "./utils"; - diff --git a/src/interfaceOfNetwork.ts b/src/interfaceOfNetwork.ts index 942a9b5f..84b284fc 100644 --- a/src/interfaceOfNetwork.ts +++ b/src/interfaceOfNetwork.ts @@ -65,7 +65,10 @@ export interface IContractReturnCode { export interface ITransactionLogs { events: ITransactionEvent[]; - findSingleOrNoneEvent(identifier: string, predicate?: (event: ITransactionEvent) => boolean): ITransactionEvent | undefined; + findSingleOrNoneEvent( + identifier: string, + predicate?: (event: ITransactionEvent) => boolean, + ): ITransactionEvent | undefined; } export interface ITransactionEvent { diff --git a/src/logger.ts b/src/logger.ts index 50ff4d25..65910ea6 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -4,7 +4,7 @@ export enum LogLevel { Info = 2, Warn = 3, Error = 4, - None = 5 + None = 5, } export class Logger { @@ -54,4 +54,3 @@ export class Logger { console.error(message, optionalParams); } } - diff --git a/src/networkParams.spec.ts b/src/networkParams.spec.ts index c217414e..7f127437 100644 --- a/src/networkParams.spec.ts +++ b/src/networkParams.spec.ts @@ -1,6 +1,9 @@ import { assert } from "chai"; import { - TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_OPTIONS_TX_GUARDED, TRANSACTION_OPTIONS_TX_HASH_SIGN, TRANSACTION_VERSION_DEFAULT + TRANSACTION_OPTIONS_DEFAULT, + TRANSACTION_OPTIONS_TX_GUARDED, + TRANSACTION_OPTIONS_TX_HASH_SIGN, + TRANSACTION_VERSION_DEFAULT, } from "./constants"; import { TransactionOptions, TransactionVersion } from "./networkParams"; @@ -61,7 +64,10 @@ describe("test transaction options", () => { assert.isTrue(optionsWithGuardian.isWithGuardian()); const optionsWithHashSignAndGuardian = TransactionOptions.withOptions({ hashSign: true, guarded: true }); - assert.equal(optionsWithHashSignAndGuardian.valueOf(), TRANSACTION_OPTIONS_TX_HASH_SIGN | TRANSACTION_OPTIONS_TX_GUARDED); + assert.equal( + optionsWithHashSignAndGuardian.valueOf(), + TRANSACTION_OPTIONS_TX_HASH_SIGN | TRANSACTION_OPTIONS_TX_GUARDED, + ); assert.isTrue(optionsWithHashSignAndGuardian.isWithHashSign()); assert.isTrue(optionsWithHashSignAndGuardian.isWithGuardian()); }); diff --git a/src/networkParams.ts b/src/networkParams.ts index 24b8b701..36f8a23c 100644 --- a/src/networkParams.ts +++ b/src/networkParams.ts @@ -1,4 +1,9 @@ -import { TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_OPTIONS_TX_GUARDED, TRANSACTION_OPTIONS_TX_HASH_SIGN, TRANSACTION_VERSION_DEFAULT } from "./constants"; +import { + TRANSACTION_OPTIONS_DEFAULT, + TRANSACTION_OPTIONS_TX_GUARDED, + TRANSACTION_OPTIONS_TX_HASH_SIGN, + TRANSACTION_VERSION_DEFAULT, +} from "./constants"; import * as errors from "./errors"; export class TransactionVersion { @@ -68,10 +73,7 @@ export class TransactionOptions { /** * Creates a TransactionOptions object from a set of options. */ - public static withOptions(options: { - hashSign?: boolean, - guarded?: boolean - }): TransactionOptions { + public static withOptions(options: { hashSign?: boolean; guarded?: boolean }): TransactionOptions { let value = 0; if (options.hashSign) { diff --git a/src/signature.ts b/src/signature.ts index e307a225..95fe9977 100644 --- a/src/signature.ts +++ b/src/signature.ts @@ -1,6 +1,5 @@ import * as errors from "./errors"; - const SIGNATURE_LENGTH = 64; /** @@ -59,7 +58,7 @@ export class Signature { } } -export function interpretSignatureAsBuffer(signature: { hex(): string; } | Uint8Array): Buffer { +export function interpretSignatureAsBuffer(signature: { hex(): string } | Uint8Array): Buffer { if (ArrayBuffer.isView(signature)) { return Buffer.from(signature); } else if ((signature).hex != null) { diff --git a/src/smartcontracts/argSerializer.spec.ts b/src/smartcontracts/argSerializer.spec.ts index 06bcac91..84065082 100644 --- a/src/smartcontracts/argSerializer.spec.ts +++ b/src/smartcontracts/argSerializer.spec.ts @@ -29,7 +29,7 @@ describe("test serializer", () => { serializeThenDeserialize( ["u32", "i64", "bytes"], [new U32Value(100), new I64Value(new BigNumber("-1")), new BytesValue(Buffer.from("abba", "hex"))], - "64@ff@abba" + "64@ff@abba", ); serializeThenDeserialize( @@ -39,7 +39,7 @@ describe("test serializer", () => { OptionValue.newMissing(), CompositeValue.fromItems(new U8Value(3), new BytesValue(Buffer.from("abba", "hex"))), ], - "0100000064@@03@abba" + "0100000064@@03@abba", ); serializeThenDeserialize( @@ -49,19 +49,26 @@ describe("test serializer", () => { VariadicValue.fromItems( new BytesValue(Buffer.from("abba", "hex")), new BytesValue(Buffer.from("abba", "hex")), - new BytesValue(Buffer.from("abba", "hex")) + new BytesValue(Buffer.from("abba", "hex")), ), ], - "00080009@abba@abba@abba" + "00080009@abba@abba@abba", ); serializeThenDeserialize( ["MultiArg, List>", "VarArgs"], [ - CompositeValue.fromItems(OptionValue.newProvided(new U8Value(7)), List.fromItems([new U16Value(8), new U16Value(9)])), - VariadicValue.fromItems(new BytesValue(Buffer.from("abba", "hex")), new BytesValue(Buffer.from("abba", "hex")), new BytesValue(Buffer.from("abba", "hex"))) + CompositeValue.fromItems( + OptionValue.newProvided(new U8Value(7)), + List.fromItems([new U16Value(8), new U16Value(9)]), + ), + VariadicValue.fromItems( + new BytesValue(Buffer.from("abba", "hex")), + new BytesValue(Buffer.from("abba", "hex")), + new BytesValue(Buffer.from("abba", "hex")), + ), ], - "0107@00080009@abba@abba@abba" + "0107@00080009@abba@abba@abba", ); }); @@ -69,7 +76,7 @@ describe("test serializer", () => { serializeThenDeserialize( ["tuple2"], [Tuple.fromItems([new I32Value(100), new I16Value(10)])], - "00000064000a" + "00000064000a", ); }); diff --git a/src/smartcontracts/argSerializer.ts b/src/smartcontracts/argSerializer.ts index fbf3c492..f065ba7a 100644 --- a/src/smartcontracts/argSerializer.ts +++ b/src/smartcontracts/argSerializer.ts @@ -5,7 +5,6 @@ import { OptionalType, OptionalValue } from "./typesystem/algebraic"; import { CompositeType, CompositeValue } from "./typesystem/composite"; import { VariadicType, VariadicValue } from "./typesystem/variadic"; - interface IArgSerializerOptions { codec: ICodec; } @@ -22,7 +21,7 @@ interface IParameterDefinition { // TODO: perhaps move default construction options to a factory (ArgSerializerFactory), instead of referencing them in the constructor // (postpone as much as possible, breaking change) const defaultArgSerializerOptions: IArgSerializerOptions = { - codec: new BinaryCodec() + codec: new BinaryCodec(), }; export class ArgSerializer { @@ -47,7 +46,7 @@ export class ArgSerializer { */ stringToBuffers(joinedString: string): Buffer[] { // We also keep the zero-length buffers (they could encode missing options, Option). - return joinedString.split(ARGUMENTS_SEPARATOR).map(item => Buffer.from(item, "hex")); + return joinedString.split(ARGUMENTS_SEPARATOR).map((item) => Buffer.from(item, "hex")); } /** @@ -137,7 +136,7 @@ export class ArgSerializer { /** * Serializes a set of typed values into an arguments string (e.g. aa@bb@@cc). */ - valuesToString(values: TypedValue[]): { argumentsString: string, count: number } { + valuesToString(values: TypedValue[]): { argumentsString: string; count: number } { let strings = this.valuesToStrings(values); let argumentsString = strings.join(ARGUMENTS_SEPARATOR); let count = strings.length; @@ -149,7 +148,7 @@ export class ArgSerializer { */ valuesToStrings(values: TypedValue[]): string[] { let buffers = this.valuesToBuffers(values); - let strings = buffers.map(buffer => buffer.toString("hex")); + let strings = buffers.map((buffer) => buffer.toString("hex")); return strings; } @@ -192,7 +191,7 @@ export class ArgSerializer { handleValue(item); } - return + return; } // Non-composite (singular), non-variadic (fixed) type. diff --git a/src/smartcontracts/argumentErrorContext.ts b/src/smartcontracts/argumentErrorContext.ts index 76543ddf..661f62b2 100644 --- a/src/smartcontracts/argumentErrorContext.ts +++ b/src/smartcontracts/argumentErrorContext.ts @@ -13,11 +13,15 @@ export class ArgumentErrorContext { } throwError(specificError: string): never { - throw new ErrInvalidArgument(`Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type})\nNested error: ${specificError}`); + throw new ErrInvalidArgument( + `Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type})\nNested error: ${specificError}`, + ); } convertError(native: any, typeName: string): never { - this.throwError(`Can't convert argument (argument: ${native}, type ${typeof native}), wanted type: ${typeName})`); + this.throwError( + `Can't convert argument (argument: ${native}, type ${typeof native}), wanted type: ${typeName})`, + ); } unhandledType(functionName: string, type: Type): never { @@ -27,14 +31,18 @@ export class ArgumentErrorContext { guardSameLength(native: any[], valueTypes: T[]) { native = native || []; if (native.length != valueTypes.length) { - this.throwError(`Incorrect composite type length: have ${native.length}, expected ${valueTypes.length} (argument: ${native})`); + this.throwError( + `Incorrect composite type length: have ${native.length}, expected ${valueTypes.length} (argument: ${native})`, + ); } } guardHasField(native: any, fieldName: string) { native = native || {}; if (!(fieldName in native)) { - this.throwError(`Struct argument does not contain a field named "${fieldName}" (argument: ${JSON.stringify(native)})`); + this.throwError( + `Struct argument does not contain a field named "${fieldName}" (argument: ${JSON.stringify(native)})`, + ); } } } diff --git a/src/smartcontracts/code.spec.ts b/src/smartcontracts/code.spec.ts index 2dd2425d..1933cfef 100644 --- a/src/smartcontracts/code.spec.ts +++ b/src/smartcontracts/code.spec.ts @@ -32,6 +32,6 @@ describe("Code Class Tests", function () { const hash = code.computeHash(); assert.instanceOf(hash, Buffer); - assert.equal(hash.toString('hex'), 'ac86b78afd9bdda3641a47a4aff2a7ee26acd40cc534d63655e9dfbf3f890a02') + assert.equal(hash.toString("hex"), "ac86b78afd9bdda3641a47a4aff2a7ee26acd40cc534d63655e9dfbf3f890a02"); }); }); diff --git a/src/smartcontracts/code.ts b/src/smartcontracts/code.ts index 6b770041..e7a8b68d 100644 --- a/src/smartcontracts/code.ts +++ b/src/smartcontracts/code.ts @@ -1,5 +1,5 @@ -const createHasher = require('blake2b') -const CODE_HASH_LENGTH = 32 +const createHasher = require("blake2b"); +const CODE_HASH_LENGTH = 32; /** * Bytecode of a Smart Contract, as an abstraction. @@ -22,7 +22,7 @@ export class Code { * Creates a Code object from a hex-encoded string. */ static fromHex(hex: string): Code { - return new Code(hex) + return new Code(hex); } /** @@ -37,10 +37,8 @@ export class Code { } computeHash(): Buffer { - const hash = createHasher(CODE_HASH_LENGTH) - .update(this.valueOf()) - .digest(); + const hash = createHasher(CODE_HASH_LENGTH).update(this.valueOf()).digest(); - return Buffer.from(hash) + return Buffer.from(hash); } } diff --git a/src/smartcontracts/codeMetadata.spec.ts b/src/smartcontracts/codeMetadata.spec.ts index 685d8cf5..7b0eab88 100644 --- a/src/smartcontracts/codeMetadata.spec.ts +++ b/src/smartcontracts/codeMetadata.spec.ts @@ -58,9 +58,13 @@ describe("CodeMetadata Class Tests", function () { it("should handle buffer too short error", function () { const buffer = Buffer.from([CodeMetadata.ByteZero.Upgradeable]); - assert.throws(() => { - CodeMetadata.fromBuffer(buffer); - }, Error, "Buffer is too short."); + assert.throws( + () => { + CodeMetadata.fromBuffer(buffer); + }, + Error, + "Buffer is too short.", + ); }); it("should test code metadata from bytes", () => { @@ -72,7 +76,7 @@ describe("CodeMetadata Class Tests", function () { upgradeable: true, readable: false, payable: false, - payableBySc: false + payableBySc: false, }); }); }); diff --git a/src/smartcontracts/codec/address.ts b/src/smartcontracts/codec/address.ts index 35dd0a82..8e640d54 100644 --- a/src/smartcontracts/codec/address.ts +++ b/src/smartcontracts/codec/address.ts @@ -4,7 +4,7 @@ import { AddressValue } from "../typesystem"; export class AddressBinaryCodec { /** * Reads and decodes an AddressValue from a given buffer. - * + * * @param buffer the input buffer */ decodeNested(buffer: Buffer): [AddressValue, number] { @@ -17,7 +17,7 @@ export class AddressBinaryCodec { /** * Reads and decodes an AddressValue from a given buffer. - * + * * @param buffer the input buffer */ decodeTopLevel(buffer: Buffer): AddressValue { diff --git a/src/smartcontracts/codec/binary.ts b/src/smartcontracts/codec/binary.ts index 519ad2a5..1b970931 100644 --- a/src/smartcontracts/codec/binary.ts +++ b/src/smartcontracts/codec/binary.ts @@ -80,13 +80,7 @@ export class BinaryCodec { } encodeNested(typedValue: TypedValue): Buffer { - guardTrue( - typedValue - .getType() - .getCardinality() - .isSingular(), - "singular cardinality, thus encodable type" - ); + guardTrue(typedValue.getType().getCardinality().isSingular(), "singular cardinality, thus encodable type"); return onTypedValueSelect(typedValue, { onPrimitive: () => this.primitiveCodec.encodeNested(typedValue), @@ -100,13 +94,7 @@ export class BinaryCodec { } encodeTopLevel(typedValue: TypedValue): Buffer { - guardTrue( - typedValue - .getType() - .getCardinality() - .isSingular(), - "singular cardinality, thus encodable type" - ); + guardTrue(typedValue.getType().getCardinality().isSingular(), "singular cardinality, thus encodable type"); return onTypedValueSelect(typedValue, { onPrimitive: () => this.primitiveCodec.encodeTopLevel(typedValue), diff --git a/src/smartcontracts/codec/enum.ts b/src/smartcontracts/codec/enum.ts index 4d9be4c8..d73e79bd 100644 --- a/src/smartcontracts/codec/enum.ts +++ b/src/smartcontracts/codec/enum.ts @@ -23,7 +23,7 @@ export class EnumBinaryCodec { let variant = type.getVariantByDiscriminant(discriminant); let fieldDefinitions = variant.getFieldsDefinitions(); - + let [fields, lengthOfFields]: [Field[], number] = this.fieldsCodec.decodeNested(buffer, fieldDefinitions); let enumValue = new EnumValue(type, variant, fields); @@ -33,7 +33,7 @@ export class EnumBinaryCodec { private readDiscriminant(buffer: Buffer): [discriminant: number, length: number] { let [value, length] = this.binaryCodec.decodeNested(buffer, new U8Type()); let discriminant = value.valueOf(); - + return [discriminant, length]; } @@ -51,9 +51,11 @@ export class EnumBinaryCodec { let fields = enumValue.getFields(); let hasFields = fields.length > 0; let fieldsBuffer = this.fieldsCodec.encodeNested(fields); - + let discriminant = new U8Value(enumValue.discriminant); - let discriminantBuffer = hasFields ? this.binaryCodec.encodeNested(discriminant) : this.binaryCodec.encodeTopLevel(discriminant); + let discriminantBuffer = hasFields + ? this.binaryCodec.encodeNested(discriminant) + : this.binaryCodec.encodeTopLevel(discriminant); return Buffer.concat([discriminantBuffer, fieldsBuffer]); } diff --git a/src/smartcontracts/codec/fields.ts b/src/smartcontracts/codec/fields.ts index d5b6dee2..31a88ab5 100644 --- a/src/smartcontracts/codec/fields.ts +++ b/src/smartcontracts/codec/fields.ts @@ -20,13 +20,13 @@ export class FieldsBinaryCodec { let field = new Field(decoded, fieldDefinition.name); fields.push(field); } - + return [fields, totalLength]; } encodeNested(fields: ReadonlyArray): Buffer { let buffers: Buffer[] = []; - + for (const field of fields) { let fieldBuffer = this.binaryCodec.encodeNested(field.value); buffers.push(fieldBuffer); diff --git a/src/smartcontracts/codec/h256.ts b/src/smartcontracts/codec/h256.ts index 76418b65..27a043c4 100644 --- a/src/smartcontracts/codec/h256.ts +++ b/src/smartcontracts/codec/h256.ts @@ -3,7 +3,7 @@ import { H256Value } from "../typesystem/h256"; export class H256BinaryCodec { /** * Reads and decodes a H256Value from a given buffer. - * + * * @param buffer the input buffer */ decodeNested(buffer: Buffer): [H256Value, number] { @@ -14,7 +14,7 @@ export class H256BinaryCodec { /** * Reads and decodes a H256Value from a given buffer. - * + * * @param buffer the input buffer */ decodeTopLevel(buffer: Buffer): H256Value { diff --git a/src/smartcontracts/codec/numerical.ts b/src/smartcontracts/codec/numerical.ts index 38016615..9dd27f6e 100644 --- a/src/smartcontracts/codec/numerical.ts +++ b/src/smartcontracts/codec/numerical.ts @@ -1,7 +1,15 @@ import BigNumber from "bignumber.js"; import { NumericalType, NumericalValue } from "../typesystem"; import { SizeOfU32 } from "./constants"; -import { bigIntToBuffer, bufferToBigInt, cloneBuffer, flipBufferBitsInPlace, isMsbOne, isMsbZero, prependByteToBuffer } from "./utils"; +import { + bigIntToBuffer, + bufferToBigInt, + cloneBuffer, + flipBufferBitsInPlace, + isMsbOne, + isMsbZero, + prependByteToBuffer, +} from "./utils"; /** * Encodes and decodes "NumericalValue" objects. @@ -91,7 +99,7 @@ export class NumericalBinaryCodec { // Fix ambiguity if any if (isMsbZero(buffer)) { - buffer = prependByteToBuffer(buffer, 0xFF); + buffer = prependByteToBuffer(buffer, 0xff); } const paddingBytes = Buffer.alloc(size - buffer.length, 0xff); @@ -135,7 +143,7 @@ export class NumericalBinaryCodec { // Fix ambiguity if any if (isMsbZero(buffer)) { - buffer = prependByteToBuffer(buffer, 0xFF); + buffer = prependByteToBuffer(buffer, 0xff); } return buffer; diff --git a/src/smartcontracts/codec/primitive.ts b/src/smartcontracts/codec/primitive.ts index 833b9e14..f761c0df 100644 --- a/src/smartcontracts/codec/primitive.ts +++ b/src/smartcontracts/codec/primitive.ts @@ -56,7 +56,7 @@ export class PrimitiveBinaryCodec { onString: () => this.stringCodec.decodeNested(buffer), onH256: () => this.h256Codec.decodeNested(buffer), onTokenIndetifier: () => this.tokenIdentifierCodec.decodeNested(buffer), - onNothing: () => this.nothingCodec.decodeNested() + onNothing: () => this.nothingCodec.decodeNested(), }); } @@ -69,7 +69,7 @@ export class PrimitiveBinaryCodec { onString: () => this.stringCodec.decodeTopLevel(buffer), onH256: () => this.h256Codec.decodeTopLevel(buffer), onTokenIndetifier: () => this.tokenIdentifierCodec.decodeTopLevel(buffer), - onNothing: () => this.nothingCodec.decodeTopLevel() + onNothing: () => this.nothingCodec.decodeTopLevel(), }); } @@ -82,7 +82,7 @@ export class PrimitiveBinaryCodec { onString: () => this.stringCodec.encodeNested(value), onH256: () => this.h256Codec.encodeNested(value), onTypeIdentifier: () => this.tokenIdentifierCodec.encodeNested(value), - onNothing: () => this.nothingCodec.encodeNested() + onNothing: () => this.nothingCodec.encodeNested(), }); } @@ -95,7 +95,7 @@ export class PrimitiveBinaryCodec { onString: () => this.stringCodec.encodeTopLevel(value), onH256: () => this.h256Codec.encodeTopLevel(value), onTypeIdentifier: () => this.tokenIdentifierCodec.encodeTopLevel(value), - onNothing: () => this.nothingCodec.encodeTopLevel() + onNothing: () => this.nothingCodec.encodeTopLevel(), }); } } diff --git a/src/smartcontracts/function.ts b/src/smartcontracts/function.ts index 83d55e3f..b8547e46 100644 --- a/src/smartcontracts/function.ts +++ b/src/smartcontracts/function.ts @@ -11,7 +11,7 @@ export class ContractFunction { /** * Creates a ContractFunction object, given its name. - * + * * @param name the name of the function */ constructor(name: string) { diff --git a/src/smartcontracts/typesystem/abiRegistry.spec.ts b/src/smartcontracts/typesystem/abiRegistry.spec.ts index 3d151e1d..e9930b4e 100644 --- a/src/smartcontracts/typesystem/abiRegistry.spec.ts +++ b/src/smartcontracts/typesystem/abiRegistry.spec.ts @@ -64,7 +64,7 @@ describe("test abi registry", () => { let bc = new BinaryCodec(); let buff = Buffer.from( "0588c738a5d26c0e3a2b4f9e8110b540ee9c0b71a3be057569a5a7b0fcb482c8f70000000806f05b59d3b200000000000b68656c6c6f20776f726c6400000000", - "hex" + "hex", ); let registry = await loadAbiRegistry("src/testdata/multisig.abi.json"); @@ -74,7 +74,7 @@ describe("test abi registry", () => { let result = bc.decodeTopLevel(buff, performAction.output[0].type); assert.deepEqual( JSON.stringify(result.valueOf()), - `{"name":"SendTransferExecute","fields":[{"to":{"bech32":"erd13rrn3fwjds8r5260n6q3pd2qa6wqkudrhczh26d957c0edyzermshds0k8","pubkey":"88c738a5d26c0e3a2b4f9e8110b540ee9c0b71a3be057569a5a7b0fcb482c8f7"},"egld_amount":"500000000000000000","endpoint_name":{"type":"Buffer","data":[104,101,108,108,111,32,119,111,114,108,100]},"arguments":[]}]}` + `{"name":"SendTransferExecute","fields":[{"to":{"bech32":"erd13rrn3fwjds8r5260n6q3pd2qa6wqkudrhczh26d957c0edyzermshds0k8","pubkey":"88c738a5d26c0e3a2b4f9e8110b540ee9c0b71a3be057569a5a7b0fcb482c8f7"},"egld_amount":"500000000000000000","endpoint_name":{"type":"Buffer","data":[104,101,108,108,111,32,119,111,114,108,100]},"arguments":[]}]}`, ); assert.equal(result.valueOf().name, "SendTransferExecute"); }); @@ -98,7 +98,12 @@ describe("test abi registry", () => { it("should load ABI when custom types are out of order (a)", async () => { const registry = await loadAbiRegistry("src/testdata/custom-types-out-of-order-a.abi.json"); - assert.deepEqual(registry.getStruct("EsdtTokenTransfer").getNamesOfDependencies(), ["EsdtTokenType", "TokenIdentifier", "u64", "BigUint"]); + assert.deepEqual(registry.getStruct("EsdtTokenTransfer").getNamesOfDependencies(), [ + "EsdtTokenType", + "TokenIdentifier", + "u64", + "BigUint", + ]); assert.deepEqual(registry.getEnum("EsdtTokenType").getNamesOfDependencies(), []); assert.deepEqual(registry.getStruct("TypeA").getNamesOfDependencies(), ["TypeB", "TypeC", "u64"]); assert.deepEqual(registry.getStruct("TypeB").getNamesOfDependencies(), ["TypeC", "u64"]); @@ -108,7 +113,12 @@ describe("test abi registry", () => { it("should load ABI when custom types are out of order (b)", async () => { const registry = await loadAbiRegistry("src/testdata/custom-types-out-of-order-b.abi.json"); - assert.deepEqual(registry.getStruct("EsdtTokenTransfer").getNamesOfDependencies(), ["EsdtTokenType", "TokenIdentifier", "u64", "BigUint"]); + assert.deepEqual(registry.getStruct("EsdtTokenTransfer").getNamesOfDependencies(), [ + "EsdtTokenType", + "TokenIdentifier", + "u64", + "BigUint", + ]); assert.deepEqual(registry.getEnum("EsdtTokenType").getNamesOfDependencies(), []); assert.deepEqual(registry.getStruct("TypeA").getNamesOfDependencies(), ["TypeB", "TypeC", "u64"]); assert.deepEqual(registry.getStruct("TypeB").getNamesOfDependencies(), ["TypeC", "u64"]); @@ -119,15 +129,29 @@ describe("test abi registry", () => { const registry = await loadAbiRegistry("src/testdata/custom-types-out-of-order-c.abi.json"); assert.lengthOf(registry.customTypes, 5); - assert.deepEqual(registry.getStruct("LoanCreateOptions").getNamesOfDependencies(), ["BigUint", "Address", "TokenIdentifier", "Status", "bytes"]); - + assert.deepEqual(registry.getStruct("LoanCreateOptions").getNamesOfDependencies(), [ + "BigUint", + "Address", + "TokenIdentifier", + "Status", + "bytes", + ]); }); it("should load ABI when custom types are out of order (community example: d)", async () => { const registry = await loadAbiRegistry("src/testdata/custom-types-out-of-order-d.abi.json"); assert.lengthOf(registry.customTypes, 12); - assert.deepEqual(registry.getStruct("AuctionItem").getNamesOfDependencies(), ["u64", "Address", "BigUint", "Option", "NftData", "bytes", "TokenIdentifier", "List"]); + assert.deepEqual(registry.getStruct("AuctionItem").getNamesOfDependencies(), [ + "u64", + "Address", + "BigUint", + "Option", + "NftData", + "bytes", + "TokenIdentifier", + "List", + ]); }); it("should load ABI with counted-variadic", async () => { diff --git a/src/smartcontracts/typesystem/abiRegistry.ts b/src/smartcontracts/typesystem/abiRegistry.ts index 27c300ee..601b65be 100644 --- a/src/smartcontracts/typesystem/abiRegistry.ts +++ b/src/smartcontracts/typesystem/abiRegistry.ts @@ -20,8 +20,8 @@ export class AbiRegistry { name: string; constructorDefinition: EndpointDefinition; endpoints: EndpointDefinition[]; - customTypes: CustomType[], - events?: EventDefinition[] + customTypes: CustomType[]; + events?: EventDefinition[]; }) { this.name = options.name; this.constructorDefinition = options.constructorDefinition; @@ -32,10 +32,10 @@ export class AbiRegistry { static create(options: { name?: string; - constructor?: any, + constructor?: any; endpoints?: any[]; - types?: Record - events?: any[] + types?: Record; + events?: any[]; }): AbiRegistry { const name = options.name || interfaceNamePlaceholder; const constructor = options.constructor || {}; @@ -45,7 +45,7 @@ export class AbiRegistry { // Load arbitrary input parameters into properly-defined objects (e.g. EndpointDefinition and CustomType). const constructorDefinition = EndpointDefinition.fromJSON({ name: "constructor", ...constructor }); - const endpointDefinitions = endpoints.map(item => EndpointDefinition.fromJSON(item)); + const endpointDefinitions = endpoints.map((item) => EndpointDefinition.fromJSON(item)); const customTypes: CustomType[] = []; for (const customTypeName in types) { @@ -60,14 +60,14 @@ export class AbiRegistry { } } - const eventDefinitions = events.map(item => EventDefinition.fromJSON(item)); + const eventDefinitions = events.map((item) => EventDefinition.fromJSON(item)); const registry = new AbiRegistry({ name: name, constructorDefinition: constructorDefinition, endpoints: endpointDefinitions, customTypes: customTypes, - events: eventDefinitions + events: eventDefinitions, }); const remappedRegistry = registry.remapToKnownTypes(); @@ -158,26 +158,31 @@ export class AbiRegistry { constructorDefinition: newConstructor, endpoints: newEndpoints, customTypes: newCustomTypes, - events: newEvents + events: newEvents, }); return newRegistry; } - private mapCustomTypeDepthFirst(typeToMap: CustomType, allTypesToMap: CustomType[], mapper: TypeMapper, mappedTypes: CustomType[]) { - const hasBeenMapped = mappedTypes.findIndex(type => type.getName() == typeToMap.getName()) >= 0; + private mapCustomTypeDepthFirst( + typeToMap: CustomType, + allTypesToMap: CustomType[], + mapper: TypeMapper, + mappedTypes: CustomType[], + ) { + const hasBeenMapped = mappedTypes.findIndex((type) => type.getName() == typeToMap.getName()) >= 0; if (hasBeenMapped) { return; } for (const typeName of typeToMap.getNamesOfDependencies()) { - const dependencyType = allTypesToMap.find(type => type.getName() == typeName); + const dependencyType = allTypesToMap.find((type) => type.getName() == typeName); if (!dependencyType) { // It's a type that we don't have to map (e.g. could be a primitive type). continue; } - this.mapCustomTypeDepthFirst(dependencyType, allTypesToMap, mapper, mappedTypes) + this.mapCustomTypeDepthFirst(dependencyType, allTypesToMap, mapper, mappedTypes); } const mappedType = mapper.mapType(typeToMap); @@ -187,11 +192,11 @@ export class AbiRegistry { function mapEndpoint(endpoint: EndpointDefinition, mapper: TypeMapper): EndpointDefinition { const newInput = endpoint.input.map( - (e) => new EndpointParameterDefinition(e.name, e.description, mapper.mapType(e.type)) + (e) => new EndpointParameterDefinition(e.name, e.description, mapper.mapType(e.type)), ); const newOutput = endpoint.output.map( - (e) => new EndpointParameterDefinition(e.name, e.description, mapper.mapType(e.type)) + (e) => new EndpointParameterDefinition(e.name, e.description, mapper.mapType(e.type)), ); return new EndpointDefinition(endpoint.name, newInput, newOutput, endpoint.modifiers); @@ -199,11 +204,12 @@ function mapEndpoint(endpoint: EndpointDefinition, mapper: TypeMapper): Endpoint function mapEvent(event: EventDefinition, mapper: TypeMapper): EventDefinition { const newInputs = event.inputs.map( - (e) => new EventTopicDefinition({ - name: e.name, - type: mapper.mapType(e.type), - indexed: e.indexed - }) + (e) => + new EventTopicDefinition({ + name: e.name, + type: mapper.mapType(e.type), + indexed: e.indexed, + }), ); return new EventDefinition(event.identifier, newInputs); diff --git a/src/smartcontracts/typesystem/address.ts b/src/smartcontracts/typesystem/address.ts index 25a86984..53391e95 100644 --- a/src/smartcontracts/typesystem/address.ts +++ b/src/smartcontracts/typesystem/address.ts @@ -32,7 +32,7 @@ export class AddressValue extends PrimitiveValue { /** * Returns whether two objects have the same value. - * + * * @param other another AddressValue */ equals(other: AddressValue): boolean { diff --git a/src/smartcontracts/typesystem/algebraic.ts b/src/smartcontracts/typesystem/algebraic.ts index 5d41282c..91225dee 100644 --- a/src/smartcontracts/typesystem/algebraic.ts +++ b/src/smartcontracts/typesystem/algebraic.ts @@ -16,7 +16,7 @@ export class OptionalType extends Type { } isAssignableFrom(type: Type): boolean { - if (!(type.hasExactClass(OptionalType.ClassName))) { + if (!type.hasExactClass(OptionalType.ClassName)) { return false; } diff --git a/src/smartcontracts/typesystem/boolean.ts b/src/smartcontracts/typesystem/boolean.ts index 78b68dac..9eef9423 100644 --- a/src/smartcontracts/typesystem/boolean.ts +++ b/src/smartcontracts/typesystem/boolean.ts @@ -30,7 +30,7 @@ export class BooleanValue extends PrimitiveValue { /** * Returns whether two objects have the same value. - * + * * @param other another BooleanValue */ equals(other: BooleanValue): boolean { diff --git a/src/smartcontracts/typesystem/composite.spec.ts b/src/smartcontracts/typesystem/composite.spec.ts index f3b4ebf6..e8ee7626 100644 --- a/src/smartcontracts/typesystem/composite.spec.ts +++ b/src/smartcontracts/typesystem/composite.spec.ts @@ -5,7 +5,6 @@ import { CompositeType, CompositeValue } from "./composite"; import { EndpointParameterDefinition } from "./endpoint"; import { U32Type, U32Value } from "./numerical"; - describe("test composite", () => { const serializer = new ArgSerializer(); @@ -21,7 +20,7 @@ describe("test composite", () => { it("should get valueOf() upon decoding", () => { const compositeType = new CompositeType(new U32Type(), new BytesType()); - const endpointDefinition = new EndpointParameterDefinition("", "", compositeType) + const endpointDefinition = new EndpointParameterDefinition("", "", compositeType); const [compositeValue] = serializer.stringToValues("2a@abba", [endpointDefinition]); const values = compositeValue.valueOf(); @@ -43,7 +42,7 @@ describe("test composite", () => { it("should get valueOf() upon decoding, when items are missing", () => { const compositeType = new CompositeType(new U32Type(), new BytesType()); - const endpointDefinition = new EndpointParameterDefinition("", "", compositeType) + const endpointDefinition = new EndpointParameterDefinition("", "", compositeType); const [compositeValue] = serializer.stringToValues("", [endpointDefinition]); const values = compositeValue.valueOf(); diff --git a/src/smartcontracts/typesystem/composite.ts b/src/smartcontracts/typesystem/composite.ts index b3441795..6892a9a1 100644 --- a/src/smartcontracts/typesystem/composite.ts +++ b/src/smartcontracts/typesystem/composite.ts @@ -32,7 +32,7 @@ export class CompositeValue extends TypedValue { } static fromItems(...items: TypedValue[]): CompositeValue { - let typeParameters = items.map(value => value.getType()); + let typeParameters = items.map((value) => value.getType()); let type = new CompositeType(...typeParameters); return new CompositeValue(type, items); } @@ -42,7 +42,7 @@ export class CompositeValue extends TypedValue { } valueOf(): any[] { - return this.items.map(item => item?.valueOf()); + return this.items.map((item) => item?.valueOf()); } equals(other: CompositeValue): boolean { diff --git a/src/smartcontracts/typesystem/endpoint.spec.ts b/src/smartcontracts/typesystem/endpoint.spec.ts index 41e7f1f8..b26cdb26 100644 --- a/src/smartcontracts/typesystem/endpoint.spec.ts +++ b/src/smartcontracts/typesystem/endpoint.spec.ts @@ -1,19 +1,18 @@ import { assert } from "chai"; import { EndpointDefinition } from "./endpoint"; - describe("test endpoint", () => { - it('should handle an only-owner modifier', async () => { - const actual = EndpointDefinition.fromJSON({ - name: 'foo', - onlyOwner: true, - mutability: 'payable', - payableInTokens: [], - inputs: [], - outputs: [], - }) + it("should handle an only-owner modifier", async () => { + const actual = EndpointDefinition.fromJSON({ + name: "foo", + onlyOwner: true, + mutability: "payable", + payableInTokens: [], + inputs: [], + outputs: [], + }); - assert.isTrue(actual.modifiers.onlyOwner) - assert.isTrue(actual.modifiers.isOnlyOwner()) - }) + assert.isTrue(actual.modifiers.onlyOwner); + assert.isTrue(actual.modifiers.isOnlyOwner()); + }); }); diff --git a/src/smartcontracts/typesystem/endpoint.ts b/src/smartcontracts/typesystem/endpoint.ts index 4fa0cbdb..9868b72d 100644 --- a/src/smartcontracts/typesystem/endpoint.ts +++ b/src/smartcontracts/typesystem/endpoint.ts @@ -10,7 +10,12 @@ export class EndpointDefinition { readonly output: EndpointParameterDefinition[] = []; readonly modifiers: EndpointModifiers; - constructor(name: string, input: EndpointParameterDefinition[], output: EndpointParameterDefinition[], modifiers: EndpointModifiers) { + constructor( + name: string, + input: EndpointParameterDefinition[], + output: EndpointParameterDefinition[], + modifiers: EndpointModifiers, + ) { this.name = name; this.input = input || []; this.output = output || []; @@ -22,12 +27,12 @@ export class EndpointDefinition { } static fromJSON(json: { - name: string, - onlyOwner?: boolean - mutability: string, - payableInTokens: string[], - inputs: any[], - outputs: any[] + name: string; + onlyOwner?: boolean; + mutability: string; + payableInTokens: string[]; + inputs: any[]; + outputs: any[]; }): EndpointDefinition { json.name = json.name == null ? NamePlaceholder : json.name; json.onlyOwner = json.onlyOwner || false; @@ -35,8 +40,8 @@ export class EndpointDefinition { json.inputs = json.inputs || []; json.outputs = json.outputs || []; - let input = json.inputs.map(param => EndpointParameterDefinition.fromJSON(param)); - let output = json.outputs.map(param => EndpointParameterDefinition.fromJSON(param)); + let input = json.inputs.map((param) => EndpointParameterDefinition.fromJSON(param)); + let output = json.outputs.map((param) => EndpointParameterDefinition.fromJSON(param)); let modifiers = new EndpointModifiers(json.mutability, json.payableInTokens, json.onlyOwner); return new EndpointDefinition(json.name, input, output, modifiers); @@ -98,8 +103,12 @@ export class EndpointParameterDefinition { this.type = type; } - static fromJSON(json: { name?: string, description?: string, type: string }): EndpointParameterDefinition { + static fromJSON(json: { name?: string; description?: string; type: string }): EndpointParameterDefinition { let parsedType = new TypeExpressionParser().parse(json.type); - return new EndpointParameterDefinition(json.name || NamePlaceholder, json.description || DescriptionPlaceholder, parsedType); + return new EndpointParameterDefinition( + json.name || NamePlaceholder, + json.description || DescriptionPlaceholder, + parsedType, + ); } } diff --git a/src/smartcontracts/typesystem/enum.spec.ts b/src/smartcontracts/typesystem/enum.spec.ts index 4e98ab65..50ede8e2 100644 --- a/src/smartcontracts/typesystem/enum.spec.ts +++ b/src/smartcontracts/typesystem/enum.spec.ts @@ -15,23 +15,18 @@ describe("test enums", () => { ]); let orangeVariant = new EnumVariantDefinition("Orange", 1, [ - new FieldDefinition("0", "hex code", new StringType()) + new FieldDefinition("0", "hex code", new StringType()), ]); - let enumType = new EnumType("Colour", [ - greenVariant, - orangeVariant - ]); + let enumType = new EnumType("Colour", [greenVariant, orangeVariant]); let green = new EnumValue(enumType, greenVariant, [ new Field(new U8Value(0), "0"), new Field(new U8Value(255), "1"), - new Field(new U8Value(0), "2") + new Field(new U8Value(0), "2"), ]); - let orange = new EnumValue(enumType, orangeVariant, [ - new Field(new StringValue("#FFA500"), "0") - ]); + let orange = new EnumValue(enumType, orangeVariant, [new Field(new StringValue("#FFA500"), "0")]); assert.lengthOf(green.getFields(), 3); assert.lengthOf(orange.getFields(), 1); @@ -52,7 +47,7 @@ describe("test enums", () => { ]); let orangeVariant = new EnumVariantDefinition("Orange", 1, [ - new FieldDefinition("0", "hex code", new StringType()) + new FieldDefinition("0", "hex code", new StringType()), ]); let yellowVariant = new EnumVariantDefinition("Yellow", 2, [ @@ -62,54 +57,37 @@ describe("test enums", () => { ]); // Define enum type - let enumType = new EnumType("Colour", [ - greenVariant, - orangeVariant, - yellowVariant - ]); + let enumType = new EnumType("Colour", [greenVariant, orangeVariant, yellowVariant]); // Create enum values let green = new EnumValue(enumType, greenVariant, [ new Field(new U8Value(0), "0"), new Field(new U8Value(255), "1"), - new Field(new U8Value(0), "2") + new Field(new U8Value(0), "2"), ]); - let orange = new EnumValue(enumType, orangeVariant, [ - new Field(new StringValue("#FFA500"), "0") - ]); + let orange = new EnumValue(enumType, orangeVariant, [new Field(new StringValue("#FFA500"), "0")]); let yellow = new EnumValue(enumType, yellowVariant, [ new Field(new U8Value(255), "red"), new Field(new U8Value(255), "green"), - new Field(new U8Value(0), "blue") + new Field(new U8Value(0), "blue"), ]); // Test valueOf() assert.deepEqual(green.valueOf(), { - "name": "Green", - "fields": [ - new BigNumber(0), - new BigNumber(255), - new BigNumber(0) - ] + name: "Green", + fields: [new BigNumber(0), new BigNumber(255), new BigNumber(0)], }); assert.deepEqual(orange.valueOf(), { - "name": "Orange", - "fields": [ - "#FFA500" - ] + name: "Orange", + fields: ["#FFA500"], }); assert.deepEqual(yellow.valueOf(), { - "name": "Yellow", - "fields": [ - new BigNumber(255), - new BigNumber(255), - new BigNumber(0) - ] + name: "Yellow", + fields: [new BigNumber(255), new BigNumber(255), new BigNumber(0)], }); }); }); - diff --git a/src/smartcontracts/typesystem/enum.ts b/src/smartcontracts/typesystem/enum.ts index 1320a4b4..a0a2b24d 100644 --- a/src/smartcontracts/typesystem/enum.ts +++ b/src/smartcontracts/typesystem/enum.ts @@ -35,8 +35,8 @@ export class EnumType extends CustomType { return variants.map((variant, index) => { return { ...variant, - discriminant: index - } + discriminant: index, + }; }); } @@ -71,7 +71,7 @@ export class EnumVariantDefinition { constructor(name: string, discriminant: number, fieldsDefinitions: FieldDefinition[] = []) { guardTrue( discriminant < SimpleEnumMaxDiscriminant, - `discriminant for simple enum should be less than ${SimpleEnumMaxDiscriminant}` + `discriminant for simple enum should be less than ${SimpleEnumMaxDiscriminant}`, ); this.name = name; @@ -89,7 +89,7 @@ export class EnumVariantDefinition { } getFieldDefinition(name: string): FieldDefinition | undefined { - return this.fieldsDefinitions.find(item => item.name == name); + return this.fieldsDefinitions.find((item) => item.name == name); } getNamesOfDependencies(): string[] { @@ -109,7 +109,7 @@ export class EnumValue extends TypedValue { this.name = variant.name; this.discriminant = variant.discriminant; this.fields = fields; - this.fieldsByName = new Map(fields.map(field => [field.name, field])); + this.fieldsByName = new Map(fields.map((field) => [field.name, field])); let definitions = variant.getFieldsDefinitions(); Fields.checkTyping(this.fields, definitions); diff --git a/src/smartcontracts/typesystem/event.ts b/src/smartcontracts/typesystem/event.ts index 5b4dcac6..f358b468 100644 --- a/src/smartcontracts/typesystem/event.ts +++ b/src/smartcontracts/typesystem/event.ts @@ -12,14 +12,11 @@ export class EventDefinition { this.inputs = inputs || []; } - static fromJSON(json: { - identifier: string, - inputs: any[] - }): EventDefinition { + static fromJSON(json: { identifier: string; inputs: any[] }): EventDefinition { json.identifier = json.identifier == null ? NamePlaceholder : json.identifier; json.inputs = json.inputs || []; - const inputs = json.inputs.map(param => EventTopicDefinition.fromJSON(param)); + const inputs = json.inputs.map((param) => EventTopicDefinition.fromJSON(param)); return new EventDefinition(json.identifier, inputs); } } @@ -29,19 +26,19 @@ export class EventTopicDefinition { readonly type: Type; readonly indexed: boolean; - constructor(options: { name: string, type: Type, indexed: boolean }) { + constructor(options: { name: string; type: Type; indexed: boolean }) { this.name = options.name; this.type = options.type; this.indexed = options.indexed; } - static fromJSON(json: { name?: string, type: string, indexed: boolean }): EventTopicDefinition { + static fromJSON(json: { name?: string; type: string; indexed: boolean }): EventTopicDefinition { const parsedType = new TypeExpressionParser().parse(json.type); return new EventTopicDefinition({ name: json.name || NamePlaceholder, type: parsedType, - indexed: json.indexed + indexed: json.indexed, }); } } diff --git a/src/smartcontracts/typesystem/factory.ts b/src/smartcontracts/typesystem/factory.ts index b4870829..651de575 100644 --- a/src/smartcontracts/typesystem/factory.ts +++ b/src/smartcontracts/typesystem/factory.ts @@ -4,13 +4,13 @@ import { List } from "./generic"; import { TokenIdentifierValue } from "./tokenIdentifier"; export function createListOfAddresses(addresses: Address[]): List { - let addressesTyped = addresses.map(address => new AddressValue(address)); + let addressesTyped = addresses.map((address) => new AddressValue(address)); let list = List.fromItems(addressesTyped); return list; } export function createListOfTokenIdentifiers(identifiers: string[]): List { - let identifiersTyped = identifiers.map(identifier => new TokenIdentifierValue(identifier)); + let identifiersTyped = identifiers.map((identifier) => new TokenIdentifierValue(identifier)); let list = List.fromItems(identifiersTyped); return list; } diff --git a/src/smartcontracts/typesystem/fields.ts b/src/smartcontracts/typesystem/fields.ts index c281df94..d8953cce 100644 --- a/src/smartcontracts/typesystem/fields.ts +++ b/src/smartcontracts/typesystem/fields.ts @@ -13,7 +13,7 @@ export class FieldDefinition { this.type = type; } - static fromJSON(json: { name: string, description: string, type: string }): FieldDefinition { + static fromJSON(json: { name: string; description: string; type: string }): FieldDefinition { let parsedType = new TypeExpressionParser().parse(json.type); return new FieldDefinition(json.name, json.description, parsedType); } @@ -32,7 +32,9 @@ export class Field { const actualType: Type = this.value.getType(); if (!actualType.equals(expectedDefinition.type)) { - throw new errors.ErrTypingSystem(`check type of field "${expectedDefinition.name}; expected: ${expectedDefinition.type}, actual: ${actualType}"`); + throw new errors.ErrTypingSystem( + `check type of field "${expectedDefinition.name}; expected: ${expectedDefinition.type}, actual: ${actualType}"`, + ); } if (this.name != expectedDefinition.name) { throw new errors.ErrTypingSystem(`check name of field "${expectedDefinition.name}"`); @@ -53,7 +55,7 @@ export class Fields { for (let i = 0; i < fields.length; i++) { let field = fields[i]; let definition = definitions[i]; - + field.checkTyping(definition); } } diff --git a/src/smartcontracts/typesystem/generic.ts b/src/smartcontracts/typesystem/generic.ts index c8b540ea..cfce5eb1 100644 --- a/src/smartcontracts/typesystem/generic.ts +++ b/src/smartcontracts/typesystem/generic.ts @@ -15,7 +15,7 @@ export class OptionType extends Type { } isAssignableFrom(type: Type): boolean { - if (!(type.hasExactClass(OptionType.ClassName))) { + if (!type.hasExactClass(OptionType.ClassName)) { return false; } diff --git a/src/smartcontracts/typesystem/index.ts b/src/smartcontracts/typesystem/index.ts index 4e79b555..f7bc39d4 100644 --- a/src/smartcontracts/typesystem/index.ts +++ b/src/smartcontracts/typesystem/index.ts @@ -27,4 +27,3 @@ export * from "./typeExpressionParser"; export * from "./typeMapper"; export * from "./types"; export * from "./variadic"; - diff --git a/src/smartcontracts/typesystem/matchers.ts b/src/smartcontracts/typesystem/matchers.ts index c34e98e8..43957d53 100644 --- a/src/smartcontracts/typesystem/matchers.ts +++ b/src/smartcontracts/typesystem/matchers.ts @@ -27,7 +27,7 @@ export function onTypeSelect( onTuple: () => TResult; onEnum: () => TResult; onOther?: () => TResult; - } + }, ): TResult { if (type.hasExactClass(OptionType.ClassName)) { return selectors.onOption(); @@ -69,7 +69,7 @@ export function onTypedValueSelect( onTuple: () => TResult; onEnum: () => TResult; onOther?: () => TResult; - } + }, ): TResult { if (value.hasClassOrSuperclass(PrimitiveValue.ClassName)) { return selectors.onPrimitive(); @@ -112,7 +112,7 @@ export function onPrimitiveValueSelect( onTypeIdentifier: () => TResult; onNothing: () => TResult; onOther?: () => TResult; - } + }, ): TResult { if (value.hasExactClass(BooleanValue.ClassName)) { return selectors.onBoolean(); @@ -157,7 +157,7 @@ export function onPrimitiveTypeSelect( onTokenIndetifier: () => TResult; onNothing: () => TResult; onOther?: () => TResult; - } + }, ): TResult { if (type.hasExactClass(BooleanType.ClassName)) { return selectors.onBoolean(); diff --git a/src/smartcontracts/typesystem/struct.spec.ts b/src/smartcontracts/typesystem/struct.spec.ts index ae763996..36209019 100644 --- a/src/smartcontracts/typesystem/struct.spec.ts +++ b/src/smartcontracts/typesystem/struct.spec.ts @@ -8,15 +8,12 @@ import { TokenIdentifierType, TokenIdentifierValue } from "./tokenIdentifier"; describe("test structs", () => { it("should get fields", () => { - let fooType = new StructType( - "Foo", - [ - new FieldDefinition("a", "", new TokenIdentifierType()), - new FieldDefinition("b", "", new BigUIntType()), - new FieldDefinition("c", "", new U32Type()), - new FieldDefinition("d", "", new BytesType()), - ] - ); + let fooType = new StructType("Foo", [ + new FieldDefinition("a", "", new TokenIdentifierType()), + new FieldDefinition("b", "", new BigUIntType()), + new FieldDefinition("c", "", new U32Type()), + new FieldDefinition("d", "", new BytesType()), + ]); let fooStruct = new Struct(fooType, [ new Field(new TokenIdentifierValue("lucky-token"), "a"), diff --git a/src/smartcontracts/typesystem/struct.ts b/src/smartcontracts/typesystem/struct.ts index 5483aa8d..94e367f8 100644 --- a/src/smartcontracts/typesystem/struct.ts +++ b/src/smartcontracts/typesystem/struct.ts @@ -15,8 +15,8 @@ export class StructType extends CustomType { return StructType.ClassName; } - static fromJSON(json: { name: string, fields: any[] }): StructType { - let definitions = (json.fields || []).map(definition => FieldDefinition.fromJSON(definition)); + static fromJSON(json: { name: string; fields: any[] }): StructType { + let definitions = (json.fields || []).map((definition) => FieldDefinition.fromJSON(definition)); return new StructType(json.name, definitions); } @@ -25,7 +25,7 @@ export class StructType extends CustomType { } getFieldDefinition(name: string): FieldDefinition | undefined { - return this.fieldsDefinitions.find(item => item.name == name); + return this.fieldsDefinitions.find((item) => item.name == name); } getNamesOfDependencies(): string[] { @@ -44,7 +44,7 @@ export class Struct extends TypedValue { constructor(type: StructType, fields: Field[]) { super(type); this.fields = fields; - this.fieldsByName = new Map(fields.map(field => [field.name, field])); + this.fieldsByName = new Map(fields.map((field) => [field.name, field])); this.checkTyping(); } diff --git a/src/smartcontracts/typesystem/tokenIdentifier.ts b/src/smartcontracts/typesystem/tokenIdentifier.ts index 7ea324cf..5fea9d8b 100644 --- a/src/smartcontracts/typesystem/tokenIdentifier.ts +++ b/src/smartcontracts/typesystem/tokenIdentifier.ts @@ -24,7 +24,7 @@ export class TokenIdentifierValue extends PrimitiveValue { } static egld(): TokenIdentifierValue { - return new TokenIdentifierValue(EGLDTokenIdentifier) + return new TokenIdentifierValue(EGLDTokenIdentifier); } static esdtTokenIdentifier(identifier: string): TokenIdentifierValue { @@ -46,7 +46,7 @@ export class TokenIdentifierValue extends PrimitiveValue { if (this.getLength() != other.getLength()) { return false; } - + return this.value == other.value; } diff --git a/src/smartcontracts/typesystem/tuple.ts b/src/smartcontracts/typesystem/tuple.ts index caaf7fd4..f249913d 100644 --- a/src/smartcontracts/typesystem/tuple.ts +++ b/src/smartcontracts/typesystem/tuple.ts @@ -15,13 +15,15 @@ export class TupleType extends StructType { } private static prepareName(typeParameters: Type[]): string { - let fields: string = typeParameters.map(type => type.toString()).join(", "); + let fields: string = typeParameters.map((type) => type.toString()).join(", "); let result = `tuple<${fields}>`; return result; } private static prepareFieldDefinitions(typeParameters: Type[]): FieldDefinition[] { - let result = typeParameters.map((type, i) => new FieldDefinition(prepareFieldName(i), "anonymous tuple field", type)); + let result = typeParameters.map( + (type, i) => new FieldDefinition(prepareFieldName(i), "anonymous tuple field", type), + ); return result; } } @@ -50,7 +52,7 @@ export class Tuple extends Struct { throw new errors.ErrTypingSystem("bad tuple items"); } - let fieldsTypes = items.map(item => item.getType()); + let fieldsTypes = items.map((item) => item.getType()); let tupleType = new TupleType(...fieldsTypes); let fields = items.map((item, i) => new Field(item, prepareFieldName(i))); diff --git a/src/smartcontracts/typesystem/typeMapper.spec.ts b/src/smartcontracts/typesystem/typeMapper.spec.ts index 987f16e3..130d511b 100644 --- a/src/smartcontracts/typesystem/typeMapper.spec.ts +++ b/src/smartcontracts/typesystem/typeMapper.spec.ts @@ -39,10 +39,14 @@ describe("test mapper", () => { }); it("should map complex generic, composite, variadic types", () => { - testMapping("MultiResultVec>", new VariadicType( - new CompositeType(new I32Type(), new BytesType()), - )); - testMapping("VarArgs>", new VariadicType(new CompositeType(new I32Type(), new BytesType()))); + testMapping( + "MultiResultVec>", + new VariadicType(new CompositeType(new I32Type(), new BytesType())), + ); + testMapping( + "VarArgs>", + new VariadicType(new CompositeType(new I32Type(), new BytesType())), + ); testMapping("OptionalResult
", new OptionalType(new AddressType())); }); diff --git a/src/smartcontracts/typesystem/typeMapper.ts b/src/smartcontracts/typesystem/typeMapper.ts index 110c37fc..edc40769 100644 --- a/src/smartcontracts/typesystem/typeMapper.ts +++ b/src/smartcontracts/typesystem/typeMapper.ts @@ -21,7 +21,7 @@ import { U16Type, U32Type, U64Type, - U8Type + U8Type, } from "./numerical"; import { StringType } from "./string"; import { StructType } from "./struct"; @@ -99,7 +99,7 @@ export class TypeMapper { ["EgldOrEsdtTokenIdentifier", new TokenIdentifierType()], ["CodeMetadata", new CodeMetadataType()], ["nothing", new NothingType()], - ["AsyncCall", new NothingType()] + ["AsyncCall", new NothingType()], ]); this.learnedTypesMap = new Map(); @@ -180,8 +180,8 @@ export class TypeMapper { new EnumVariantDefinition( variant.name, variant.discriminant, - this.mappedFields(variant.getFieldsDefinitions()) - ) + this.mappedFields(variant.getFieldsDefinitions()), + ), ); let mappedEnum = new EnumType(type.getName(), variants); return mappedEnum; @@ -189,7 +189,7 @@ export class TypeMapper { private mappedFields(definitions: FieldDefinition[]): FieldDefinition[] { return definitions.map( - (definition) => new FieldDefinition(definition.name, definition.description, this.mapType(definition.type)) + (definition) => new FieldDefinition(definition.name, definition.description, this.mapType(definition.type)), ); } diff --git a/src/smartcontracts/typesystem/types.spec.ts b/src/smartcontracts/typesystem/types.spec.ts index 22f87769..0639b961 100644 --- a/src/smartcontracts/typesystem/types.spec.ts +++ b/src/smartcontracts/typesystem/types.spec.ts @@ -19,19 +19,19 @@ describe("test types", () => { }); it("should be assignable from", () => { - assert.isTrue((new Type("Type")).isAssignableFrom(new PrimitiveType("PrimitiveType"))); - assert.isTrue((new Type("Type")).isAssignableFrom(new BooleanType())); - assert.isTrue((new Type("Type")).isAssignableFrom(new AddressType())); - assert.isTrue((new Type("Type")).isAssignableFrom(new U32Type())); + assert.isTrue(new Type("Type").isAssignableFrom(new PrimitiveType("PrimitiveType"))); + assert.isTrue(new Type("Type").isAssignableFrom(new BooleanType())); + assert.isTrue(new Type("Type").isAssignableFrom(new AddressType())); + assert.isTrue(new Type("Type").isAssignableFrom(new U32Type())); - assert.isTrue((new PrimitiveType("PrimitiveType")).isAssignableFrom(new BooleanType())); - assert.isTrue((new PrimitiveType("PrimitiveType")).isAssignableFrom(new AddressType())); - assert.isTrue((new PrimitiveType("PrimitiveType")).isAssignableFrom(new U32Type())); + assert.isTrue(new PrimitiveType("PrimitiveType").isAssignableFrom(new BooleanType())); + assert.isTrue(new PrimitiveType("PrimitiveType").isAssignableFrom(new AddressType())); + assert.isTrue(new PrimitiveType("PrimitiveType").isAssignableFrom(new U32Type())); - assert.isTrue((new AddressType()).isAssignableFrom(new AddressType())); - assert.isFalse((new AddressType()).isAssignableFrom(new BooleanType())); - assert.isFalse((new U32Type()).isAssignableFrom(new BooleanType())); - assert.isFalse((new U32Type()).isAssignableFrom(new PrimitiveType("PrimitiveType"))); + assert.isTrue(new AddressType().isAssignableFrom(new AddressType())); + assert.isFalse(new AddressType().isAssignableFrom(new BooleanType())); + assert.isFalse(new U32Type().isAssignableFrom(new BooleanType())); + assert.isFalse(new U32Type().isAssignableFrom(new PrimitiveType("PrimitiveType"))); assert.isTrue(new BytesType().isAssignableFrom(new BytesType())); assert.isTrue(new U32Type().isAssignableFrom(parser.parse("u32"))); @@ -54,17 +54,32 @@ describe("test types", () => { it("should get fully qualified name", () => { assert.equal(new Type("foo").getFullyQualifiedName(), "multiversx:types:foo"); assert.equal(new U32Type().getFullyQualifiedName(), "multiversx:types:u32"); - assert.equal(parser.parse("MultiResultVec").getFullyQualifiedName(), "multiversx:types:MultiResultVec"); + assert.equal( + parser.parse("MultiResultVec").getFullyQualifiedName(), + "multiversx:types:MultiResultVec", + ); assert.equal(parser.parse("utf-8 string").getFullyQualifiedName(), "multiversx:types:utf-8 string"); - assert.equal(parser.parse("Option").getFullyQualifiedName(), "multiversx:types:Option"); + assert.equal( + parser.parse("Option").getFullyQualifiedName(), + "multiversx:types:Option", + ); }); it("types and values should have correct JavaScript class hierarchy", () => { assert.deepEqual(new U32Type().getClassHierarchy(), ["Type", "PrimitiveType", "NumericalType", "U32Type"]); - assert.deepEqual(new U32Value(42).getClassHierarchy(), ["TypedValue", "PrimitiveValue", "NumericalValue", "U32Value"]); + assert.deepEqual(new U32Value(42).getClassHierarchy(), [ + "TypedValue", + "PrimitiveValue", + "NumericalValue", + "U32Value", + ]); assert.deepEqual(new BytesType().getClassHierarchy(), ["Type", "PrimitiveType", "BytesType"]); - assert.deepEqual(new BytesValue(Buffer.from("foobar")).getClassHierarchy(), ["TypedValue", "PrimitiveValue", "BytesValue"]); + assert.deepEqual(new BytesValue(Buffer.from("foobar")).getClassHierarchy(), [ + "TypedValue", + "PrimitiveValue", + "BytesValue", + ]); }); it("should report type dependencies", () => { diff --git a/src/smartcontracts/typesystem/types.ts b/src/smartcontracts/typesystem/types.ts index 007b780c..b3e68d5b 100644 --- a/src/smartcontracts/typesystem/types.ts +++ b/src/smartcontracts/typesystem/types.ts @@ -12,7 +12,11 @@ export class Type { private readonly typeParameters: Type[]; protected readonly cardinality: TypeCardinality; - public constructor(name: string, typeParameters: Type[] = [], cardinality: TypeCardinality = TypeCardinality.fixed(1)) { + public constructor( + name: string, + typeParameters: Type[] = [], + cardinality: TypeCardinality = TypeCardinality.fixed(1), + ) { guardValueIsSet("name", name); this.name = name; @@ -29,8 +33,8 @@ export class Type { } getClassHierarchy(): string[] { - let prototypes = getJavascriptPrototypesInHierarchy(this, prototype => prototype.belongsToTypesystem); - let classNames = prototypes.map(prototype => (prototype).getClassName()).reverse(); + let prototypes = getJavascriptPrototypesInHierarchy(this, (prototype) => prototype.belongsToTypesystem); + let classNames = prototypes.map((prototype) => (prototype).getClassName()).reverse(); return classNames; } @@ -38,11 +42,13 @@ export class Type { * Gets the fully qualified name of the type, to allow for better (efficient and non-ambiguous) type comparison within the custom typesystem. */ getFullyQualifiedName(): string { - let joinedTypeParameters = this.getTypeParameters().map(type => type.getFullyQualifiedName()).join(", "); + let joinedTypeParameters = this.getTypeParameters() + .map((type) => type.getFullyQualifiedName()) + .join(", "); - return this.isGenericType() ? - `multiversx:types:${this.getName()}<${joinedTypeParameters}>` : - `multiversx:types:${this.getName()}`; + return this.isGenericType() + ? `multiversx:types:${this.getName()}<${joinedTypeParameters}>` + : `multiversx:types:${this.getName()}`; } hasExactClass(className: string): boolean { @@ -68,10 +74,12 @@ export class Type { } /** - * Generates type expressions similar to mx-sdk-rs. + * Generates type expressions similar to mx-sdk-rs. */ toString() { - let typeParameters: string = this.getTypeParameters().map(type => type.toString()).join(", "); + let typeParameters: string = this.getTypeParameters() + .map((type) => type.toString()) + .join(", "); let typeParametersExpression = typeParameters ? `<${typeParameters}>` : ""; return `${this.name}${typeParametersExpression}`; } @@ -103,11 +111,11 @@ export class Type { /** * Inspired from: https://docs.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom * For (most) generics, type invariance is expected (assumed) - neither covariance, nor contravariance are supported yet (will be supported in a next release). - * + * * One exception though: for {@link OptionType}, we simulate covariance for missing (not provided) values. * For example, Option is assignable from Option. * For more details, see the implementation of {@link OptionType} and @{@link OptionalType}. - * + * * Also see: * - https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science) * - https://docs.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance @@ -128,8 +136,8 @@ export class Type { } private static getFullyQualifiedNamesInHierarchy(type: Type): string[] { - let prototypes: any[] = getJavascriptPrototypesInHierarchy(type, prototype => prototype.belongsToTypesystem); - let fullyQualifiedNames = prototypes.map(prototype => prototype.getFullyQualifiedName.call(type)); + let prototypes: any[] = getJavascriptPrototypesInHierarchy(type, (prototype) => prototype.belongsToTypesystem); + let fullyQualifiedNames = prototypes.map((prototype) => prototype.getFullyQualifiedName.call(type)); return fullyQualifiedNames; } @@ -150,7 +158,7 @@ export class Type { toJSON(): any { return { name: this.name, - typeParameters: this.typeParameters.map(item => item.toJSON()) + typeParameters: this.typeParameters.map((item) => item.toJSON()), }; } @@ -161,14 +169,14 @@ export class Type { /** * A special marker for types within the custom typesystem. */ - belongsToTypesystem() { } + belongsToTypesystem() {} } /** * TODO: Simplify this class, keep only what is needed. - * + * * An abstraction for defining and operating with the cardinality of a (composite or simple) type. - * + * * Simple types (the ones that are directly encodable) have a fixed cardinality: [lower = 1, upper = 1]. * Composite types (not directly encodable) do not follow this constraint. For example: * - VarArgs: [lower = 0, upper = *] @@ -254,8 +262,8 @@ export abstract class TypedValue { } getClassHierarchy(): string[] { - let prototypes = getJavascriptPrototypesInHierarchy(this, prototype => prototype.belongsToTypesystem); - let classNames = prototypes.map(prototype => (prototype).getClassName()).reverse(); + let prototypes = getJavascriptPrototypesInHierarchy(this, (prototype) => prototype.belongsToTypesystem); + let classNames = prototypes.map((prototype) => (prototype).getClassName()).reverse(); return classNames; } @@ -278,7 +286,7 @@ export abstract class TypedValue { /** * A special marker for values within the custom typesystem. */ - belongsToTypesystem() { } + belongsToTypesystem() {} } export abstract class PrimitiveValue extends TypedValue { @@ -309,7 +317,6 @@ export class TypePlaceholder extends Type { } } - export class NullType extends Type { static ClassName = "NullType"; diff --git a/src/testutils/mockProvider.ts b/src/testutils/mockProvider.ts index 884ca649..fc867a6c 100644 --- a/src/testutils/mockProvider.ts +++ b/src/testutils/mockProvider.ts @@ -1,10 +1,21 @@ -import { ContractResultItem, ContractResults, TransactionOnNetwork, TransactionStatus } from "@multiversx/sdk-network-providers"; +import { + ContractResultItem, + ContractResults, + TransactionOnNetwork, + TransactionStatus, +} from "@multiversx/sdk-network-providers"; import { Address } from "../address"; import { AsyncTimer } from "../asyncTimer"; import * as errors from "../errors"; import { ErrMock } from "../errors"; import { IAddress } from "../interface"; -import { IAccountOnNetwork, IContractQueryResponse, INetworkConfig, ITransactionOnNetwork, ITransactionStatus } from "../interfaceOfNetwork"; +import { + IAccountOnNetwork, + IContractQueryResponse, + INetworkConfig, + ITransactionOnNetwork, + ITransactionStatus, +} from "../interfaceOfNetwork"; import { Query } from "../smartcontracts/query"; import { Transaction, TransactionHash } from "../transaction"; import { createAccountBalance } from "./utils"; @@ -24,18 +35,9 @@ export class MockProvider { this.transactions = new Map(); this.accounts = new Map(); - this.accounts.set( - MockProvider.AddressOfAlice.bech32(), - { nonce: 0, balance: createAccountBalance(1000) } - ); - this.accounts.set( - MockProvider.AddressOfBob.bech32(), - { nonce: 5, balance: createAccountBalance(500) } - ); - this.accounts.set( - MockProvider.AddressOfCarol.bech32(), - { nonce: 42, balance: createAccountBalance(300) } - ); + this.accounts.set(MockProvider.AddressOfAlice.bech32(), { nonce: 0, balance: createAccountBalance(1000) }); + this.accounts.set(MockProvider.AddressOfBob.bech32(), { nonce: 5, balance: createAccountBalance(500) }); + this.accounts.set(MockProvider.AddressOfCarol.bech32(), { nonce: 42, balance: createAccountBalance(300) }); } mockUpdateAccount(address: Address, mutate: (item: IAccountOnNetwork) => void) { @@ -69,7 +71,7 @@ export class MockProvider { let response = new TransactionOnNetwork({ status: new TransactionStatus("executed"), contractResults: new ContractResults([contractResult]), - isCompleted: true + isCompleted: true, }); this.getTransactionResponders.unshift(new GetTransactionResponder(predicate, response)); @@ -109,7 +111,7 @@ export class MockProvider { return account; } - throw new ErrMock("Account not found") + throw new ErrMock("Account not found"); } async sendTransaction(transaction: Transaction): Promise { @@ -119,8 +121,8 @@ export class MockProvider { sender: transaction.getSender(), receiver: transaction.getReceiver(), data: transaction.getData().valueOf(), - status: new TransactionStatus("pending") - }) + status: new TransactionStatus("pending"), + }), ); this.mockTransactionTimeline(transaction, this.nextTransactionTimelinePoints); @@ -176,7 +178,7 @@ export class Wait { } } -export class MarkCompleted { } +export class MarkCompleted {} class QueryContractResponder { readonly matches: (query: Query) => boolean; diff --git a/src/testutils/networkProviders.ts b/src/testutils/networkProviders.ts index 475da761..736a9bed 100644 --- a/src/testutils/networkProviders.ts +++ b/src/testutils/networkProviders.ts @@ -1,6 +1,12 @@ import { ApiNetworkProvider, ProxyNetworkProvider } from "@multiversx/sdk-network-providers"; import { IAddress } from "../interface"; -import { IAccountOnNetwork, IContractQueryResponse, INetworkConfig, ITransactionOnNetwork, ITransactionStatus } from "../interfaceOfNetwork"; +import { + IAccountOnNetwork, + IContractQueryResponse, + INetworkConfig, + ITransactionOnNetwork, + ITransactionStatus, +} from "../interfaceOfNetwork"; import { Query } from "../smartcontracts/query"; import { Transaction } from "../transaction"; diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index 4c59ad5d..252e6b13 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -11,12 +11,12 @@ import axios, { AxiosResponse } from "axios"; import BigNumber from "bignumber.js"; export async function prepareDeployment(obj: { - deployer: TestWallet, - contract: SmartContract, - codePath: string, - initArguments: TypedValue[], - gasLimit: IGasLimit, - chainID: IChainID + deployer: TestWallet; + contract: SmartContract; + codePath: string; + initArguments: TypedValue[]; + gasLimit: IGasLimit; + chainID: IChainID; }): Promise { let contract = obj.contract; let deployer = obj.deployer; @@ -26,13 +26,13 @@ export async function prepareDeployment(obj: { gasLimit: obj.gasLimit, initArguments: obj.initArguments, chainID: obj.chainID, - deployer: deployer.address + deployer: deployer.address, }); let nonce = deployer.account.getNonceThenIncrement(); let contractAddress = SmartContract.computeAddress(deployer.address, nonce); transaction.setNonce(nonce); - transaction.setSender(deployer.address) + transaction.setSender(deployer.address); contract.setAddress(contractAddress); transaction.applySignature(await deployer.signer.sign(transaction.serializeForSigning())); @@ -42,11 +42,11 @@ export async function prepareDeployment(obj: { export async function loadContractCode(path: PathLike): Promise { if (isOnBrowserTests()) { let response: AxiosResponse = await axios.get(path.toString(), { - responseType: 'arraybuffer', + responseType: "arraybuffer", transformResponse: [], headers: { - "Accept": "application/wasm" - } + Accept: "application/wasm", + }, }); let buffer = Buffer.from(response.data); diff --git a/src/testutils/wallets.ts b/src/testutils/wallets.ts index fefefb05..e86ce05c 100644 --- a/src/testutils/wallets.ts +++ b/src/testutils/wallets.ts @@ -23,8 +23,21 @@ export async function syncTestWallets(wallets: Record, provi } export async function loadTestWallets(): Promise> { - let walletNames = ["alice", "bob", "carol", "dan", "eve", "frank", "grace", "heidi", "ivan", "judy", "mallory", "mike"]; - let wallets = await Promise.all(walletNames.map(async name => await loadTestWallet(name))); + let walletNames = [ + "alice", + "bob", + "carol", + "dan", + "eve", + "frank", + "grace", + "heidi", + "ivan", + "judy", + "mallory", + "mike", + ]; + let wallets = await Promise.all(walletNames.map(async (name) => await loadTestWallet(name))); let walletMap: Record = {}; for (let i in walletNames) { walletMap[walletNames[i]] = wallets[i]; @@ -44,11 +57,7 @@ export async function loadTestWallet(name: string): Promise { let jsonContents = JSON.parse(await readTestWalletFileContents(name + ".json")); let pemContents = await readTestWalletFileContents(name + ".pem"); let pemKey = UserSecretKey.fromPem(pemContents); - return new TestWallet( - new Address(jsonContents.address), - pemKey.hex(), - jsonContents, - pemContents); + return new TestWallet(new Address(jsonContents.address), pemKey.hex(), jsonContents, pemContents); } async function readTestWalletFileContents(name: string): Promise { diff --git a/src/tokenTransfer.spec.ts b/src/tokenTransfer.spec.ts index 5a891869..274121a7 100644 --- a/src/tokenTransfer.spec.ts +++ b/src/tokenTransfer.spec.ts @@ -19,7 +19,10 @@ describe("test token transfer", () => { assert.equal(TokenTransfer.egldFromAmount(100).toPrettyString(), "100.000000000000000000 EGLD"); assert.equal(TokenTransfer.egldFromAmount(1000).toPrettyString(), "1000.000000000000000000 EGLD"); assert.equal(TokenTransfer.egldFromAmount("0.123456789").toPrettyString(), "0.123456789000000000 EGLD"); - assert.equal(TokenTransfer.egldFromAmount("0.123456789123456789777777888888").toPrettyString(), "0.123456789123456789 EGLD"); + assert.equal( + TokenTransfer.egldFromAmount("0.123456789123456789777777888888").toPrettyString(), + "0.123456789123456789 EGLD", + ); assert.equal(TokenTransfer.egldFromBigInteger("1").toString(), "1"); assert.equal(TokenTransfer.egldFromBigInteger("1").toPrettyString(), "0.000000000000000001 EGLD"); @@ -34,7 +37,10 @@ describe("test token transfer", () => { assert.equal(TokenTransfer.fungibleFromAmount(identifier, "0.1", numDecimals).toString(), "100000"); assert.equal(TokenTransfer.fungibleFromAmount(identifier, "0.123456789", numDecimals).toString(), "123456"); assert.equal(TokenTransfer.fungibleFromBigInteger(identifier, "1000000", numDecimals).toString(), "1000000"); - assert.equal(TokenTransfer.fungibleFromBigInteger(identifier, "1000000", numDecimals).toPrettyString(), "1.000000 USDC-c76f1f"); + assert.equal( + TokenTransfer.fungibleFromBigInteger(identifier, "1000000", numDecimals).toPrettyString(), + "1.000000 USDC-c76f1f", + ); }); it("should work with MetaESDT", () => { diff --git a/src/tokenTransfer.ts b/src/tokenTransfer.ts index c0dff5aa..ab81d89a 100644 --- a/src/tokenTransfer.ts +++ b/src/tokenTransfer.ts @@ -51,7 +51,11 @@ export class TokenTransfer { return this.fungibleFromBigInteger(tokenIdentifier, amountAsBigInteger, numDecimals); } - static fungibleFromBigInteger(tokenIdentifier: string, amountAsBigInteger: BigNumber.Value, numDecimals: number = 0) { + static fungibleFromBigInteger( + tokenIdentifier: string, + amountAsBigInteger: BigNumber.Value, + numDecimals: number = 0, + ) { return new TokenTransfer({ tokenIdentifier, nonce: 0, @@ -83,7 +87,12 @@ export class TokenTransfer { return this.metaEsdtFromBigInteger(tokenIdentifier, nonce, amountAsBigInteger, numDecimals); } - static metaEsdtFromBigInteger(tokenIdentifier: string, nonce: number, amountAsBigInteger: BigNumber.Value, numDecimals = 0) { + static metaEsdtFromBigInteger( + tokenIdentifier: string, + nonce: number, + amountAsBigInteger: BigNumber.Value, + numDecimals = 0, + ) { return new TokenTransfer({ tokenIdentifier, nonce, @@ -129,4 +138,4 @@ export class TokenPayment extends TokenTransfer { numDecimals, }); } -}; +} diff --git a/src/tokenTransferBuilders.spec.ts b/src/tokenTransferBuilders.spec.ts index f9ff0152..abddcb37 100644 --- a/src/tokenTransferBuilders.spec.ts +++ b/src/tokenTransferBuilders.spec.ts @@ -1,7 +1,11 @@ import { assert } from "chai"; import { Address } from "./address"; import { TokenTransfer } from "./tokenTransfer"; -import { ESDTNFTTransferPayloadBuilder, ESDTTransferPayloadBuilder, MultiESDTNFTTransferPayloadBuilder } from "./tokenTransferBuilders"; +import { + ESDTNFTTransferPayloadBuilder, + ESDTTransferPayloadBuilder, + MultiESDTNFTTransferPayloadBuilder, +} from "./tokenTransferBuilders"; describe("test token transfer builders", () => { it("should work with ESDT transfers", () => { @@ -17,7 +21,10 @@ describe("test token transfer builders", () => { .setDestination(new Address("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx")) .build(); - assert.equal(payload.toString(), "ESDTNFTTransfer@4552444a532d333866323439@01@01@8049d639e5a6980d1cd2392abcce41029cda74a1563523a202f09641cc2618f8"); + assert.equal( + payload.toString(), + "ESDTNFTTransfer@4552444a532d333866323439@01@01@8049d639e5a6980d1cd2392abcce41029cda74a1563523a202f09641cc2618f8", + ); }); it("should work with ESDTNFT transfers (SFT)", () => { @@ -28,7 +35,10 @@ describe("test token transfer builders", () => { .setDestination(new Address("erd1testnlersh4z0wsv8kjx39me4rmnvjkwu8dsaea7ukdvvc9z396qykv7z7")) .build(); - assert.equal(payload.toString(), "ESDTNFTTransfer@53454d492d396566643066@01@05@5e60b9ff2385ea27ba0c3da4689779a8f7364acee1db0ee7bee59ac660a28974"); + assert.equal( + payload.toString(), + "ESDTNFTTransfer@53454d492d396566643066@01@05@5e60b9ff2385ea27ba0c3da4689779a8f7364acee1db0ee7bee59ac660a28974", + ); }); it("should work with Multi ESDTNFT transfers", () => { @@ -39,6 +49,9 @@ describe("test token transfer builders", () => { .setDestination(new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th")) .build(); - assert.equal(payload.toString(), "MultiESDTNFTTransfer@0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1@02@4552444a532d333866323439@01@01@4241522d633830643239@@8ac7230489e80000"); + assert.equal( + payload.toString(), + "MultiESDTNFTTransfer@0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1@02@4552444a532d333866323439@01@01@4241522d633830643239@@8ac7230489e80000", + ); }); }); diff --git a/src/tokens.ts b/src/tokens.ts index b0020339..e6d18c28 100644 --- a/src/tokens.ts +++ b/src/tokens.ts @@ -22,7 +22,7 @@ export class NextTokenTransfer { } export class TokenComputer { - constructor() { } + constructor() {} isFungible(token: Token): boolean { return token.nonce === 0; @@ -72,7 +72,7 @@ export class TokenComputer { if (randomSequence.length !== TOKEN_RANDOM_SEQUENCE_LENGTH) { throw new ErrInvalidTokenIdentifier( - "The identifier is not valid. The random sequence does not have the right length" + "The identifier is not valid. The random sequence does not have the right length", ); } } @@ -83,7 +83,7 @@ export class TokenComputer { if (ticker.length < MIN_TICKER_LENGTH || ticker.length > MAX_TICKER_LENGTH) { throw new ErrInvalidTokenIdentifier( - `The token ticker should be between ${MIN_TICKER_LENGTH} and ${MAX_TICKER_LENGTH} characters` + `The token ticker should be between ${MIN_TICKER_LENGTH} and ${MAX_TICKER_LENGTH} characters`, ); } diff --git a/src/utils.ts b/src/utils.ts index 7b1a78b5..dd72af65 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -37,19 +37,19 @@ export function guardLength(withLength: { length?: number }, expectedLength: num } } -export function guardNotEmpty(value: { isEmpty?: () => boolean, length?: number }, what: string) { +export function guardNotEmpty(value: { isEmpty?: () => boolean; length?: number }, what: string) { if (isEmpty(value)) { throw new errors.ErrInvariantFailed(`${what} is empty`); } } -export function guardEmpty(value: { isEmpty?: () => boolean, length?: number }, what: string) { +export function guardEmpty(value: { isEmpty?: () => boolean; length?: number }, what: string) { if (!isEmpty(value)) { throw new errors.ErrInvariantFailed(`${what} is not empty`); } } -export function isEmpty(value: { isEmpty?: () => boolean, length?: number }): boolean { +export function isEmpty(value: { isEmpty?: () => boolean; length?: number }): boolean { if (value.isEmpty) { return value.isEmpty(); } From 75a131c9ae2fb6a9d4c17242ca8f4a17527c1b31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrei=20B=C4=83ncioiu?= Date: Fri, 2 Feb 2024 12:59:49 +0200 Subject: [PATCH 2/3] Add editor config. --- .editorconfig | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..25437d3b --- /dev/null +++ b/.editorconfig @@ -0,0 +1,11 @@ +# See: https://EditorConfig.org +# VSCode plugin: https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 From c3c1a2f357658bdd71da1eb6958057a1ac45f125 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrei=20B=C4=83ncioiu?= Date: Fri, 2 Feb 2024 13:38:29 +0200 Subject: [PATCH 3/3] Disable eslint formatting rules (prettier wins). --- .eslintrc.js | 28 ++---- .vscode/settings.json | 10 +- package-lock.json | 97 ++++--------------- package.json | 5 +- src/tokenOperations/tokenOperationsFactory.ts | 10 +- 5 files changed, 44 insertions(+), 106 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index b822dafb..c2294fc7 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -5,23 +5,12 @@ module.exports = { sourceType: "module", }, plugins: ["@typescript-eslint/eslint-plugin"], - extends: [ - "plugin:@typescript-eslint/eslint-recommended", - "plugin:@typescript-eslint/recommended", - "prettier" - ], + extends: ["plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended", "prettier"], root: true, env: { - node: true + node: true, }, - ignorePatterns: [ - ".eslintrc.js", - "node_modules", - "out", - "out-tests", - "out-browser", - "out-browser-tests", - ], + ignorePatterns: [".eslintrc.js", "node_modules", "out", "out-tests", "out-browser", "out-browser-tests"], rules: { "@typescript-eslint/interface-name-prefix": "off", "@typescript-eslint/explicit-function-return-type": "off", @@ -34,10 +23,13 @@ module.exports = { "@typescript-eslint/no-namespace": "warn", "@typescript-eslint/no-var-requires": "warn", "@typescript-eslint/no-empty-function": "off", - "@typescript-eslint/no-unused-vars": ["warn", { - "argsIgnorePattern": "^_", - "varsIgnorePattern": "^_" - }], + "@typescript-eslint/no-unused-vars": [ + "warn", + { + argsIgnorePattern: "^_", + varsIgnorePattern: "^_", + }, + ], "prefer-const": "off", }, }; diff --git a/.vscode/settings.json b/.vscode/settings.json index 7a73a41b..e5c7eee4 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,2 +1,10 @@ { -} \ No newline at end of file + "editor.formatOnSave": true, + "editor.formatOnSaveMode": "file", + "[javascript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[typescript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + } +} diff --git a/package-lock.json b/package-lock.json index 51031e87..5430da97 100644 --- a/package-lock.json +++ b/package-lock.json @@ -33,11 +33,10 @@ "browserify": "17.0.0", "chai": "4.2.0", "eslint": "8.28.0", - "eslint-config-prettier": "8.5.0", - "eslint-plugin-prettier": "3.4.1", + "eslint-config-prettier": "9.1.0", "esmify": "2.1.1", "mocha": "9.2.2", - "prettier": "2.2.1", + "prettier": "3.2.4", "ts-node": "9.1.1", "typescript": "4.1.2" } @@ -2561,9 +2560,9 @@ } }, "node_modules/eslint-config-prettier": { - "version": "8.5.0", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.5.0.tgz", - "integrity": "sha512-obmWKLUNCnhtQRKc+tmnYuQl0pFU1ibYJQ5BGhTVB08bHe9wC8qUeG7c08dj9XX+AuPj1YSGSQIHl1pnDHZR0Q==", + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz", + "integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==", "dev": true, "bin": { "eslint-config-prettier": "bin/cli.js" @@ -2572,27 +2571,6 @@ "eslint": ">=7.0.0" } }, - "node_modules/eslint-plugin-prettier": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-3.4.1.tgz", - "integrity": "sha512-htg25EUYUeIhKHXjOinK4BgCcDwtLHjqaxCDsMy5nbnUMkKFvIhMVCp+5GFUXQ4Nr8lBsPqtGAqBenbpFqAA2g==", - "dev": true, - "dependencies": { - "prettier-linter-helpers": "^1.0.0" - }, - "engines": { - "node": ">=6.0.0" - }, - "peerDependencies": { - "eslint": ">=5.0.0", - "prettier": ">=1.13.0" - }, - "peerDependenciesMeta": { - "eslint-config-prettier": { - "optional": true - } - } - }, "node_modules/eslint-scope": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", @@ -2911,12 +2889,6 @@ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "dev": true }, - "node_modules/fast-diff": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.3.0.tgz", - "integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==", - "dev": true - }, "node_modules/fast-glob": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", @@ -4608,27 +4580,18 @@ } }, "node_modules/prettier": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.2.1.tgz", - "integrity": "sha512-PqyhM2yCjg/oKkFPtTGUojv7gnZAoG80ttl45O6x2Ug/rMJw4wcc9k6aaf2hibP7BGVCCM33gZoGjyvt9mm16Q==", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.4.tgz", + "integrity": "sha512-FWu1oLHKCrtpO1ypU6J0SbK2d9Ckwysq6bHj/uaCP26DxrPpppCLQRGVuqAxSTvhF00AcvDRyYrLNW7ocBhFFQ==", "dev": true, "bin": { - "prettier": "bin-prettier.js" + "prettier": "bin/prettier.cjs" }, "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/prettier-linter-helpers": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz", - "integrity": "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==", - "dev": true, - "dependencies": { - "fast-diff": "^1.1.2" + "node": ">=14" }, - "engines": { - "node": ">=6.0.0" + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" } }, "node_modules/process": { @@ -7801,21 +7764,12 @@ } }, "eslint-config-prettier": { - "version": "8.5.0", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.5.0.tgz", - "integrity": "sha512-obmWKLUNCnhtQRKc+tmnYuQl0pFU1ibYJQ5BGhTVB08bHe9wC8qUeG7c08dj9XX+AuPj1YSGSQIHl1pnDHZR0Q==", + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz", + "integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==", "dev": true, "requires": {} }, - "eslint-plugin-prettier": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-3.4.1.tgz", - "integrity": "sha512-htg25EUYUeIhKHXjOinK4BgCcDwtLHjqaxCDsMy5nbnUMkKFvIhMVCp+5GFUXQ4Nr8lBsPqtGAqBenbpFqAA2g==", - "dev": true, - "requires": { - "prettier-linter-helpers": "^1.0.0" - } - }, "eslint-scope": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", @@ -7954,12 +7908,6 @@ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "dev": true }, - "fast-diff": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.3.0.tgz", - "integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==", - "dev": true - }, "fast-glob": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", @@ -9237,20 +9185,11 @@ "dev": true }, "prettier": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.2.1.tgz", - "integrity": "sha512-PqyhM2yCjg/oKkFPtTGUojv7gnZAoG80ttl45O6x2Ug/rMJw4wcc9k6aaf2hibP7BGVCCM33gZoGjyvt9mm16Q==", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.4.tgz", + "integrity": "sha512-FWu1oLHKCrtpO1ypU6J0SbK2d9Ckwysq6bHj/uaCP26DxrPpppCLQRGVuqAxSTvhF00AcvDRyYrLNW7ocBhFFQ==", "dev": true }, - "prettier-linter-helpers": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz", - "integrity": "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==", - "dev": true, - "requires": { - "fast-diff": "^1.1.2" - } - }, "process": { "version": "0.11.10", "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", diff --git a/package.json b/package.json index 4bc33272..83fcc1c6 100644 --- a/package.json +++ b/package.json @@ -54,8 +54,7 @@ "@typescript-eslint/eslint-plugin": "5.44.0", "@typescript-eslint/parser": "5.44.0", "eslint": "8.28.0", - "eslint-config-prettier": "8.5.0", - "eslint-plugin-prettier": "3.4.1", - "prettier": "2.2.1" + "eslint-config-prettier": "9.1.0", + "prettier": "3.2.4" } } diff --git a/src/tokenOperations/tokenOperationsFactory.ts b/src/tokenOperations/tokenOperationsFactory.ts index a55371b9..a4a4ffc5 100644 --- a/src/tokenOperations/tokenOperationsFactory.ts +++ b/src/tokenOperations/tokenOperationsFactory.ts @@ -63,7 +63,7 @@ interface IIssueSemiFungibleArgs extends IBaseArgs { canAddSpecialRoles: boolean; } -interface IIssueNonFungibleArgs extends IIssueSemiFungibleArgs { } +interface IIssueNonFungibleArgs extends IIssueSemiFungibleArgs {} interface IRegisterMetaESDT extends IIssueSemiFungibleArgs { numDecimals: number; @@ -210,7 +210,7 @@ export class TokenOperationsFactory { utf8ToHex("canUpgrade"), args.canUpgrade ? this.trueAsHex : this.falseAsHex, utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex + args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex, ]; return this.createTransaction({ @@ -254,7 +254,7 @@ Once the token is registered, you can unset this role by calling "unsetBurnRoleG utf8ToHex("canUpgrade"), args.canUpgrade ? this.trueAsHex : this.falseAsHex, utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex + args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex, ]; return this.createTransaction({ @@ -289,7 +289,7 @@ Once the token is registered, you can unset this role by calling "unsetBurnRoleG utf8ToHex("canUpgrade"), args.canUpgrade ? this.trueAsHex : this.falseAsHex, utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex + args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex, ]; return this.createTransaction({ @@ -325,7 +325,7 @@ Once the token is registered, you can unset this role by calling "unsetBurnRoleG utf8ToHex("canUpgrade"), args.canUpgrade ? this.trueAsHex : this.falseAsHex, utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex + args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex, ]; return this.createTransaction({